text
stringlengths
5
1.04M
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/hmac.h" #include <openssl/hmac.h> #include <algorithm> #include <vector> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "crypto/openssl_util.h" namespace crypto { struct HMACPlatformData { std::vector<unsigned char> key; }; HMAC::HMAC(HashAlgorithm hash_alg) : hash_alg_(hash_alg), plat_(new HMACPlatformData()) { // Only SHA-1 and SHA-256 hash algorithms are supported now. DCHECK(hash_alg_ == SHA1 || hash_alg_ == SHA256); } bool HMAC::Init(const unsigned char* key, size_t key_length) { // Init must not be called more than once on the same HMAC object. DCHECK(plat_->key.empty()); plat_->key.assign(key, key + key_length); return true; } HMAC::~HMAC() { // Zero out key copy. plat_->key.assign(plat_->key.size(), 0); STLClearObject(&plat_->key); } bool HMAC::Sign(const base::StringPiece& data, unsigned char* digest, size_t digest_length) const { DCHECK(!plat_->key.empty()); // Init must be called before Sign. ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length); return ::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(), &plat_->key[0], plat_->key.size(), reinterpret_cast<const unsigned char*>(data.data()), data.size(), result.safe_buffer(), NULL); } } // namespace crypto
/* * Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st> * SPI Master library for arduino. * * This file is free software; you can redistribute it and/or modify * it under the terms of either the GNU General Public License version 2 * or the GNU Lesser General Public License version 2.1, both as * published by the Free Software Foundation. */ #include "pins_arduino.h" #include "SPI.h" SPIClass SPI; #if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) // see http://gammon.com.au/spi # define DI 0 // D0, pin 5 Data In # define DO 1 // D1, pin 6 Data Out (this is *not* MOSI) # define USCK 2 // D2, pin 7 Universal Serial Interface clock # define SS 3 // D3, pin 2 Slave Select #elif defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) // these depend on the core used (check pins_arduino.h) // this is for jeelabs' one (based on google-code core) # define DI 4 // PA6 # define DO 5 // PA5 # define USCK 6 // PA4 # define SS 3 // PA7 #endif void SPIClass::begin() { #if defined(SPCR) // Set SS to high so a connected chip will be "deselected" by default digitalWrite(SS, HIGH); // When the SS pin is set as OUTPUT, it can be used as // a general purpose output port (it doesn't influence // SPI operations). pinMode(SS, OUTPUT); // Warning: if the SS pin ever becomes a LOW INPUT then SPI // automatically switches to Slave, so the data direction of // the SS pin MUST be kept as OUTPUT. SPCR |= _BV(MSTR); SPCR |= _BV(SPE); // Set direction register for SCK and MOSI pin. // MISO pin automatically overrides to INPUT. // By doing this AFTER enabling SPI, we avoid accidentally // clocking in a single bit since the lines go directly // from "input" to SPI control. // http://code.google.com/p/arduino/issues/detail?id=888 pinMode(SCK, OUTPUT); pinMode(MOSI, OUTPUT); #else digitalWrite(SS, HIGH); pinMode(USCK, OUTPUT); pinMode(DO, OUTPUT); pinMode(SS, OUTPUT); pinMode(DI, INPUT); USICR = _BV(USIWM0); #endif } byte SPIClass::transfer(byte b) { #if defined(SPCR) SPDR = b; while (!(SPSR & _BV(SPIF))) ; return SPDR; #else USIDR = b; USISR = _BV(USIOIF); do USICR = _BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC); while ((USISR & _BV(USIOIF)) == 0); return USIDR; #endif } void SPIClass::end() { #if defined(SPCR) SPCR &= ~_BV(SPE); #endif } void SPIClass::setBitOrder(uint8_t bitOrder) { #if defined(SPCR) if(bitOrder == LSBFIRST) { SPCR |= _BV(DORD); } else { SPCR &= ~(_BV(DORD)); } #endif } void SPIClass::setDataMode(uint8_t mode) { #if defined(SPCR) SPCR = (SPCR & ~SPI_MODE_MASK) | mode; #endif } void SPIClass::setClockDivider(uint8_t rate) { #if defined(SPCR) SPCR = (SPCR & ~SPI_CLOCK_MASK) | (rate & SPI_CLOCK_MASK); SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((rate >> 2) & SPI_2XCLOCK_MASK); #endif }
/** * * NermalProxy * * Copyright 2019 Mark Slevinsky * * 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 of the copyright holder 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 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. */ #pragma once #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <list> #include <string> #include "Log.hpp" /** * @brief The MultiValueAttribute class implements a data structure * containing one key, and 0 or more values. */ class MultiValueAttribute { public: MultiValueAttribute(const std::string& name); void AddValue(const std::string& value); const std::string& GetName(); bool GetValue(const int index, std::string& value); std::string GetValue(); int GetCount(); public: std::string m_name; std::list<std::string> m_values; }; /** * @brief The ConfigSection class implements a collection of * configuration data attributes. */ class ConfigSection { public: ConfigSection(const std::string& sectionName); const std::string& GetName(); MultiValueAttribute& GetAttribute(const std::string& attribute); MultiValueAttribute* GetAttribute(int idx); private: std::string m_name; std::list<MultiValueAttribute> m_attributes; }; /** * @brief The ConfigData class represents the program configuration data, * as a collection of sections, each containing unique attributes. */ class ConfigData { public: ConfigSection& AddSection(const std::string& name); ConfigSection& FindSection(const std::string& name); private: std::list<ConfigSection> m_sections; }; /** * @brief The ConfigFile class loads a file with a given format into a * ConfigData object. */ class ConfigFile { public: ConfigFile(const std::string& path); void LoadData(); ConfigSection& GetSection(const std::string& name); private: std::string m_path; ConfigData m_data; };
// // posix/stream_descriptor.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_POSIX_STREAM_DESCRIPTOR_HPP #define BOOST_ASIO_POSIX_STREAM_DESCRIPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/posix/descriptor.hpp> #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ || defined(GENERATING_DOCUMENTATION) #if defined(BOOST_ASIO_ENABLE_OLD_SERVICES) # include <boost/asio/posix/basic_stream_descriptor.hpp> #endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES) namespace boost { namespace asio { namespace posix { #if defined(BOOST_ASIO_ENABLE_OLD_SERVICES) // Typedef for the typical usage of a stream-oriented descriptor. typedef basic_stream_descriptor<> stream_descriptor; #else // defined(BOOST_ASIO_ENABLE_OLD_SERVICES) /// Provides stream-oriented descriptor functionality. /** * The posix::stream_descriptor class template provides asynchronous and * blocking stream-oriented descriptor functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ class stream_descriptor : public descriptor { public: /// Construct a stream_descriptor without opening it. /** * This constructor creates a stream descriptor without opening it. The * descriptor needs to be opened and then connected or accepted before data * can be sent or received on it. * * @param io_context The io_context object that the stream descriptor will * use to dispatch handlers for any asynchronous operations performed on the * descriptor. */ explicit stream_descriptor(boost::asio::io_context& io_context) : descriptor(io_context) { } /// Construct a stream_descriptor on an existing native descriptor. /** * This constructor creates a stream descriptor object to hold an existing * native descriptor. * * @param io_context The io_context object that the stream descriptor will * use to dispatch handlers for any asynchronous operations performed on the * descriptor. * * @param native_descriptor The new underlying descriptor implementation. * * @throws boost::system::system_error Thrown on failure. */ stream_descriptor(boost::asio::io_context& io_context, const native_handle_type& native_descriptor) : descriptor(io_context, native_descriptor) { } #if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a stream_descriptor from another. /** * This constructor moves a stream descriptor from one object to another. * * @param other The other stream_descriptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c stream_descriptor(io_context&) constructor. */ stream_descriptor(stream_descriptor&& other) : descriptor(std::move(other)) { } /// Move-assign a stream_descriptor from another. /** * This assignment operator moves a stream descriptor from one object to * another. * * @param other The other stream_descriptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c stream_descriptor(io_context&) constructor. */ stream_descriptor& operator=(stream_descriptor&& other) { descriptor::operator=(std::move(other)); return *this; } #endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Write some data to the descriptor. /** * This function is used to write data to the stream descriptor. The function * call will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the descriptor. * * @returns The number of bytes written. * * @throws boost::system::system_error Thrown on failure. An error code of * boost::asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * descriptor.write_some(boost::asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { boost::system::error_code ec; std::size_t s = this->get_service().write_some( this->get_implementation(), buffers, ec); boost::asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the descriptor. /** * This function is used to write data to the stream descriptor. The function * call will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the descriptor. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, boost::system::error_code& ec) { return this->get_service().write_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the stream * descriptor. The function call always returns immediately. * * @param buffers One or more data buffers to be written to the descriptor. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * boost::asio::io_context::post(). * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * descriptor.async_write_some(boost::asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence, typename WriteHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (boost::system::error_code, std::size_t)) async_write_some(const ConstBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. BOOST_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; boost::asio::async_completion<WriteHandler, void (boost::system::error_code, std::size_t)> init(handler); this->get_service().async_write_some( this->get_implementation(), buffers, init.completion_handler); return init.result.get(); } /// Read some data from the descriptor. /** * This function is used to read data from the stream descriptor. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws boost::system::system_error Thrown on failure. An error code of * boost::asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * descriptor.read_some(boost::asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { boost::system::error_code ec; std::size_t s = this->get_service().read_some( this->get_implementation(), buffers, ec); boost::asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the descriptor. /** * This function is used to read data from the stream descriptor. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, boost::system::error_code& ec) { return this->get_service().read_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the stream * descriptor. The function call always returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * boost::asio::io_context::post(). * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * descriptor.async_read_some(boost::asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (boost::system::error_code, std::size_t)) async_read_some(const MutableBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. BOOST_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; boost::asio::async_completion<ReadHandler, void (boost::system::error_code, std::size_t)> init(handler); this->get_service().async_read_some( this->get_implementation(), buffers, init.completion_handler); return init.result.get(); } }; #endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES) } // namespace posix } // namespace asio } // namespace boost #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_POSIX_STREAM_DESCRIPTOR_HPP
#include "ofxPatches/Manager.h" using namespace ofxPatches; Manager::Manager(){ name = "Manager"; filename = ""; output = NULL; manager = this; allowBypass = false; fragmentShader = "void main(void){}"; } Manager::~Manager(){ } void Manager::setup(int nSources, string name, string filename){ nSources ++; // one extra texture to use as output if(name.compare("")){ this->name = name; } if(filename.compare("")){ this->filename = filename; } if(!this->filename.compare("")){ this->filename = this->name + ".xml"; } baseFolder = OFX_PATCHES_SETTINGS_FOLDER + ofFilePath::removeExt(this->filename) + "/"; ofDirectory::createDirectory(baseFolder, true, true); this->filename = baseFolder + this->filename; fragmentShader = "void main(void){}"; for (int i = 0; i < nSources; i ++) { fragmentShader += string("uniform sampler2DRect tex" + ofToString(i) +"; "); } gui.setup(this->name, this->filename); gui.setSize(OFX_PATCHES_GUI_SIZE); gui.setPosition(20, 20); gui.clear(); // Add th load / save buttons ofxButton * saveSettingsButton = new ofxButton(); saveSettingsButton->setup("Save",OFX_PATCHES_GUI_SIZE); saveSettingsButton->addListener(this, &Manager::onSaveSettings); gui.add(saveSettingsButton); ofxButton * loadSettingsButton = new ofxButton(); loadSettingsButton->setup("Load",OFX_PATCHES_GUI_SIZE); loadSettingsButton->addListener(this, &Manager::onLoadSettings); gui.add(loadSettingsButton); // Add the edit toogle ofxToggle * editToogle = new ofxToggle(); editToogle->setup("Edit", true, OFX_PATCHES_GUI_SIZE); editToogle->addListener(this, &Manager::onEdit); gui.add(editToogle); // Add the preview slider ofxFloatSlider * previewSlider = new ofxFloatSlider(); previewSlider->setup("Preview Scale", 0.25, 0., 1., OFX_PATCHES_GUI_SIZE); previewSlider->addListener((Patch*)this, &Patch::onPreviewScaleChange); gui.add(previewSlider); patchesGui.setup("Patches", baseFolder + "patches_gui.xml"); patchesGui.setSize(OFX_PATCHES_GUI_SIZE); patchesGui.setPosition(gui.getShape().x+ gui.getShape().width + 2, 20); } bool Manager::compileCode(){ unregisterAllPatches(); bool compileSuccess = ofxFXObject::compileCode(); patchesGui.clear(); for (int i = 0; i < nTextures - 1; i ++) { Patch * patch = new FixedSource(&(textures[i]), string("Source " + ofToString(i))); ofxButton * patchButton = new ofxButton(); patchButton->setup(patch->getName(),OFX_PATCHES_GUI_SIZE); ManagerPatchGUIHandler * handler = new ManagerPatchGUIHandler(this, registeredPatches.size()); patchButton->addListener(handler, &ManagerPatchGUIHandler::onPatchButton); registeredPatches.push_back(patch); patchesGui.add(patchButton); registeredPatchesHandlers.push_back(handler); } // The one and only input, that will be used when we want to plug // in the last patch in the system inputs.clear(); inputs.push_back(new PatchInput(this, NULL, 0)); return compileSuccess; } void Manager::unregisterAllPatches(){ while (registeredPatches.size()) { delete registeredPatches[registeredPatches.size()-1]; registeredPatches.pop_back(); } while (registeredPatchesHandlers.size()) { delete registeredPatchesHandlers[registeredPatchesHandlers.size()-1]; registeredPatchesHandlers.pop_back(); } } Patch * Manager::getPatchById(int id){ for (int i = 0; i < currentPatches.size(); i++) { if(currentPatches[i]->getId() == id){ return currentPatches[i]; break; } } return NULL; } int Manager::getPatchLabelById(int id){ for (int i = 0; i < currentPatches.size(); i++) { if(currentPatches[i]->getId() == id){ return i; break; } } return -1; } vector<Patch*> Manager::getPatchesByName(string name){ vector<Patch*> patches = vector<Patch*>(); for (int i = 0; i < currentPatches.size(); i++) { if(currentPatches[i]->getName().compare(name)){ patches.push_back(currentPatches[i]); } } return patches; } void Manager::addPatch(int label, int id){ if (label < 0 || label >= registeredPatches.size()) { ofLogWarning("Manager: Can't add Patch (label \"" + ofToString(label) + "\"). It is not registered."); return; } Patch * patch = registeredPatches[label]->create(); patch->setup(this, patch->getName(), string(ofToString(id) + ".xml"), id); patch->setLabel(label); patch->allocate(width, height, internalFormat); patch->setGUIPosition(ofGetWidth()/2 - patch->gui.getShape().width / 2 + currentPatches.size() * 14, ofGetHeight()/2 - patch->gui.getShape().height / 2 + currentPatches.size() * 14); currentPatches.push_back(patch); } void Manager::addPatch(string name, int id){ Patch * patch = NULL; int label; for (int i = 0; i < registeredPatches.size(); i++) { if(name.compare(registeredPatches[i]->name) == 0){ patch = registeredPatches[i]->create(); label = i; break; } } if(!patch){ ofLogWarning("Manager: Can't add Patch (name \"" + name + "\"). It is not registered."); return; } patch->setup(this, patch->getName(), string(ofToString(id) + ".xml"), id); patch->setLabel(label); patch->allocate(width, height, internalFormat); patch->setGUIPosition(ofGetWidth()/2 - patch->gui.getShape().width / 2 + currentPatches.size() * 14, ofGetHeight()/2 - patch->gui.getShape().height / 2 + currentPatches.size() * 14); currentPatches.push_back(patch); } void Manager::removePatch(int id){ int label = getPatchLabelById(id); if(label == -1) return; Patch * patch = currentPatches[label]; // swap with the last! Patch * lastPatch = currentPatches[currentPatches.size()-1]; currentPatches[label] = lastPatch; currentPatches[currentPatches.size()-1] = patch; // remove the settings file //ofFile::removeFile(patch->filename); // store patch for garbage collection (we can't delete them immediately // as that will cause the gui mutex to go bananas) garbageCollection.push_back(currentPatches[currentPatches.size()-1]); // remove patch from collection currentPatches.pop_back(); // loop through all the remaining patches and remove the connector for (int i = 0; i < currentPatches.size(); i++) { for (int j = 0; j < currentPatches[i]->inputs.size(); j++) { if(currentPatches[i]->inputs[j]->patch){ if(currentPatches[i]->inputs[j]->patch->id == id){ currentPatches[i]->inputs[j]->patch = NULL; } } } } // also check if the patch was connecte to the manager itself for (int i = 0; i < inputs.size(); i++) { if(inputs[i]->patch){ if(inputs[i]->patch->id == id){ inputs[i]->patch = NULL; } } } } void Manager::update(){ for (int i = 0; i < currentPatches.size(); i++){ currentPatches[i]->update(); } if(inputs[0]->getPatch()) setTexture(inputs[0]->getPatch()->getTexture(), nTextures-1); else { begin(nTextures-1); ofPushStyle(); ofSetColor(255,10,10); ofDrawRectangle(0,0,width,height); ofPopStyle(); end(nTextures-1); } pingPong.dst->begin(); ofClear(0,0,0,0); textures[nTextures-1].draw(0, 0, width, height); pingPong.dst->end(); pingPong.swap(); pingPong.swap(); // Garbage disposal int garbageIndex = garbageCollection.size() - 1; while (garbageIndex > 0) { delete garbageCollection[garbageIndex]; garbageCollection.pop_back(); garbageIndex = garbageCollection.size() - 1; } } void Manager::drawGUI(){ ExtendedFXObject::drawGUI(); if(previewScale > 0) { draw(gui.getShape().x, gui.getShape().y + gui.getShape().height, width*previewScale, height*previewScale); } if(editing){ if(output) output->draw(); for (int i = 0; i < inputs.size(); i++) { inputs[i]->draw(); } patchesGui.draw(); for (int i = 0; i < currentPatches.size(); i++) { currentPatches[i]->drawGUI(); } } } void Manager::setGUIPosition(float x, float y){ gui.setPosition(x, y); } void Manager::setPatchesGUIPosition(float x, float y){ patchesGui.setPosition(x, y); } void Manager::applyGuiValues(){ Patch::applyGuiValues(); bool edit = gui.getToggle("Edit"); onEdit(edit); } string Manager::getBaseFolder(){ return baseFolder; } void Manager::saveSettings(){ // make sure dir exists ofDirectory::createDirectory(baseFolder, true, true); // Save gui gui.saveToFile(filename); // Create the main settings xml ofxXmlSettings settings; // Save the current input settings.addTag("inputs"); if(inputs.size()){ settings.pushTag("inputs"); for (int i = 0; i < inputs.size(); i++) { if(inputs[i]->getPatch()){ settings.addTag("id"); settings.setValue("id", inputs[i]->getPatch()->getId(), i); } } settings.popTag(); } // Save the current position settings.addTag("gui_position"); settings.pushTag("gui_position"); settings.addTag("x"); settings.setValue("x", gui.getPosition().x); settings.addTag("y"); settings.setValue("y", gui.getPosition().y); settings.popTag(); settings.addTag("patches_gui_position"); settings.pushTag("patches_gui_position"); settings.addTag("x"); settings.setValue("x", patchesGui.getPosition().x); settings.addTag("y"); settings.setValue("y", patchesGui.getPosition().y); settings.popTag(); // Save all the patches settings.addTag("patches"); settings.pushTag("patches"); for (int i = 0; i < currentPatches.size(); i++) { // Save each individual internal settings currentPatches[i]->saveSettings(); settings.addTag("patch"); settings.pushTag("patch", i); settings.addTag("id"); settings.setValue("id", currentPatches[i]->getId()); settings.addTag("name"); settings.setValue("name", currentPatches[i]->getName()); settings.addTag("gui_position"); settings.pushTag("gui_position"); settings.addTag("x"); settings.setValue("x", currentPatches[i]->gui.getPosition().x); settings.addTag("y"); settings.setValue("y", currentPatches[i]->gui.getPosition().y); settings.popTag(); settings.addTag("inputs"); settings.pushTag("inputs"); for (int j = 0; j < currentPatches[i]->inputs.size(); j++) { if(currentPatches[i]->inputs[j]->getPatch()){ settings.addTag("id"); settings.setValue("id", currentPatches[i]->inputs[j]->getPatch()->getId(), j); } } settings.popTag(); settings.popTag(); } settings.popTag(); // Save the file settings.saveFile(baseFolder + "_settings.xml"); } void Manager::loadSettings(){ // Load the gui gui.loadFromFile(filename); applyGuiValues(); // Open the xml file (and if it's not there, return early) ofxXmlSettings settings; if(!settings.loadFile(baseFolder + "_settings.xml")) return; // Set the position setGUIPosition(settings.getValue("gui_position:x", 0.0), settings.getValue("gui_position:y", 0.0)); setPatchesGUIPosition(settings.getValue("patches_gui_position:x", 0.0), settings.getValue("patches_gui_position:y", 0.0)); // Create each of the patches while (currentPatches.size()) { removePatch(currentPatches[currentPatches.size()-1]->getId()); } settings.pushTag("patches"); for (int i = 0; i < settings.getNumTags("patch"); i++) { settings.pushTag("patch", i); // create the patch addPatch(settings.getValue("name", ""), settings.getValue("id", -1)); // load the internal settings currentPatches[i]->loadSettings(); // set the position currentPatches[i]->setGUIPosition(settings.getValue("gui_position:x", 0.0), settings.getValue("gui_position:y", 0.0)); settings.popTag(); } settings.popTag(); // Only now that all the patches were created, we can set the inputs settings.pushTag("patches"); for (int i = 0; i < settings.getNumTags("patch"); i++) { settings.pushTag("patch", i);; settings.pushTag("inputs"); for (int j = 0; j < settings.getNumTags("id"); j++) { currentPatches[i]->setInput(getPatchById(settings.getValue("id", -1, j)), j); } settings.popTag(); settings.popTag(); } settings.popTag(); settings.pushTag("inputs"); for (int i = 0; i < settings.getNumTags("id"); i++) { setInput(getPatchById(settings.getValue("id", -1, i)), i); } settings.popTag(); } void Manager::onSaveSettings(){ saveSettings(); } void Manager::onLoadSettings(){ loadSettings(); } void Manager::onEdit(bool & value){ if(value){ enableEditing(); } else{ disableEditing(); } } void Manager::toggleEditing(){ if(editing) disableEditing(); else enableEditing(); } void Manager::enableEditing(){ editing = true; } void Manager::disableEditing(){ editing = false; } bool Manager::isEditing(){ return editing; }
#include "uritests.h" #include "../guiutil.h" #include "../walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString("Wikipedia Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Wikipedia Example")); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("newyorkc://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); // We currently don't implement the message parameter (ok, yea, we break spec...) uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("newyorkc:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); }
// Copyright John Maddock 2005-2008. // Copyright (c) 2006-2008 Johan Rade // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_FPCLASSIFY_HPP #define BOOST_MATH_FPCLASSIFY_HPP #ifdef _MSC_VER #pragma once #endif #include <math.h> #include <boost/config/no_tr1/cmath.hpp> #include <boost/limits.hpp> #include <boost/math/tools/real_cast.hpp> #include <boost/type_traits/is_floating_point.hpp> #include <boost/math/special_functions/math_fwd.hpp> #include <boost/math/special_functions/detail/fp_traits.hpp> /*! \file fpclassify.hpp \brief Classify floating-point value as normal, subnormal, zero, infinite, or NaN. \version 1.0 \author John Maddock */ /* 1. If the platform is C99 compliant, then the native floating point classification functions are used. However, note that we must only define the functions which call std::fpclassify etc if that function really does exist: otherwise a compiler may reject the code even though the template is never instantiated. 2. If the platform is not C99 compliant, and the binary format for a floating point type (float, double or long double) can be determined at compile time, then the following algorithm is used: If all exponent bits, the flag bit (if there is one), and all significand bits are 0, then the number is zero. If all exponent bits and the flag bit (if there is one) are 0, and at least one significand bit is 1, then the number is subnormal. If all exponent bits are 1 and all significand bits are 0, then the number is infinity. If all exponent bits are 1 and at least one significand bit is 1, then the number is a not-a-number. Otherwise the number is normal. This algorithm works for the IEEE 754 representation, and also for several non IEEE 754 formats. Most formats have the structure sign bit + exponent bits + significand bits. A few have the structure sign bit + exponent bits + flag bit + significand bits. The flag bit is 0 for zero and subnormal numbers, and 1 for normal numbers and NaN. It is 0 (Motorola 68K) or 1 (Intel) for infinity. To get the bits, the four or eight most significant bytes are copied into an uint32_t or uint64_t and bit masks are applied. This covers all the exponent bits and the flag bit (if there is one), but not always all the significand bits. Some of the functions below have two implementations, depending on whether all the significand bits are copied or not. 3. If the platform is not C99 compliant, and the binary format for a floating point type (float, double or long double) can not be determined at compile time, then comparison with std::numeric_limits values is used. */ #if defined(_MSC_VER) || defined(__BORLANDC__) #include <float.h> #endif #ifdef BOOST_NO_STDC_NAMESPACE namespace std{ using ::abs; using ::fabs; } #endif namespace boost{ // // This must not be located in any namespace under boost::math // otherwise we can get into an infinite loop if isnan is // a #define for "isnan" ! // namespace math_detail{ #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable:4800) #endif template <class T> inline bool is_nan_helper(T t, const boost::true_type&) { #ifdef isnan return isnan(t); #elif defined(BOOST_MATH_DISABLE_STD_FPCLASSIFY) || !defined(BOOST_HAS_FPCLASSIFY) (void)t; return false; #else // BOOST_HAS_FPCLASSIFY return (BOOST_FPCLASSIFY_PREFIX fpclassify(t) == (int)FP_NAN); #endif } #ifdef BOOST_MSVC #pragma warning(pop) #endif template <class T> inline bool is_nan_helper(T, const boost::false_type&) { return false; } } namespace math{ namespace detail{ #ifdef BOOST_MATH_USE_STD_FPCLASSIFY template <class T> inline int fpclassify_imp BOOST_NO_MACRO_EXPAND(T t, const native_tag&) { return (std::fpclassify)(t); } #endif template <class T> inline int fpclassify_imp BOOST_NO_MACRO_EXPAND(T t, const generic_tag<true>&) { BOOST_MATH_INSTRUMENT_VARIABLE(t); // whenever possible check for Nan's first: #if defined(BOOST_HAS_FPCLASSIFY) && !defined(BOOST_MATH_DISABLE_STD_FPCLASSIFY) if(::boost::math_detail::is_nan_helper(t, ::boost::is_floating_point<T>())) return FP_NAN; #elif defined(isnan) if(boost::math_detail::is_nan_helper(t, ::boost::is_floating_point<T>())) return FP_NAN; #elif defined(_MSC_VER) || defined(__BORLANDC__) if(::_isnan(boost::math::tools::real_cast<double>(t))) return FP_NAN; #endif // std::fabs broken on a few systems especially for long long!!!! T at = (t < T(0)) ? -t : t; // Use a process of exclusion to figure out // what kind of type we have, this relies on // IEEE conforming reals that will treat // Nan's as unordered. Some compilers // don't do this once optimisations are // turned on, hence the check for nan's above. if(at <= (std::numeric_limits<T>::max)()) { if(at >= (std::numeric_limits<T>::min)()) return FP_NORMAL; return (at != 0) ? FP_SUBNORMAL : FP_ZERO; } else if(at > (std::numeric_limits<T>::max)()) return FP_INFINITE; return FP_NAN; } template <class T> inline int fpclassify_imp BOOST_NO_MACRO_EXPAND(T t, const generic_tag<false>&) { #ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS if(std::numeric_limits<T>::is_specialized) return fpclassify_imp(t, generic_tag<true>()); #endif // // An unknown type with no numeric_limits support, // so what are we supposed to do we do here? // BOOST_MATH_INSTRUMENT_VARIABLE(t); return t == 0 ? FP_ZERO : FP_NORMAL; } template<class T> int fpclassify_imp BOOST_NO_MACRO_EXPAND(T x, ieee_copy_all_bits_tag) { typedef BOOST_DEDUCED_TYPENAME fp_traits<T>::type traits; BOOST_MATH_INSTRUMENT_VARIABLE(x); BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); BOOST_MATH_INSTRUMENT_VARIABLE(a); a &= traits::exponent | traits::flag | traits::significand; BOOST_MATH_INSTRUMENT_VARIABLE((traits::exponent | traits::flag | traits::significand)); BOOST_MATH_INSTRUMENT_VARIABLE(a); if(a <= traits::significand) { if(a == 0) return FP_ZERO; else return FP_SUBNORMAL; } if(a < traits::exponent) return FP_NORMAL; a &= traits::significand; if(a == 0) return FP_INFINITE; return FP_NAN; } template<class T> int fpclassify_imp BOOST_NO_MACRO_EXPAND(T x, ieee_copy_leading_bits_tag) { typedef BOOST_DEDUCED_TYPENAME fp_traits<T>::type traits; BOOST_MATH_INSTRUMENT_VARIABLE(x); BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); a &= traits::exponent | traits::flag | traits::significand; if(a <= traits::significand) { if(x == 0) return FP_ZERO; else return FP_SUBNORMAL; } if(a < traits::exponent) return FP_NORMAL; a &= traits::significand; traits::set_bits(x,a); if(x == 0) return FP_INFINITE; return FP_NAN; } #if defined(BOOST_MATH_USE_STD_FPCLASSIFY) && (defined(BOOST_MATH_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY) || defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS)) inline int fpclassify_imp BOOST_NO_MACRO_EXPAND(long double t, const native_tag&) { return boost::math::detail::fpclassify_imp(t, generic_tag<true>()); } #endif } // namespace detail template <class T> inline int fpclassify BOOST_NO_MACRO_EXPAND(T t) { typedef typename detail::fp_traits<T>::type traits; typedef typename traits::method method; typedef typename tools::promote_args_permissive<T>::type value_type; #ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS if(std::numeric_limits<T>::is_specialized && detail::is_generic_tag_false(static_cast<method*>(0))) return detail::fpclassify_imp(static_cast<value_type>(t), detail::generic_tag<true>()); return detail::fpclassify_imp(static_cast<value_type>(t), method()); #else return detail::fpclassify_imp(static_cast<value_type>(t), method()); #endif } #ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS template <> inline int fpclassify<long double> BOOST_NO_MACRO_EXPAND(long double t) { typedef detail::fp_traits<long double>::type traits; typedef traits::method method; typedef long double value_type; #ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS if(std::numeric_limits<long double>::is_specialized && detail::is_generic_tag_false(static_cast<method*>(0))) return detail::fpclassify_imp(static_cast<value_type>(t), detail::generic_tag<true>()); return detail::fpclassify_imp(static_cast<value_type>(t), method()); #else return detail::fpclassify_imp(static_cast<value_type>(t), method()); #endif } #endif namespace detail { #ifdef BOOST_MATH_USE_STD_FPCLASSIFY template<class T> inline bool isfinite_impl(T x, native_tag const&) { return (std::isfinite)(x); } #endif template<class T> inline bool isfinite_impl(T x, generic_tag<true> const&) { return x >= -(std::numeric_limits<T>::max)() && x <= (std::numeric_limits<T>::max)(); } template<class T> inline bool isfinite_impl(T x, generic_tag<false> const&) { #ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS if(std::numeric_limits<T>::is_specialized) return isfinite_impl(x, generic_tag<true>()); #endif (void)x; // warning supression. return true; } template<class T> inline bool isfinite_impl(T x, ieee_tag const&) { typedef BOOST_DEDUCED_TYPENAME detail::fp_traits<T>::type traits; BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); a &= traits::exponent; return a != traits::exponent; } #if defined(BOOST_MATH_USE_STD_FPCLASSIFY) && defined(BOOST_MATH_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY) inline bool isfinite_impl BOOST_NO_MACRO_EXPAND(long double t, const native_tag&) { return boost::math::detail::isfinite_impl(t, generic_tag<true>()); } #endif } template<class T> inline bool (isfinite)(T x) { //!< \brief return true if floating-point type t is finite. typedef typename detail::fp_traits<T>::type traits; typedef typename traits::method method; // typedef typename boost::is_floating_point<T>::type fp_tag; typedef typename tools::promote_args_permissive<T>::type value_type; return detail::isfinite_impl(static_cast<value_type>(x), method()); } #ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS template<> inline bool (isfinite)(long double x) { //!< \brief return true if floating-point type t is finite. typedef detail::fp_traits<long double>::type traits; typedef traits::method method; //typedef boost::is_floating_point<long double>::type fp_tag; typedef long double value_type; return detail::isfinite_impl(static_cast<value_type>(x), method()); } #endif //------------------------------------------------------------------------------ namespace detail { #ifdef BOOST_MATH_USE_STD_FPCLASSIFY template<class T> inline bool isnormal_impl(T x, native_tag const&) { return (std::isnormal)(x); } #endif template<class T> inline bool isnormal_impl(T x, generic_tag<true> const&) { if(x < 0) x = -x; return x >= (std::numeric_limits<T>::min)() && x <= (std::numeric_limits<T>::max)(); } template<class T> inline bool isnormal_impl(T x, generic_tag<false> const&) { #ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS if(std::numeric_limits<T>::is_specialized) return isnormal_impl(x, generic_tag<true>()); #endif return !(x == 0); } template<class T> inline bool isnormal_impl(T x, ieee_tag const&) { typedef BOOST_DEDUCED_TYPENAME detail::fp_traits<T>::type traits; BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); a &= traits::exponent | traits::flag; return (a != 0) && (a < traits::exponent); } #if defined(BOOST_MATH_USE_STD_FPCLASSIFY) && defined(BOOST_MATH_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY) inline bool isnormal_impl BOOST_NO_MACRO_EXPAND(long double t, const native_tag&) { return boost::math::detail::isnormal_impl(t, generic_tag<true>()); } #endif } template<class T> inline bool (isnormal)(T x) { typedef typename detail::fp_traits<T>::type traits; typedef typename traits::method method; //typedef typename boost::is_floating_point<T>::type fp_tag; typedef typename tools::promote_args_permissive<T>::type value_type; return detail::isnormal_impl(static_cast<value_type>(x), method()); } #ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS template<> inline bool (isnormal)(long double x) { typedef detail::fp_traits<long double>::type traits; typedef traits::method method; //typedef boost::is_floating_point<long double>::type fp_tag; typedef long double value_type; return detail::isnormal_impl(static_cast<value_type>(x), method()); } #endif //------------------------------------------------------------------------------ namespace detail { #ifdef BOOST_MATH_USE_STD_FPCLASSIFY template<class T> inline bool isinf_impl(T x, native_tag const&) { return (std::isinf)(x); } #endif template<class T> inline bool isinf_impl(T x, generic_tag<true> const&) { (void)x; // in case the compiler thinks that x is unused because std::numeric_limits<T>::has_infinity is false return std::numeric_limits<T>::has_infinity && ( x == std::numeric_limits<T>::infinity() || x == -std::numeric_limits<T>::infinity()); } template<class T> inline bool isinf_impl(T x, generic_tag<false> const&) { #ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS if(std::numeric_limits<T>::is_specialized) return isinf_impl(x, generic_tag<true>()); #endif (void)x; // warning supression. return false; } template<class T> inline bool isinf_impl(T x, ieee_copy_all_bits_tag const&) { typedef BOOST_DEDUCED_TYPENAME fp_traits<T>::type traits; BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); a &= traits::exponent | traits::significand; return a == traits::exponent; } template<class T> inline bool isinf_impl(T x, ieee_copy_leading_bits_tag const&) { typedef BOOST_DEDUCED_TYPENAME fp_traits<T>::type traits; BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); a &= traits::exponent | traits::significand; if(a != traits::exponent) return false; traits::set_bits(x,0); return x == 0; } #if defined(BOOST_MATH_USE_STD_FPCLASSIFY) && defined(BOOST_MATH_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY) inline bool isinf_impl BOOST_NO_MACRO_EXPAND(long double t, const native_tag&) { return boost::math::detail::isinf_impl(t, generic_tag<true>()); } #endif } // namespace detail template<class T> inline bool (isinf)(T x) { typedef typename detail::fp_traits<T>::type traits; typedef typename traits::method method; // typedef typename boost::is_floating_point<T>::type fp_tag; typedef typename tools::promote_args_permissive<T>::type value_type; return detail::isinf_impl(static_cast<value_type>(x), method()); } #ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS template<> inline bool (isinf)(long double x) { typedef detail::fp_traits<long double>::type traits; typedef traits::method method; //typedef boost::is_floating_point<long double>::type fp_tag; typedef long double value_type; return detail::isinf_impl(static_cast<value_type>(x), method()); } #endif //------------------------------------------------------------------------------ namespace detail { #ifdef BOOST_MATH_USE_STD_FPCLASSIFY template<class T> inline bool isnan_impl(T x, native_tag const&) { return (std::isnan)(x); } #endif template<class T> inline bool isnan_impl(T x, generic_tag<true> const&) { return std::numeric_limits<T>::has_infinity ? !(x <= std::numeric_limits<T>::infinity()) : x != x; } template<class T> inline bool isnan_impl(T x, generic_tag<false> const&) { #ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS if(std::numeric_limits<T>::is_specialized) return isnan_impl(x, generic_tag<true>()); #endif (void)x; // warning supression return false; } template<class T> inline bool isnan_impl(T x, ieee_copy_all_bits_tag const&) { typedef BOOST_DEDUCED_TYPENAME fp_traits<T>::type traits; BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); a &= traits::exponent | traits::significand; return a > traits::exponent; } template<class T> inline bool isnan_impl(T x, ieee_copy_leading_bits_tag const&) { typedef BOOST_DEDUCED_TYPENAME fp_traits<T>::type traits; BOOST_DEDUCED_TYPENAME traits::bits a; traits::get_bits(x,a); a &= traits::exponent | traits::significand; if(a < traits::exponent) return false; a &= traits::significand; traits::set_bits(x,a); return x != 0; } } // namespace detail template<class T> inline bool (isnan)(T x) { //!< \brief return true if floating-point type t is NaN (Not A Number). typedef typename detail::fp_traits<T>::type traits; typedef typename traits::method method; // typedef typename boost::is_floating_point<T>::type fp_tag; return detail::isnan_impl(x, method()); } #ifdef isnan template <> inline bool isnan BOOST_NO_MACRO_EXPAND<float>(float t){ return ::boost::math_detail::is_nan_helper(t, boost::true_type()); } template <> inline bool isnan BOOST_NO_MACRO_EXPAND<double>(double t){ return ::boost::math_detail::is_nan_helper(t, boost::true_type()); } template <> inline bool isnan BOOST_NO_MACRO_EXPAND<long double>(long double t){ return ::boost::math_detail::is_nan_helper(t, boost::true_type()); } #elif defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) template<> inline bool (isnan)(long double x) { //!< \brief return true if floating-point type t is NaN (Not A Number). typedef detail::fp_traits<long double>::type traits; typedef traits::method method; //typedef boost::is_floating_point<long double>::type fp_tag; return detail::isnan_impl(x, method()); } #endif } // namespace math } // namespace boost #endif // BOOST_MATH_FPCLASSIFY_HPP
#include <iostream> #include <regex.h> #include <regex_tokenizer.h> // @manual #include <sentencepiece.h> // @manual #include <torch/script.h> #include <vectors.h> // @manual #include <vocab.h> // @manual namespace torchtext { TORCH_LIBRARY_FRAGMENT(torchtext, m) { m.class_<Regex>("Regex") .def(torch::init<std::string>()) .def("Sub", &Regex::Sub) .def_pickle( // __getstate__ [](const c10::intrusive_ptr<Regex> &self) -> std::string { return _serialize_regex(self); }, // __setstate__ [](std::string state) -> c10::intrusive_ptr<Regex> { return _deserialize_regex(std::move(state)); }); m.class_<RegexTokenizer>("RegexTokenizer") .def(torch::init<std::vector<std::string>, std::vector<std::string>, bool>()) .def("forward", &RegexTokenizer::forward) .def_pickle( // __getstate__ [](const c10::intrusive_ptr<RegexTokenizer> &self) -> RegexTokenizerStates { return _serialize_regex_tokenizer(self); }, // __setstate__ [](RegexTokenizerStates states) -> c10::intrusive_ptr<RegexTokenizer> { return _deserialize_regex_tokenizer(std::move(states)); }); m.class_<SentencePiece>("SentencePiece") .def(torch::init<std::string>()) .def("Encode", &SentencePiece::Encode) .def("EncodeAsIds", &SentencePiece::EncodeAsIds) .def("DecodeIds", &SentencePiece::DecodeIds) .def("EncodeAsPieces", &SentencePiece::EncodeAsPieces) .def("DecodePieces", &SentencePiece::DecodePieces) .def("GetPieceSize", &SentencePiece::GetPieceSize) .def("unk_id", &SentencePiece::unk_id) .def("PieceToId", &SentencePiece::PieceToId) .def("IdToPiece", &SentencePiece::IdToPiece) .def_pickle( // The underlying content of SentencePiece contains byte string, // and returing it as std::string cause UTF8 decoding error. // Since TorchScript does not support byte string, we use byte Tensor // to pass around the data. // __getstate__ [](const c10::intrusive_ptr<SentencePiece> &self) -> torch::Tensor { auto *data = static_cast<void *>(const_cast<char *>(self->content_.data())); auto numel = static_cast<int64_t>(self->content_.size()); return torch::from_blob(data, {numel}, {torch::kUInt8}).clone(); }, // __setstate__ [](torch::Tensor state) -> c10::intrusive_ptr<SentencePiece> { auto *data = static_cast<char *>(state.data_ptr()); auto numel = state.size(0); return c10::make_intrusive<SentencePiece>(std::string(data, numel)); }); m.class_<Vectors>("Vectors") .def(torch::init<std::vector<std::string>, std::vector<std::int64_t>, torch::Tensor, torch::Tensor>()) .def("__getitem__", &Vectors::__getitem__) .def("lookup_vectors", &Vectors::lookup_vectors) .def("__setitem__", &Vectors::__setitem__) .def("__len__", &Vectors::__len__) .def_pickle( // __getstate__ [](const c10::intrusive_ptr<Vectors> &self) -> VectorsStates { return _serialize_vectors(self); }, // __setstate__ [](VectorsStates states) -> c10::intrusive_ptr<Vectors> { return _deserialize_vectors(states); }); m.class_<Vocab>("Vocab") .def(torch::init<StringList, c10::optional<int64_t>>()) .def("__contains__", [](const c10::intrusive_ptr<Vocab> &self, const std::string &item) -> bool { return self->__contains__(c10::string_view{item}); }) .def("__getitem__", [](const c10::intrusive_ptr<Vocab> &self, const std::string &item) -> int64_t { return self->__getitem__(c10::string_view{item}); }) .def("insert_token", &Vocab::insert_token) .def("__len__", &Vocab::__len__) .def("set_default_index", &Vocab::set_default_index) .def("get_default_index", &Vocab::get_default_index) .def("append_token", &Vocab::append_token) .def("lookup_token", &Vocab::lookup_token) .def("lookup_tokens", &Vocab::lookup_tokens) .def("lookup_indices", [](const c10::intrusive_ptr<Vocab> &self, const std::vector<std::string> &items) { std::vector<int64_t> indices(items.size()); int64_t counter = 0; for (const auto &item : items) { indices[counter++] = self->__getitem__(c10::string_view{item}); } return indices; }) .def("get_stoi", &Vocab::get_stoi) .def("get_itos", &Vocab::get_itos) .def_pickle( // __getstate__ [](const c10::intrusive_ptr<Vocab> &self) -> VocabStates { return _serialize_vocab(self); }, // __setstate__ [](VocabStates states) -> c10::intrusive_ptr<Vocab> { return _deserialize_vocab(states); }); m.def("torchtext::generate_sp_model", &generate_sp_model); m.def("torchtext::load_sp_model", &load_sp_model); m.def("torchtext::load_sp_model_string", &load_sp_model_string); } } // namespace torchtext
/* Copyright (c) 2012-2018, Arvid Norberg 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 of conditions 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 materials provided with the distribution. * Neither the name of the author 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. */ #ifndef TORRENT_PART_FILE_HPP_INCLUDE #define TORRENT_PART_FILE_HPP_INCLUDE #include <string> #include <vector> #include <mutex> #include <unordered_map> #include <cstdint> #include <memory> #include "libtorrent/config.hpp" #include "libtorrent/file.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/units.hpp" namespace libtorrent { using slot_index_t = aux::strong_typedef<int, struct slot_index_tag_t>; struct TORRENT_EXTRA_EXPORT part_file { // create a part file at ``path``, that can hold ``num_pieces`` pieces. // each piece being ``piece_size`` number of bytes part_file(std::string const& path, std::string const& name, int num_pieces, int piece_size); ~part_file(); int writev(span<iovec_t const> bufs, piece_index_t piece, int offset, error_code& ec); int readv(span<iovec_t const> bufs, piece_index_t piece, int offset, error_code& ec); // free the slot the given piece is stored in. We no longer need to store this // piece in the part file void free_piece(piece_index_t piece); void move_partfile(std::string const& path, error_code& ec); // the function is called for every block of data belonging to the // specified range that's in the part_file. The first parameter is the // offset within the range void export_file(std::function<void(std::int64_t, span<char>)> f , std::int64_t offset, std::int64_t size, error_code& ec); // flush the metadata void flush_metadata(error_code& ec); private: file open_file(open_mode_t mode, error_code& ec); void flush_metadata_impl(error_code& ec); std::int64_t slot_offset(slot_index_t const slot) const { return static_cast<int>(slot) * static_cast<std::int64_t>(m_piece_size) + m_header_size; } std::string m_path; std::string const m_name; // allocate a slot and return the slot index slot_index_t allocate_slot(piece_index_t piece); // this mutex must be held while accessing the data // structure. Not while reading or writing from the file though! // it's important to support multithreading std::mutex m_mutex; // this is a list of unallocated slots in the part file // within the m_num_allocated range std::vector<slot_index_t> m_free_slots; // this is the number of slots allocated slot_index_t m_num_allocated{0}; // the max number of pieces in the torrent this part file is // backing int const m_max_pieces; // number of bytes each piece contains int const m_piece_size; // this is the size of the part_file header, it is added // to offsets when calculating the offset to read and write // payload data from int const m_header_size; // if this is true, the metadata in memory has changed since // we last saved or read it from disk. It means that we // need to flush the metadata before closing the file bool m_dirty_metadata = false; // maps a piece index to the part-file slot it is stored in std::unordered_map<piece_index_t, slot_index_t> m_piece_map; }; } #endif
//===--- ParseSIL.cpp - SIL File Parsing logic ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SILParserFunctionBuilder.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/ExistentialLayout.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/NameLookup.h" #include "swift/AST/NameLookupRequests.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/SILGenRequests.h" #include "swift/AST/SourceFile.h" #include "swift/AST/TypeCheckRequests.h" #include "swift/Basic/Defer.h" #include "swift/Demangling/Demangle.h" #include "swift/Parse/Lexer.h" #include "swift/Parse/ParseSILSupport.h" #include "swift/Parse/Parser.h" #include "swift/SIL/AbstractionPattern.h" #include "swift/SIL/InstructionUtils.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILDebugScope.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILUndef.h" #include "swift/SIL/TypeLowering.h" #include "swift/Subsystems.h" #include "swift/Syntax/SyntaxKind.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/SaveAndRestore.h" using namespace swift; using namespace swift::syntax; //===----------------------------------------------------------------------===// // SILParserState implementation //===----------------------------------------------------------------------===// namespace { class SILParserState : public SILParserStateBase { public: explicit SILParserState(SILModule &M) : M(M) {} ~SILParserState(); SILModule &M; /// This is all of the forward referenced functions with /// the location for where the reference is. llvm::DenseMap<Identifier, Located<SILFunction*>> ForwardRefFns; /// A list of all functions forward-declared by a sil_scope. llvm::DenseSet<SILFunction *> PotentialZombieFns; /// A map from textual .sil scope number to SILDebugScopes. llvm::DenseMap<unsigned, SILDebugScope *> ScopeSlots; /// Did we parse a sil_stage for this module? bool DidParseSILStage = false; bool parseDeclSIL(Parser &P) override; bool parseDeclSILStage(Parser &P) override; bool parseSILVTable(Parser &P) override; bool parseSILGlobal(Parser &P) override; bool parseSILWitnessTable(Parser &P) override; bool parseSILDefaultWitnessTable(Parser &P) override; bool parseSILDifferentiabilityWitness(Parser &P) override; bool parseSILCoverageMap(Parser &P) override; bool parseSILProperty(Parser &P) override; bool parseSILScope(Parser &P) override; }; } // end anonymous namespace SILParserState::~SILParserState() { if (!ForwardRefFns.empty()) { for (auto Entry : ForwardRefFns) { if (Entry.second.Loc.isValid()) { M.getASTContext().Diags.diagnose(Entry.second.Loc, diag::sil_use_of_undefined_value, Entry.first.str()); } } } // Turn any debug-info-only function declarations into zombies. for (auto *Fn : PotentialZombieFns) if (Fn->isExternalDeclaration()) { Fn->setInlined(); M.eraseFunction(Fn); } } std::unique_ptr<SILModule> ParseSILModuleRequest::evaluate(Evaluator &evaluator, ASTLoweringDescriptor desc) const { auto *SF = desc.getSourceFileToParse(); assert(SF); auto bufferID = SF->getBufferID(); assert(bufferID); auto silMod = SILModule::createEmptyModule(desc.context, desc.conv, desc.opts); SILParserState parserState(*silMod.get()); Parser parser(*bufferID, *SF, &parserState); PrettyStackTraceParser StackTrace(parser); auto hadError = parser.parseTopLevelSIL(); if (hadError) { // The rest of the SIL pipeline expects well-formed SIL, so if we encounter // a parsing error, just return an empty SIL module. return SILModule::createEmptyModule(desc.context, desc.conv, desc.opts); } return silMod; } //===----------------------------------------------------------------------===// // SILParser //===----------------------------------------------------------------------===// namespace { struct ParsedSubstitution { SourceLoc loc; Type replacement; }; struct ParsedSpecAttr { ArrayRef<RequirementRepr> requirements; bool exported; SILSpecializeAttr::SpecializationKind kind; }; enum class ConformanceContext { /// A normal conformance parse. Ordinary, /// We're parsing this for a SIL witness table. /// Leave any generic parameter clauses in scope, and use an explicit /// self-conformance instead of an abstract one. WitnessTable, }; class SILParser { friend SILParserState; public: Parser &P; SILModule &SILMod; SILParserState &TUState; SILFunction *F = nullptr; GenericEnvironment *ContextGenericEnv = nullptr; private: /// HadError - Have we seen an error parsing this function? bool HadError = false; /// Data structures used to perform name lookup of basic blocks. llvm::DenseMap<Identifier, SILBasicBlock*> BlocksByName; llvm::DenseMap<SILBasicBlock*, Located<Identifier>> UndefinedBlocks; /// Data structures used to perform name lookup for local values. llvm::StringMap<ValueBase*> LocalValues; llvm::StringMap<SourceLoc> ForwardRefLocalValues; /// A callback to be invoked every time a type was deserialized. std::function<void(Type)> ParsedTypeCallback; Type performTypeResolution(TypeRepr *TyR, bool IsSILType, GenericEnvironment *GenericEnv); void convertRequirements(SILFunction *F, ArrayRef<RequirementRepr> From, SmallVectorImpl<Requirement> &To); ProtocolConformanceRef parseProtocolConformanceHelper( ProtocolDecl *&proto, GenericEnvironment *GenericEnv, ConformanceContext context, ProtocolDecl *defaultForProto); public: SILParser(Parser &P) : P(P), SILMod(static_cast<SILParserState *>(P.SIL)->M), TUState(*static_cast<SILParserState *>(P.SIL)), ParsedTypeCallback([](Type ty) {}) {} /// diagnoseProblems - After a function is fully parse, emit any diagnostics /// for errors and return true if there were any. bool diagnoseProblems(); /// getGlobalNameForReference - Given a reference to a global name, look it /// up and return an appropriate SIL function. SILFunction *getGlobalNameForReference(Identifier Name, CanSILFunctionType Ty, SourceLoc Loc, bool IgnoreFwdRef = false); /// getGlobalNameForDefinition - Given a definition of a global name, look /// it up and return an appropriate SIL function. SILFunction *getGlobalNameForDefinition(Identifier Name, CanSILFunctionType Ty, SourceLoc Loc); /// getBBForDefinition - Return the SILBasicBlock for a definition of the /// specified block. SILBasicBlock *getBBForDefinition(Identifier Name, SourceLoc Loc); /// getBBForReference - return the SILBasicBlock of the specified name. The /// source location is used to diagnose a failure if the block ends up never /// being defined. SILBasicBlock *getBBForReference(Identifier Name, SourceLoc Loc); struct UnresolvedValueName { StringRef Name; SourceLoc NameLoc; bool isUndef() const { return Name == "undef"; } }; /// getLocalValue - Get a reference to a local value with the specified name /// and type. SILValue getLocalValue(UnresolvedValueName Name, SILType Type, SILLocation L, SILBuilder &B); /// setLocalValue - When an instruction or block argument is defined, this /// method is used to register it and update our symbol table. void setLocalValue(ValueBase *Value, StringRef Name, SourceLoc NameLoc); SILDebugLocation getDebugLoc(SILBuilder & B, SILLocation Loc) { return SILDebugLocation(Loc, F->getDebugScope()); } /// @{ Primitive parsing. /// \verbatim /// sil-identifier ::= [A-Za-z_0-9]+ /// \endverbatim bool parseSILIdentifier(Identifier &Result, SourceLoc &Loc, const Diagnostic &D); template<typename ...DiagArgTypes, typename ...ArgTypes> bool parseSILIdentifier(Identifier &Result, Diag<DiagArgTypes...> ID, ArgTypes... Args) { SourceLoc L; return parseSILIdentifier(Result, L, Diagnostic(ID, Args...)); } template <typename T, typename... DiagArgTypes, typename... ArgTypes> bool parseSILIdentifierSwitch(T &Result, ArrayRef<StringRef> Strings, Diag<DiagArgTypes...> ID, ArgTypes... Args) { Identifier TmpResult; SourceLoc L; if (parseSILIdentifier(TmpResult, L, Diagnostic(ID, Args...))) { return true; } auto Iter = std::find(Strings.begin(), Strings.end(), TmpResult.str()); if (Iter == Strings.end()) { P.diagnose(P.Tok, Diagnostic(ID, Args...)); return true; } Result = T(*Iter); return false; } template<typename ...DiagArgTypes, typename ...ArgTypes> bool parseSILIdentifier(Identifier &Result, SourceLoc &L, Diag<DiagArgTypes...> ID, ArgTypes... Args) { return parseSILIdentifier(Result, L, Diagnostic(ID, Args...)); } bool parseVerbatim(StringRef identifier); template <typename T> bool parseInteger(T &Result, const Diagnostic &D) { if (!P.Tok.is(tok::integer_literal)) { P.diagnose(P.Tok, D); return true; } bool error = parseIntegerLiteral(P.Tok.getText(), 0, Result); P.consumeToken(tok::integer_literal); return error; } template <typename T> bool parseIntegerLiteral(StringRef text, unsigned radix, T &result) { text = prepareIntegerLiteralForParsing(text); return text.getAsInteger(radix, result); } StringRef prepareIntegerLiteralForParsing(StringRef text) { // tok::integer_literal can contain characters that the library // parsing routines don't expect. if (text.contains('_')) text = P.copyAndStripUnderscores(text); return text; } /// @} /// @{ Type parsing. bool parseASTType(CanType &result, GenericEnvironment *environment = nullptr); bool parseASTType(CanType &result, SourceLoc &TypeLoc) { TypeLoc = P.Tok.getLoc(); return parseASTType(result); } bool parseASTType(CanType &result, SourceLoc &TypeLoc, GenericEnvironment *env) { TypeLoc = P.Tok.getLoc(); return parseASTType(result, env); } bool parseSILOwnership(ValueOwnershipKind &OwnershipKind) { // We parse here @ <identifier>. if (!P.consumeIf(tok::at_sign)) { // If we fail, we must have @any ownership. We check elsewhere in the // parser that this matches what the function signature wants. OwnershipKind = ValueOwnershipKind::None; return false; } StringRef AllOwnershipKinds[3] = {"unowned", "owned", "guaranteed"}; return parseSILIdentifierSwitch(OwnershipKind, AllOwnershipKinds, diag::expected_sil_value_ownership_kind); } bool parseSILType(SILType &Result, GenericEnvironment *&parsedGenericEnv, bool IsFuncDecl = false, GenericEnvironment *parentGenericEnv = nullptr); bool parseSILType(SILType &Result) { GenericEnvironment *IgnoredEnv; return parseSILType(Result, IgnoredEnv); } bool parseSILType(SILType &Result, SourceLoc &TypeLoc) { TypeLoc = P.Tok.getLoc(); return parseSILType(Result); } bool parseSILType(SILType &Result, SourceLoc &TypeLoc, GenericEnvironment *&parsedGenericEnv, GenericEnvironment *parentGenericEnv = nullptr) { TypeLoc = P.Tok.getLoc(); return parseSILType(Result, parsedGenericEnv, false, parentGenericEnv); } /// @} bool parseSILDottedPath(ValueDecl *&Decl, SmallVectorImpl<ValueDecl *> &values); bool parseSILDottedPath(ValueDecl *&Decl) { SmallVector<ValueDecl *, 4> values; return parseSILDottedPath(Decl, values); } bool parseSILDottedPathWithoutPound(ValueDecl *&Decl, SmallVectorImpl<ValueDecl *> &values); bool parseSILDottedPathWithoutPound(ValueDecl *&Decl) { SmallVector<ValueDecl *, 4> values; return parseSILDottedPathWithoutPound(Decl, values); } /// At the time of calling this function, we may not have the type of the /// Decl yet. So we return a SILDeclRef on the first lookup result and also /// return all the lookup results. After parsing the expected type, the /// caller of this function can choose the one that has the expected type. bool parseSILDeclRef(SILDeclRef &Result, SmallVectorImpl<ValueDecl *> &values); bool parseSILDeclRef(SILDeclRef &Result) { SmallVector<ValueDecl *, 4> values; return parseSILDeclRef(Result, values); } bool parseSILDeclRef(SILDeclRef &Member, bool FnTypeRequired); bool parseGlobalName(Identifier &Name); bool parseValueName(UnresolvedValueName &Name); bool parseValueRef(SILValue &Result, SILType Ty, SILLocation Loc, SILBuilder &B); bool parseTypedValueRef(SILValue &Result, SourceLoc &Loc, SILBuilder &B); bool parseTypedValueRef(SILValue &Result, SILBuilder &B) { SourceLoc Tmp; return parseTypedValueRef(Result, Tmp, B); } bool parseSILOpcode(SILInstructionKind &Opcode, SourceLoc &OpcodeLoc, StringRef &OpcodeName); bool parseSILDebugVar(SILDebugVariable &Var); /// Parses the basic block arguments as part of branch instruction. bool parseSILBBArgsAtBranch(SmallVector<SILValue, 6> &Args, SILBuilder &B); bool parseSILLocation(SILLocation &L); bool parseScopeRef(SILDebugScope *&DS); bool parseSILDebugLocation(SILLocation &L, SILBuilder &B, bool parsedComma = false); bool parseSpecificSILInstruction(SILBuilder &B, SILInstructionKind Opcode, SourceLoc OpcodeLoc, StringRef OpcodeName, SILInstruction *&ResultVal); bool parseSILInstruction(SILBuilder &B); bool parseCallInstruction(SILLocation InstLoc, SILInstructionKind Opcode, SILBuilder &B, SILInstruction *&ResultVal); bool parseSILFunctionRef(SILLocation InstLoc, SILFunction *&ResultFn); bool parseSILBasicBlock(SILBuilder &B); bool parseKeyPathPatternComponent(KeyPathPatternComponent &component, SmallVectorImpl<SILType> &operandTypes, SourceLoc componentLoc, Identifier componentKind, SILLocation InstLoc, GenericEnvironment *patternEnv); bool isStartOfSILInstruction(); bool parseSubstitutions(SmallVectorImpl<ParsedSubstitution> &parsed, GenericEnvironment *GenericEnv=nullptr, ProtocolDecl *defaultForProto = nullptr); ProtocolConformanceRef parseProtocolConformance( ProtocolDecl *&proto, GenericEnvironment *&genericEnv, ConformanceContext context, ProtocolDecl *defaultForProto); ProtocolConformanceRef parseProtocolConformance(ProtocolDecl *defaultForProto, ConformanceContext context) { ProtocolDecl *dummy; GenericEnvironment *env; return parseProtocolConformance(dummy, env, context, defaultForProto); } Optional<llvm::coverage::Counter> parseSILCoverageExpr(llvm::coverage::CounterExpressionBuilder &Builder); template <class T> struct ParsedEnum { Optional<T> Value; StringRef Name; SourceLoc Loc; bool isSet() const { return Value.hasValue(); } T operator*() const { return *Value; } }; template <class T> void setEnum(ParsedEnum<T> &existing, T value, StringRef name, SourceLoc loc) { if (existing.Value) { if (*existing.Value == value) { P.diagnose(loc, diag::duplicate_attribute, /*modifier*/ 1); } else { P.diagnose(loc, diag::mutually_exclusive_attrs, name, existing.Name, /*modifier*/ 1); } P.diagnose(existing.Loc, diag::previous_attribute, /*modifier*/ 1); } existing.Value = value; existing.Name = name; existing.Loc = loc; } template <class T> void maybeSetEnum(bool allowed, ParsedEnum<T> &existing, T value, StringRef name, SourceLoc loc) { if (allowed) setEnum(existing, value, name, loc); else P.diagnose(loc, diag::unknown_attribute, name); } }; } // end anonymous namespace bool SILParser::parseSILIdentifier(Identifier &Result, SourceLoc &Loc, const Diagnostic &D) { switch (P.Tok.getKind()) { case tok::identifier: case tok::dollarident: Result = P.Context.getIdentifier(P.Tok.getText()); break; case tok::string_literal: { // Drop the double quotes. StringRef rawString = P.Tok.getText().drop_front().drop_back(); Result = P.Context.getIdentifier(rawString); break; } case tok::oper_binary_unspaced: // fixme? case tok::oper_binary_spaced: case tok::kw_init: // A binary operator or `init` can be part of a SILDeclRef. Result = P.Context.getIdentifier(P.Tok.getText()); break; default: // If it's some other keyword, grab an identifier for it. if (P.Tok.isKeyword()) { Result = P.Context.getIdentifier(P.Tok.getText()); break; } P.diagnose(P.Tok, D); return true; } Loc = P.Tok.getLoc(); P.consumeToken(); return false; } bool SILParser::parseVerbatim(StringRef name) { Identifier tok; SourceLoc loc; if (parseSILIdentifier(tok, loc, diag::expected_tok_in_sil_instr, name)) { return true; } if (tok.str() != name) { P.diagnose(loc, diag::expected_tok_in_sil_instr, name); return true; } return false; } /// diagnoseProblems - After a function is fully parse, emit any diagnostics /// for errors and return true if there were any. bool SILParser::diagnoseProblems() { // Check for any uses of basic blocks that were not defined. if (!UndefinedBlocks.empty()) { // FIXME: These are going to come out in nondeterministic order. for (auto Entry : UndefinedBlocks) P.diagnose(Entry.second.Loc, diag::sil_undefined_basicblock_use, Entry.second.Item); HadError = true; } if (!ForwardRefLocalValues.empty()) { // FIXME: These are going to come out in nondeterministic order. for (auto &Entry : ForwardRefLocalValues) P.diagnose(Entry.second, diag::sil_use_of_undefined_value, Entry.first()); HadError = true; } return HadError; } /// getGlobalNameForDefinition - Given a definition of a global name, look /// it up and return an appropriate SIL function. SILFunction *SILParser::getGlobalNameForDefinition(Identifier name, CanSILFunctionType ty, SourceLoc sourceLoc) { SILParserFunctionBuilder builder(SILMod); auto silLoc = RegularLocation(sourceLoc); // Check to see if a function of this name has been forward referenced. If so // complete the forward reference. auto iter = TUState.ForwardRefFns.find(name); if (iter != TUState.ForwardRefFns.end()) { SILFunction *fn = iter->second.Item; // Verify that the types match up. if (fn->getLoweredFunctionType() != ty) { P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(), fn->getLoweredFunctionType(), ty); P.diagnose(iter->second.Loc, diag::sil_prior_reference); fn = builder.createFunctionForForwardReference("" /*name*/, ty, silLoc); } assert(fn->isExternalDeclaration() && "Forward defns cannot have bodies!"); TUState.ForwardRefFns.erase(iter); // Move the function to this position in the module. // // FIXME: Should we move this functionality into SILParserFunctionBuilder? SILMod.getFunctionList().remove(fn); SILMod.getFunctionList().push_back(fn); return fn; } // If we don't have a forward reference, make sure the function hasn't been // defined already. if (SILMod.lookUpFunction(name.str()) != nullptr) { P.diagnose(sourceLoc, diag::sil_value_redefinition, name.str()); return builder.createFunctionForForwardReference("" /*name*/, ty, silLoc); } // Otherwise, this definition is the first use of this name. return builder.createFunctionForForwardReference(name.str(), ty, silLoc); } /// getGlobalNameForReference - Given a reference to a global name, look it /// up and return an appropriate SIL function. SILFunction *SILParser::getGlobalNameForReference(Identifier name, CanSILFunctionType funcTy, SourceLoc sourceLoc, bool ignoreFwdRef) { SILParserFunctionBuilder builder(SILMod); auto silLoc = RegularLocation(sourceLoc); // Check to see if we have a function by this name already. if (SILFunction *fn = SILMod.lookUpFunction(name.str())) { // If so, check for matching types. if (fn->getLoweredFunctionType() == funcTy) { return fn; } P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(), fn->getLoweredFunctionType(), funcTy); return builder.createFunctionForForwardReference("" /*name*/, funcTy, silLoc); } // If we didn't find a function, create a new one - it must be a forward // reference. auto *fn = builder.createFunctionForForwardReference(name.str(), funcTy, silLoc); TUState.ForwardRefFns[name] = {fn, ignoreFwdRef ? SourceLoc() : sourceLoc}; return fn; } /// getBBForDefinition - Return the SILBasicBlock for a definition of the /// specified block. SILBasicBlock *SILParser::getBBForDefinition(Identifier Name, SourceLoc Loc) { // If there was no name specified for this block, just create a new one. if (Name.empty()) return F->createBasicBlock(); SILBasicBlock *&BB = BlocksByName[Name]; // If the block has never been named yet, just create it. if (BB == nullptr) return BB = F->createBasicBlock(); // If it already exists, it was either a forward reference or a redefinition. // If it is a forward reference, it should be in our undefined set. if (!UndefinedBlocks.erase(BB)) { // If we have a redefinition, return a new BB to avoid inserting // instructions after the terminator. P.diagnose(Loc, diag::sil_basicblock_redefinition, Name); HadError = true; return F->createBasicBlock(); } // FIXME: Splice the block to the end of the function so they come out in the // right order. return BB; } /// getBBForReference - return the SILBasicBlock of the specified name. The /// source location is used to diagnose a failure if the block ends up never /// being defined. SILBasicBlock *SILParser::getBBForReference(Identifier Name, SourceLoc Loc) { // If the block has already been created, use it. SILBasicBlock *&BB = BlocksByName[Name]; if (BB != nullptr) return BB; // Otherwise, create it and remember that this is a forward reference so // that we can diagnose use without definition problems. BB = F->createBasicBlock(); UndefinedBlocks[BB] = {Name, Loc}; return BB; } /// sil-global-name: /// '@' identifier bool SILParser::parseGlobalName(Identifier &Name) { return P.parseToken(tok::at_sign, diag::expected_sil_value_name) || parseSILIdentifier(Name, diag::expected_sil_value_name); } /// getLocalValue - Get a reference to a local value with the specified name /// and type. SILValue SILParser::getLocalValue(UnresolvedValueName Name, SILType Type, SILLocation Loc, SILBuilder &B) { if (Name.isUndef()) return SILUndef::get(Type, B.getFunction()); // Check to see if this is already defined. ValueBase *&Entry = LocalValues[Name.Name]; if (Entry) { // If this value is already defined, check it to make sure types match. SILType EntryTy = Entry->getType(); if (EntryTy != Type) { HadError = true; P.diagnose(Name.NameLoc, diag::sil_value_use_type_mismatch, Name.Name, EntryTy.getASTType(), Type.getASTType()); // Make sure to return something of the requested type. return new (SILMod) GlobalAddrInst(getDebugLoc(B, Loc), Type); } return SILValue(Entry); } // Otherwise, this is a forward reference. Create a dummy node to represent // it until we see a real definition. ForwardRefLocalValues[Name.Name] = Name.NameLoc; Entry = new (SILMod) GlobalAddrInst(getDebugLoc(B, Loc), Type); return Entry; } /// setLocalValue - When an instruction or block argument is defined, this /// method is used to register it and update our symbol table. void SILParser::setLocalValue(ValueBase *Value, StringRef Name, SourceLoc NameLoc) { ValueBase *&Entry = LocalValues[Name]; // If this value was already defined, it is either a redefinition, or a // specification for a forward referenced value. if (Entry) { if (!ForwardRefLocalValues.erase(Name)) { P.diagnose(NameLoc, diag::sil_value_redefinition, Name); HadError = true; return; } // If the forward reference was of the wrong type, diagnose this now. if (Entry->getType() != Value->getType()) { P.diagnose(NameLoc, diag::sil_value_def_type_mismatch, Name, Entry->getType().getASTType(), Value->getType().getASTType()); HadError = true; } else { // Forward references only live here if they have a single result. Entry->replaceAllUsesWith(Value); } Entry = Value; return; } // Otherwise, just store it in our map. Entry = Value; } //===----------------------------------------------------------------------===// // SIL Parsing Logic //===----------------------------------------------------------------------===// /// parseSILLinkage - Parse a linkage specifier if present. /// sil-linkage: /// /*empty*/ // default depends on whether this is a definition /// 'public' /// 'hidden' /// 'shared' /// 'private' /// 'public_external' /// 'hidden_external' /// 'private_external' static bool parseSILLinkage(Optional<SILLinkage> &Result, Parser &P) { // Begin by initializing result to our base value of None. Result = None; // Unfortunate collision with access control keywords. if (P.Tok.is(tok::kw_public)) { Result = SILLinkage::Public; P.consumeToken(); return false; } // Unfortunate collision with access control keywords. if (P.Tok.is(tok::kw_private)) { Result = SILLinkage::Private; P.consumeToken(); return false; } // If we do not have an identifier, bail. All SILLinkages that we are parsing // are identifiers. if (P.Tok.isNot(tok::identifier)) return false; // Then use a string switch to try and parse the identifier. Result = llvm::StringSwitch<Optional<SILLinkage>>(P.Tok.getText()) .Case("non_abi", SILLinkage::PublicNonABI) .Case("hidden", SILLinkage::Hidden) .Case("shared", SILLinkage::Shared) .Case("public_external", SILLinkage::PublicExternal) .Case("hidden_external", SILLinkage::HiddenExternal) .Case("shared_external", SILLinkage::SharedExternal) .Case("private_external", SILLinkage::PrivateExternal) .Default(None); // If we succeed, consume the token. if (Result) { P.consumeToken(tok::identifier); } return false; } /// Given whether it's known to be a definition, resolve an optional /// SIL linkage to a real one. static SILLinkage resolveSILLinkage(Optional<SILLinkage> linkage, bool isDefinition) { if (linkage.hasValue()) { return linkage.getValue(); } else if (isDefinition) { return SILLinkage::DefaultForDefinition; } else { return SILLinkage::DefaultForDeclaration; } } static bool parseSILOptional(StringRef &Result, SourceLoc &Loc, SILParser &SP) { if (SP.P.consumeIf(tok::l_square)) { Identifier Id; SP.parseSILIdentifier(Id, Loc, diag::expected_in_attribute_list); SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); Result = Id.str(); return true; } return false; } static bool parseSILOptional(StringRef &Result, SILParser &SP) { SourceLoc Loc; return parseSILOptional(Result, Loc, SP); } /// Parse an option attribute ('[' Expected ']')? static bool parseSILOptional(bool &Result, SILParser &SP, StringRef Expected) { StringRef Optional; if (parseSILOptional(Optional, SP)) { if (Optional != Expected) return true; Result = true; } return false; } namespace { /// A helper class to perform lookup of IdentTypes in the /// current parser scope. class IdentTypeReprLookup : public ASTWalker { Parser &P; public: IdentTypeReprLookup(Parser &P) : P(P) {} bool walkToTypeReprPre(TypeRepr *Ty) override { auto *T = dyn_cast_or_null<IdentTypeRepr>(Ty); auto Comp = T->getComponentRange().front(); if (auto Entry = P.lookupInScope(Comp->getNameRef())) if (auto *TD = dyn_cast<TypeDecl>(Entry)) { Comp->setValue(TD, nullptr); return false; } return true; } }; } // end anonymous namespace /// Remap RequirementReps to Requirements. void SILParser::convertRequirements(SILFunction *F, ArrayRef<RequirementRepr> From, SmallVectorImpl<Requirement> &To) { if (From.empty()) { To.clear(); return; } auto *GenericEnv = F->getGenericEnvironment(); assert(GenericEnv); (void)GenericEnv; IdentTypeReprLookup PerformLookup(P); // Use parser lexical scopes to resolve references // to the generic parameters. auto ResolveToInterfaceType = [&](TypeRepr *TyR) -> Type { TyR->walk(PerformLookup); return performTypeResolution(TyR, /*IsSILType=*/false, ContextGenericEnv) ->mapTypeOutOfContext(); }; for (auto &Req : From) { if (Req.getKind() == RequirementReprKind::SameType) { auto FirstType = ResolveToInterfaceType(Req.getFirstTypeRepr()); auto SecondType = ResolveToInterfaceType(Req.getSecondTypeRepr()); Requirement ConvertedRequirement(RequirementKind::SameType, FirstType, SecondType); To.push_back(ConvertedRequirement); continue; } if (Req.getKind() == RequirementReprKind::TypeConstraint) { auto Subject = ResolveToInterfaceType(Req.getSubjectRepr()); auto Constraint = ResolveToInterfaceType(Req.getConstraintRepr()); Requirement ConvertedRequirement(RequirementKind::Conformance, Subject, Constraint); To.push_back(ConvertedRequirement); continue; } if (Req.getKind() == RequirementReprKind::LayoutConstraint) { auto Subject = ResolveToInterfaceType(Req.getSubjectRepr()); Requirement ConvertedRequirement(RequirementKind::Layout, Subject, Req.getLayoutConstraint()); To.push_back(ConvertedRequirement); continue; } llvm_unreachable("Unsupported requirement kind"); } } static bool parseDeclSILOptional(bool *isTransparent, IsSerialized_t *isSerialized, bool *isCanonical, bool *hasOwnershipSSA, IsThunk_t *isThunk, IsDynamicallyReplaceable_t *isDynamic, IsExactSelfClass_t *isExactSelfClass, SILFunction **dynamicallyReplacedFunction, Identifier *objCReplacementFor, SILFunction::Purpose *specialPurpose, Inline_t *inlineStrategy, OptimizationMode *optimizationMode, bool *isLet, bool *isWeakImported, AvailabilityContext *availability, bool *isWithoutActuallyEscapingThunk, SmallVectorImpl<std::string> *Semantics, SmallVectorImpl<ParsedSpecAttr> *SpecAttrs, ValueDecl **ClangDecl, EffectsKind *MRK, SILParser &SP, SILModule &M) { while (SP.P.consumeIf(tok::l_square)) { if (isLet && SP.P.Tok.is(tok::kw_let)) { *isLet = true; SP.P.consumeToken(tok::kw_let); SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); continue; } else if (SP.P.Tok.isNot(tok::identifier)) { SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list); return true; } else if (isTransparent && SP.P.Tok.getText() == "transparent") *isTransparent = true; else if (isSerialized && SP.P.Tok.getText() == "serialized") *isSerialized = IsSerialized; else if (isDynamic && SP.P.Tok.getText() == "dynamically_replacable") *isDynamic = IsDynamic; else if (isExactSelfClass && SP.P.Tok.getText() == "exact_self_class") *isExactSelfClass = IsExactSelfClass; else if (isSerialized && SP.P.Tok.getText() == "serializable") *isSerialized = IsSerializable; else if (isCanonical && SP.P.Tok.getText() == "canonical") *isCanonical = true; else if (hasOwnershipSSA && SP.P.Tok.getText() == "ossa") *hasOwnershipSSA = true; else if (isThunk && SP.P.Tok.getText() == "thunk") *isThunk = IsThunk; else if (isThunk && SP.P.Tok.getText() == "signature_optimized_thunk") *isThunk = IsSignatureOptimizedThunk; else if (isThunk && SP.P.Tok.getText() == "reabstraction_thunk") *isThunk = IsReabstractionThunk; else if (isWithoutActuallyEscapingThunk && SP.P.Tok.getText() == "without_actually_escaping") *isWithoutActuallyEscapingThunk = true; else if (specialPurpose && SP.P.Tok.getText() == "global_init") *specialPurpose = SILFunction::Purpose::GlobalInit; else if (specialPurpose && SP.P.Tok.getText() == "lazy_getter") *specialPurpose = SILFunction::Purpose::LazyPropertyGetter; else if (isWeakImported && SP.P.Tok.getText() == "weak_imported") { if (M.getASTContext().LangOpts.Target.isOSBinFormatCOFF()) SP.P.diagnose(SP.P.Tok, diag::attr_unsupported_on_target, SP.P.Tok.getText(), M.getASTContext().LangOpts.Target.str()); else *isWeakImported = true; } else if (availability && SP.P.Tok.getText() == "available") { SP.P.consumeToken(tok::identifier); SourceRange range; llvm::VersionTuple version; if (SP.P.parseVersionTuple(version, range, diag::sil_availability_expected_version)) return true; *availability = AvailabilityContext(VersionRange::allGTE(version)); SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); continue; } else if (inlineStrategy && SP.P.Tok.getText() == "noinline") *inlineStrategy = NoInline; else if (optimizationMode && SP.P.Tok.getText() == "Onone") *optimizationMode = OptimizationMode::NoOptimization; else if (optimizationMode && SP.P.Tok.getText() == "Ospeed") *optimizationMode = OptimizationMode::ForSpeed; else if (optimizationMode && SP.P.Tok.getText() == "Osize") *optimizationMode = OptimizationMode::ForSize; else if (inlineStrategy && SP.P.Tok.getText() == "always_inline") *inlineStrategy = AlwaysInline; else if (MRK && SP.P.Tok.getText() == "readnone") *MRK = EffectsKind::ReadNone; else if (MRK && SP.P.Tok.getText() == "readonly") *MRK = EffectsKind::ReadOnly; else if (MRK && SP.P.Tok.getText() == "readwrite") *MRK = EffectsKind::ReadWrite; else if (MRK && SP.P.Tok.getText() == "releasenone") *MRK = EffectsKind::ReleaseNone; else if (dynamicallyReplacedFunction && SP.P.Tok.getText() == "dynamic_replacement_for") { SP.P.consumeToken(tok::identifier); if (SP.P.Tok.getKind() != tok::string_literal) { SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list); return true; } // Drop the double quotes. StringRef replacedFunc = SP.P.Tok.getText().drop_front().drop_back(); SILFunction *Func = M.lookUpFunction(replacedFunc.str()); if (!Func) { Identifier Id = SP.P.Context.getIdentifier(replacedFunc); SP.P.diagnose(SP.P.Tok, diag::sil_dynamically_replaced_func_not_found, Id); return true; } *dynamicallyReplacedFunction = Func; SP.P.consumeToken(tok::string_literal); SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); continue; } else if (objCReplacementFor && SP.P.Tok.getText() == "objc_replacement_for") { SP.P.consumeToken(tok::identifier); if (SP.P.Tok.getKind() != tok::string_literal) { SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list); return true; } // Drop the double quotes. StringRef replacedFunc = SP.P.Tok.getText().drop_front().drop_back(); *objCReplacementFor = SP.P.Context.getIdentifier(replacedFunc); SP.P.consumeToken(tok::string_literal); SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); continue; } else if (Semantics && SP.P.Tok.getText() == "_semantics") { SP.P.consumeToken(tok::identifier); if (SP.P.Tok.getKind() != tok::string_literal) { SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list); return true; } // Drop the double quotes. StringRef rawString = SP.P.Tok.getText().drop_front().drop_back(); Semantics->push_back(rawString.str()); SP.P.consumeToken(tok::string_literal); SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); continue; } else if (SpecAttrs && SP.P.Tok.getText() == "_specialize") { SourceLoc AtLoc = SP.P.Tok.getLoc(); SourceLoc Loc(AtLoc); // Parse a _specialized attribute, building a parsed substitution list // and pushing a new ParsedSpecAttr on the SpecAttrs list. Conformances // cannot be generated until the function declaration is fully parsed so // that the function's generic signature can be consulted. ParsedSpecAttr SpecAttr; SpecAttr.requirements = {}; SpecAttr.exported = false; SpecAttr.kind = SILSpecializeAttr::SpecializationKind::Full; SpecializeAttr *Attr; if (!SP.P.parseSpecializeAttribute(tok::r_square, AtLoc, Loc, Attr)) return true; // Convert SpecializeAttr into ParsedSpecAttr. SpecAttr.requirements = Attr->getTrailingWhereClause()->getRequirements(); SpecAttr.kind = Attr->getSpecializationKind() == swift::SpecializeAttr::SpecializationKind::Full ? SILSpecializeAttr::SpecializationKind::Full : SILSpecializeAttr::SpecializationKind::Partial; SpecAttr.exported = Attr->isExported(); SpecAttrs->emplace_back(SpecAttr); continue; } else if (ClangDecl && SP.P.Tok.getText() == "clang") { SP.P.consumeToken(tok::identifier); if (SP.parseSILDottedPathWithoutPound(*ClangDecl)) return true; SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); continue; } else { SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list); return true; } SP.P.consumeToken(tok::identifier); SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list); } return false; } Type SILParser::performTypeResolution(TypeRepr *TyR, bool IsSILType, GenericEnvironment *GenericEnv) { if (GenericEnv == nullptr) GenericEnv = ContextGenericEnv; return swift::performTypeResolution(TyR, P.Context, /*isSILMode=*/true, IsSILType, GenericEnv, &P.SF); } /// Find the top-level ValueDecl or Module given a name. static llvm::PointerUnion<ValueDecl *, ModuleDecl *> lookupTopDecl(Parser &P, DeclBaseName Name, bool typeLookup) { // Use UnqualifiedLookup to look through all of the imports. UnqualifiedLookupOptions options; if (typeLookup) options |= UnqualifiedLookupFlags::TypeLookup; auto &ctx = P.SF.getASTContext(); auto descriptor = UnqualifiedLookupDescriptor(DeclNameRef(Name), &P.SF); auto lookup = evaluateOrDefault(ctx.evaluator, UnqualifiedLookupRequest{descriptor}, {}); assert(lookup.size() == 1); return lookup.back().getValueDecl(); } /// Find the ValueDecl given an interface type and a member name. static ValueDecl *lookupMember(Parser &P, Type Ty, DeclBaseName Name, SourceLoc Loc, SmallVectorImpl<ValueDecl *> &Lookup, bool ExpectMultipleResults) { Type CheckTy = Ty; if (auto MetaTy = CheckTy->getAs<AnyMetatypeType>()) CheckTy = MetaTy->getInstanceType(); if (auto nominal = CheckTy->getAnyNominal()) { if (Name == DeclBaseName::createDestructor() && isa<ClassDecl>(nominal)) { auto *classDecl = cast<ClassDecl>(nominal); Lookup.push_back(classDecl->getDestructor()); } else { auto found = nominal->lookupDirect(Name); Lookup.append(found.begin(), found.end()); } } else if (auto moduleTy = CheckTy->getAs<ModuleType>()) { moduleTy->getModule()->lookupValue(Name, NLKind::QualifiedLookup, Lookup); } else { P.diagnose(Loc, diag::sil_member_lookup_bad_type, Name, Ty); return nullptr; } if (Lookup.empty() || (!ExpectMultipleResults && Lookup.size() != 1)) { P.diagnose(Loc, diag::sil_named_member_decl_not_found, Name, Ty); return nullptr; } return Lookup[0]; } bool SILParser::parseASTType(CanType &result, GenericEnvironment *env) { ParserResult<TypeRepr> parsedType = P.parseType(); if (parsedType.isNull()) return true; const auto resolvedType = performTypeResolution(parsedType.get(), /*isSILType=*/false, env); if (resolvedType->hasError()) return true; if (env) result = resolvedType->mapTypeOutOfContext()->getCanonicalType(); else result = resolvedType->getCanonicalType(); // Invoke the callback on the parsed type. ParsedTypeCallback(resolvedType); return false; } /// sil-type: /// '$' '*'? attribute-list (generic-params)? type /// bool SILParser::parseSILType(SILType &Result, GenericEnvironment *&ParsedGenericEnv, bool IsFuncDecl, GenericEnvironment *OuterGenericEnv) { ParsedGenericEnv = nullptr; if (P.parseToken(tok::sil_dollar, diag::expected_sil_type)) return true; // If we have a '*', then this is an address type. SILValueCategory category = SILValueCategory::Object; if (P.Tok.isAnyOperator() && P.Tok.getText().startswith("*")) { category = SILValueCategory::Address; P.consumeStartingCharacterOfCurrentToken(); } // Parse attributes. ParamDecl::Specifier specifier; SourceLoc specifierLoc; TypeAttributes attrs; P.parseTypeAttributeList(specifier, specifierLoc, attrs); // Global functions are implicitly @convention(thin) if not specified otherwise. if (IsFuncDecl && !attrs.has(TAK_convention)) { // Use a random location. attrs.setAttr(TAK_convention, P.PreviousLoc); attrs.ConventionArguments = TypeAttributes::Convention::makeSwiftConvention("thin"); } ParserResult<TypeRepr> TyR = P.parseType(diag::expected_sil_type, /*handleCodeCompletion*/ true, /*isSILFuncDecl*/ IsFuncDecl); if (TyR.isNull()) return true; // Resolve the generic environments for parsed generic function and box types. class HandleSILGenericParamsWalker : public ASTWalker { SourceFile *SF; public: HandleSILGenericParamsWalker(SourceFile *SF) : SF(SF) {} bool walkToTypeReprPre(TypeRepr *T) override { if (auto fnType = dyn_cast<FunctionTypeRepr>(T)) { if (auto generics = fnType->getGenericParams()) { auto env = handleSILGenericParams(generics, SF); fnType->setGenericEnvironment(env); } if (auto generics = fnType->getPatternGenericParams()) { auto env = handleSILGenericParams(generics, SF); fnType->setPatternGenericEnvironment(env); } } if (auto boxType = dyn_cast<SILBoxTypeRepr>(T)) { if (auto generics = boxType->getGenericParams()) { auto env = handleSILGenericParams(generics, SF); boxType->setGenericEnvironment(env); } } return true; } }; TyR.get()->walk(HandleSILGenericParamsWalker(&P.SF)); // Save the top-level function generic environment if there was one. if (auto fnType = dyn_cast<FunctionTypeRepr>(TyR.get())) if (auto env = fnType->getGenericEnvironment()) ParsedGenericEnv = env; // Apply attributes to the type. auto *attrRepr = P.applyAttributeToType(TyR.get(), attrs, specifier, specifierLoc); const auto Ty = performTypeResolution(attrRepr, /*IsSILType=*/true, OuterGenericEnv); if (Ty->hasError()) return true; Result = SILType::getPrimitiveType(Ty->getCanonicalType(), category); // Invoke the callback on the parsed type. ParsedTypeCallback(Ty); return false; } bool SILParser::parseSILDottedPath(ValueDecl *&Decl, SmallVectorImpl<ValueDecl *> &values) { if (P.parseToken(tok::pound, diag::expected_sil_constant)) return true; return parseSILDottedPathWithoutPound(Decl, values); } bool SILParser::parseSILDottedPathWithoutPound(ValueDecl *&Decl, SmallVectorImpl<ValueDecl *> &values) { // Handle sil-dotted-path. Identifier Id; SmallVector<DeclBaseName, 4> FullName; SmallVector<SourceLoc, 4> Locs; do { Locs.push_back(P.Tok.getLoc()); switch (P.Tok.getKind()) { case tok::kw_subscript: P.consumeToken(); FullName.push_back(DeclBaseName::createSubscript()); break; case tok::kw_init: P.consumeToken(); FullName.push_back(DeclBaseName::createConstructor()); break; case tok::kw_deinit: P.consumeToken(); FullName.push_back(DeclBaseName::createDestructor()); break; default: if (parseSILIdentifier(Id, diag::expected_sil_constant)) return true; FullName.push_back(Id); break; } } while (P.consumeIf(tok::period)); // Look up ValueDecl from a dotted path. If there are multiple components, // the first one must be a type declaration. ValueDecl *VD; llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res = lookupTopDecl( P, FullName[0], /*typeLookup=*/FullName.size() > 1); // It is possible that the last member lookup can return multiple lookup // results. One example is the overloaded member functions. if (Res.is<ModuleDecl*>()) { assert(FullName.size() > 1 && "A single module is not a full path to SILDeclRef"); auto Mod = Res.get<ModuleDecl*>(); values.clear(); VD = lookupMember(P, ModuleType::get(Mod), FullName[1], Locs[1], values, FullName.size() == 2/*ExpectMultipleResults*/); for (unsigned I = 2, E = FullName.size(); I < E; ++I) { values.clear(); VD = lookupMember(P, VD->getInterfaceType(), FullName[I], Locs[I], values, I == FullName.size() - 1/*ExpectMultipleResults*/); } } else { VD = Res.get<ValueDecl*>(); for (unsigned I = 1, E = FullName.size(); I < E; ++I) { values.clear(); VD = lookupMember(P, VD->getInterfaceType(), FullName[I], Locs[I], values, I == FullName.size() - 1/*ExpectMultipleResults*/); } } Decl = VD; return false; } static Optional<AccessorKind> getAccessorKind(StringRef ident) { return llvm::StringSwitch<Optional<AccessorKind>>(ident) .Case("getter", AccessorKind::Get) .Case("setter", AccessorKind::Set) .Case("addressor", AccessorKind::Address) .Case("mutableAddressor", AccessorKind::MutableAddress) .Case("read", AccessorKind::Read) .Case("modify", AccessorKind::Modify) .Default(None); } /// sil-decl-ref ::= '#' sil-identifier ('.' sil-identifier)* sil-decl-subref? /// sil-decl-subref ::= '!' sil-decl-subref-part ('.' sil-decl-lang)? /// ('.' sil-decl-autodiff)? /// sil-decl-subref ::= '!' sil-decl-lang /// sil-decl-subref ::= '!' sil-decl-autodiff /// sil-decl-subref-part ::= 'getter' /// sil-decl-subref-part ::= 'setter' /// sil-decl-subref-part ::= 'allocator' /// sil-decl-subref-part ::= 'initializer' /// sil-decl-subref-part ::= 'enumelt' /// sil-decl-subref-part ::= 'destroyer' /// sil-decl-subref-part ::= 'globalaccessor' /// sil-decl-lang ::= 'foreign' /// sil-decl-autodiff ::= sil-decl-autodiff-kind '.' sil-decl-autodiff-indices /// sil-decl-autodiff-kind ::= 'jvp' /// sil-decl-autodiff-kind ::= 'vjp' /// sil-decl-autodiff-indices ::= [SU]+ bool SILParser::parseSILDeclRef(SILDeclRef &Result, SmallVectorImpl<ValueDecl *> &values) { ValueDecl *VD; if (parseSILDottedPath(VD, values)) return true; // Initialize SILDeclRef components. SILDeclRef::Kind Kind = SILDeclRef::Kind::Func; bool IsObjC = false; AutoDiffDerivativeFunctionIdentifier *DerivativeId = nullptr; if (!P.consumeIf(tok::sil_exclamation)) { // Construct SILDeclRef. Result = SILDeclRef(VD, Kind, IsObjC, DerivativeId); return false; } // Handle SILDeclRef components. ParseState tracks the last parsed component. // // When ParseState is 0, accept kind (`func|getter|setter|...`) and set // ParseState to 1. // // Always accept `foreign` and derivative function identifier. unsigned ParseState = 0; Identifier Id; do { if (P.Tok.is(tok::identifier)) { auto IdLoc = P.Tok.getLoc(); if (parseSILIdentifier(Id, diag::expected_sil_constant)) return true; Optional<AccessorKind> accessorKind; if (!ParseState && Id.str() == "func") { Kind = SILDeclRef::Kind::Func; ParseState = 1; } else if (!ParseState && (accessorKind = getAccessorKind(Id.str())).hasValue()) { // Drill down to the corresponding accessor for each declaration, // compacting away decls that lack it. size_t destI = 0; for (size_t srcI = 0, e = values.size(); srcI != e; ++srcI) { if (auto storage = dyn_cast<AbstractStorageDecl>(values[srcI])) if (auto accessor = storage->getOpaqueAccessor(*accessorKind)) values[destI++] = accessor; } values.resize(destI); // Complain if none of the decls had a corresponding accessor. if (destI == 0) { P.diagnose(IdLoc, diag::referenced_value_no_accessor, 0); return true; } Kind = SILDeclRef::Kind::Func; VD = values[0]; ParseState = 1; } else if (!ParseState && Id.str() == "allocator") { Kind = SILDeclRef::Kind::Allocator; ParseState = 1; } else if (!ParseState && Id.str() == "initializer") { Kind = SILDeclRef::Kind::Initializer; ParseState = 1; } else if (!ParseState && Id.str() == "enumelt") { Kind = SILDeclRef::Kind::EnumElement; ParseState = 1; } else if (!ParseState && Id.str() == "destroyer") { Kind = SILDeclRef::Kind::Destroyer; ParseState = 1; } else if (!ParseState && Id.str() == "deallocator") { Kind = SILDeclRef::Kind::Deallocator; ParseState = 1; } else if (!ParseState && Id.str() == "globalaccessor") { Kind = SILDeclRef::Kind::GlobalAccessor; ParseState = 1; } else if (!ParseState && Id.str() == "ivardestroyer") { Kind = SILDeclRef::Kind::IVarDestroyer; ParseState = 1; } else if (!ParseState && Id.str() == "ivarinitializer") { Kind = SILDeclRef::Kind::IVarInitializer; ParseState = 1; } else if (!ParseState && Id.str() == "defaultarg") { Kind = SILDeclRef::Kind::IVarInitializer; ParseState = 1; } else if (!ParseState && Id.str() == "propertyinit") { Kind = SILDeclRef::Kind::StoredPropertyInitializer; ParseState = 1; } else if (!ParseState && Id.str() == "backinginit") { Kind = SILDeclRef::Kind::PropertyWrapperBackingInitializer; ParseState = 1; } else if (Id.str() == "foreign") { IsObjC = true; break; } else if (Id.str() == "jvp" || Id.str() == "vjp") { IndexSubset *parameterIndices = nullptr; GenericSignature derivativeGenSig; // Parse derivative function kind. AutoDiffDerivativeFunctionKind derivativeKind(Id.str()); if (!P.consumeIf(tok::period)) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "."); return true; } // Parse parameter indices. parameterIndices = IndexSubset::getFromString(SILMod.getASTContext(), P.Tok.getText()); if (!parameterIndices) { P.diagnose(P.Tok, diag::invalid_index_subset); return true; } P.consumeToken(); // Parse derivative generic signature (optional). if (P.Tok.is(tok::oper_binary_unspaced) && P.Tok.getText() == ".<") { P.consumeStartingCharacterOfCurrentToken(tok::period); // Create a new scope to avoid type redefinition errors. Scope genericsScope(&P, ScopeKind::Generics); auto *genericParams = P.maybeParseGenericParams().getPtrOrNull(); assert(genericParams); auto *derivativeGenEnv = handleSILGenericParams(genericParams, &P.SF); derivativeGenSig = derivativeGenEnv->getGenericSignature(); } DerivativeId = AutoDiffDerivativeFunctionIdentifier::get( derivativeKind, parameterIndices, derivativeGenSig, SILMod.getASTContext()); break; } else { break; } } else break; } while (P.consumeIf(tok::period)); // Construct SILDeclRef. Result = SILDeclRef(VD, Kind, IsObjC, DerivativeId); return false; } /// parseValueName - Parse a value name without a type available yet. /// /// sil-value-name: /// sil-local-name /// 'undef' /// bool SILParser::parseValueName(UnresolvedValueName &Result) { Result.Name = P.Tok.getText(); if (P.Tok.is(tok::kw_undef)) { Result.NameLoc = P.consumeToken(tok::kw_undef); return false; } // Parse the local-name. if (P.parseToken(tok::sil_local_name, Result.NameLoc, diag::expected_sil_value_name)) return true; return false; } /// parseValueRef - Parse a value, given a contextual type. /// /// sil-value-ref: /// sil-local-name /// bool SILParser::parseValueRef(SILValue &Result, SILType Ty, SILLocation Loc, SILBuilder &B) { UnresolvedValueName Name; if (parseValueName(Name)) return true; Result = getLocalValue(Name, Ty, Loc, B); return false; } /// parseTypedValueRef - Parse a type/value reference pair. /// /// sil-typed-valueref: /// sil-value-ref ':' sil-type /// bool SILParser::parseTypedValueRef(SILValue &Result, SourceLoc &Loc, SILBuilder &B) { Loc = P.Tok.getLoc(); UnresolvedValueName Name; SILType Ty; if (parseValueName(Name) || P.parseToken(tok::colon, diag::expected_sil_colon_value_ref) || parseSILType(Ty)) return true; Result = getLocalValue(Name, Ty, RegularLocation(Loc), B); return false; } /// Look up whether the given string corresponds to a SIL opcode. static Optional<SILInstructionKind> getOpcodeByName(StringRef OpcodeName) { return llvm::StringSwitch<Optional<SILInstructionKind>>(OpcodeName) #define FULL_INST(Id, TextualName, Parent, MemBehavior, MayRelease) \ .Case(#TextualName, SILInstructionKind::Id) #include "swift/SIL/SILNodes.def" .Default(None); } /// getInstructionKind - This method maps the string form of a SIL instruction /// opcode to an enum. bool SILParser::parseSILOpcode(SILInstructionKind &Opcode, SourceLoc &OpcodeLoc, StringRef &OpcodeName) { OpcodeLoc = P.Tok.getLoc(); OpcodeName = P.Tok.getText(); // Parse this textually to avoid Swift keywords (like 'return') from // interfering with opcode recognition. auto MaybeOpcode = getOpcodeByName(OpcodeName); if (!MaybeOpcode) { P.diagnose(OpcodeLoc, diag::expected_sil_instr_opcode); return true; } Opcode = MaybeOpcode.getValue(); P.consumeToken(); return false; } static bool peekSILDebugLocation(Parser &P) { auto T = P.peekToken().getText(); return P.Tok.is(tok::comma) && (T == "loc" || T == "scope"); } bool SILParser::parseSILDebugVar(SILDebugVariable &Var) { while (P.Tok.is(tok::comma) && !peekSILDebugLocation(P)) { P.consumeToken(); StringRef Key = P.Tok.getText(); if (Key == "name") { P.consumeToken(); if (P.Tok.getKind() != tok::string_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string"); return true; } // Drop the double quotes. StringRef Val = P.Tok.getText().drop_front().drop_back(); Var.Name = Val; } else if (Key == "argno") { P.consumeToken(); if (P.Tok.getKind() != tok::integer_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer"); return true; } uint16_t ArgNo; if (parseIntegerLiteral(P.Tok.getText(), 0, ArgNo)) return true; Var.ArgNo = ArgNo; } else if (Key == "let") { Var.Constant = true; } else if (Key == "var") { Var.Constant = false; } else if (Key == "loc") { Var.Constant = false; } else { P.diagnose(P.Tok, diag::sil_dbg_unknown_key, Key); return true; } P.consumeToken(); } return false; } bool SILParser::parseSILBBArgsAtBranch(SmallVector<SILValue, 6> &Args, SILBuilder &B) { if (P.Tok.is(tok::l_paren)) { SourceLoc LParenLoc = P.consumeToken(tok::l_paren); SourceLoc RParenLoc; bool HasError = false; if (P.parseList(tok::r_paren, LParenLoc, RParenLoc, /*AllowSepAfterLast=*/false, diag::sil_basicblock_arg_rparen, SyntaxKind::Unknown, [&]() -> ParserStatus { SILValue Arg; SourceLoc ArgLoc; if (parseTypedValueRef(Arg, ArgLoc, B)) { HasError = true; return makeParserError(); } Args.push_back(Arg); return makeParserSuccess(); }).isError() || HasError) return true; } return false; } /// Bind any unqualified 'Self' references to the given protocol's 'Self' /// generic parameter. /// /// FIXME: This is a hack to work around the lack of a DeclContext for /// witness tables. static void bindProtocolSelfInTypeRepr(TypeRepr *typeRepr, ProtocolDecl *proto) { assert(typeRepr); // AST walker to update 'Self' references. class BindProtocolSelf : public ASTWalker { ProtocolDecl *proto; GenericTypeParamDecl *selfParam; Identifier selfId; public: BindProtocolSelf(ProtocolDecl *proto) : proto(proto), selfParam(proto->getProtocolSelfType()->getDecl()), selfId(proto->getASTContext().Id_Self) { } virtual bool walkToTypeReprPre(TypeRepr *T) override { if (auto ident = dyn_cast<IdentTypeRepr>(T)) { auto firstComponent = ident->getComponentRange().front(); if (firstComponent->getNameRef().isSimpleName(selfId)) firstComponent->setValue(selfParam, proto); } return true; } }; typeRepr->walk(BindProtocolSelf(proto)); } /// Parse the substitution list for an apply instruction or /// specialized protocol conformance. bool SILParser::parseSubstitutions(SmallVectorImpl<ParsedSubstitution> &parsed, GenericEnvironment *GenericEnv, ProtocolDecl *defaultForProto) { // Check for an opening '<' bracket. if (!P.startsWithLess(P.Tok)) return false; P.consumeStartingLess(); // Parse a list of Substitutions. do { SourceLoc Loc = P.Tok.getLoc(); // Parse substitution as AST type. ParserResult<TypeRepr> TyR = P.parseType(); if (TyR.isNull()) return true; if (defaultForProto) bindProtocolSelfInTypeRepr(TyR.get(), defaultForProto); const auto Ty = performTypeResolution(TyR.get(), /*IsSILType=*/false, GenericEnv); if (Ty->hasError()) return true; parsed.push_back({Loc, Ty}); } while (P.consumeIf(tok::comma)); // Consume the closing '>'. if (!P.startsWithGreater(P.Tok)) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ">"); return true; } P.consumeStartingGreater(); return false; } /// Collect conformances by looking up the conformance from replacement /// type and protocol decl. static bool getConformancesForSubstitution(Parser &P, ExistentialLayout::ProtocolTypeArrayRef protocols, Type subReplacement, SourceLoc loc, SmallVectorImpl<ProtocolConformanceRef> &conformances) { auto M = P.SF.getParentModule(); for (auto protoTy : protocols) { auto conformance = M->lookupConformance(subReplacement, protoTy->getDecl()); if (conformance.isInvalid()) { P.diagnose(loc, diag::sil_substitution_mismatch, subReplacement, protoTy); return true; } conformances.push_back(conformance); } return false; } /// Reconstruct an AST substitution map from parsed substitutions. SubstitutionMap getApplySubstitutionsFromParsed( SILParser &SP, GenericEnvironment *env, ArrayRef<ParsedSubstitution> parses) { if (parses.empty()) { assert(!env); return SubstitutionMap(); } assert(env); auto loc = parses[0].loc; // Ensure that we have the right number of type arguments. auto genericSig = env->getGenericSignature(); if (parses.size() != genericSig->getGenericParams().size()) { bool hasTooFew = parses.size() < genericSig->getGenericParams().size(); SP.P.diagnose(loc, hasTooFew ? diag::sil_missing_substitutions : diag::sil_too_many_substitutions); return SubstitutionMap(); } bool failed = false; auto subMap = SubstitutionMap::get( genericSig, [&](SubstitutableType *type) -> Type { auto genericParam = dyn_cast<GenericTypeParamType>(type); if (!genericParam) return nullptr; auto index = genericSig->getGenericParamOrdinal(genericParam); assert(index < genericSig->getGenericParams().size()); assert(index < parses.size()); // Provide the replacement type. return parses[index].replacement; }, [&](CanType dependentType, Type replacementType, ProtocolDecl *proto) -> ProtocolConformanceRef { auto M = SP.P.SF.getParentModule(); if (auto conformance = M->lookupConformance(replacementType, proto)) return conformance; SP.P.diagnose(loc, diag::sil_substitution_mismatch, replacementType, proto->getDeclaredInterfaceType()); failed = true; return ProtocolConformanceRef(proto); }); return failed ? SubstitutionMap() : subMap; } static ArrayRef<ProtocolConformanceRef> collectExistentialConformances(Parser &P, CanType conformingType, SourceLoc loc, CanType protocolType) { auto layout = protocolType.getExistentialLayout(); if (layout.requiresClass()) { if (!conformingType->mayHaveSuperclass() && !conformingType->isObjCExistentialType()) { P.diagnose(loc, diag::sil_not_class, conformingType); } } // FIXME: Check superclass also. auto protocols = layout.getProtocols(); if (protocols.empty()) return {}; SmallVector<ProtocolConformanceRef, 2> conformances; getConformancesForSubstitution(P, protocols, conformingType, loc, conformances); return P.Context.AllocateCopy(conformances); } /// sil-loc ::= 'loc' string-literal ':' [0-9]+ ':' [0-9]+ bool SILParser::parseSILLocation(SILLocation &Loc) { SILLocation::DebugLoc L; if (parseVerbatim("loc")) return true; if (P.Tok.getKind() != tok::string_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string"); return true; } // Drop the double quotes. StringRef File = P.Tok.getText().drop_front().drop_back(); L.Filename = P.Context.getIdentifier(File).str().data(); P.consumeToken(tok::string_literal); if (P.parseToken(tok::colon, diag::expected_colon_in_sil_location)) return true; if (parseInteger(L.Line, diag::sil_invalid_line_in_sil_location)) return true; if (P.parseToken(tok::colon, diag::expected_colon_in_sil_location)) return true; if (parseInteger(L.Column, diag::sil_invalid_column_in_sil_location)) return true; Loc.setDebugInfoLoc(L); return false; } bool SILParser::parseScopeRef(SILDebugScope *&DS) { unsigned Slot; SourceLoc SlotLoc = P.Tok.getLoc(); if (parseInteger(Slot, diag::sil_invalid_scope_slot)) return true; DS = TUState.ScopeSlots[Slot]; if (!DS) { P.diagnose(SlotLoc, diag::sil_scope_undeclared, Slot); return true; } return false; } /// (',' sil-loc)? (',' sil-scope-ref)? bool SILParser::parseSILDebugLocation(SILLocation &L, SILBuilder &B, bool parsedComma) { // Parse the debug information, if any. if (P.Tok.is(tok::comma)) { P.consumeToken(); parsedComma = true; } if (!parsedComma) return false; bool requireScope = false; if (P.Tok.getText() == "loc") { if (parseSILLocation(L)) return true; if (P.Tok.is(tok::comma)) { P.consumeToken(); requireScope = true; } } if (P.Tok.getText() == "scope" || requireScope) { parseVerbatim("scope"); SILDebugScope *DS = nullptr; if (parseScopeRef(DS)) return true; if (DS) B.setCurrentDebugScope(DS); } return false; } static bool parseLoadOwnershipQualifier(LoadOwnershipQualifier &Result, SILParser &P) { StringRef Str; // If we do not parse '[' ... ']', we have unqualified. Set value and return. if (!parseSILOptional(Str, P)) { Result = LoadOwnershipQualifier::Unqualified; return false; } // Then try to parse one of our other qualifiers. We do not support parsing // unqualified here so we use that as our fail value. auto Tmp = llvm::StringSwitch<LoadOwnershipQualifier>(Str) .Case("take", LoadOwnershipQualifier::Take) .Case("copy", LoadOwnershipQualifier::Copy) .Case("trivial", LoadOwnershipQualifier::Trivial) .Default(LoadOwnershipQualifier::Unqualified); // Thus return true (following the conventions in this file) if we fail. if (Tmp == LoadOwnershipQualifier::Unqualified) return true; // Otherwise, assign Result and return false. Result = Tmp; return false; } static bool parseStoreOwnershipQualifier(StoreOwnershipQualifier &Result, SILParser &P) { StringRef Str; // If we do not parse '[' ... ']', we have unqualified. Set value and return. if (!parseSILOptional(Str, P)) { Result = StoreOwnershipQualifier::Unqualified; return false; } // Then try to parse one of our other qualifiers. We do not support parsing // unqualified here so we use that as our fail value. auto Tmp = llvm::StringSwitch<StoreOwnershipQualifier>(Str) .Case("init", StoreOwnershipQualifier::Init) .Case("assign", StoreOwnershipQualifier::Assign) .Case("trivial", StoreOwnershipQualifier::Trivial) .Default(StoreOwnershipQualifier::Unqualified); // Thus return true (following the conventions in this file) if we fail. if (Tmp == StoreOwnershipQualifier::Unqualified) return true; // Otherwise, assign Result and return false. Result = Tmp; return false; } static bool parseAssignOwnershipQualifier(AssignOwnershipQualifier &Result, SILParser &P) { StringRef Str; // If we do not parse '[' ... ']', we have unknown. Set value and return. if (!parseSILOptional(Str, P)) { Result = AssignOwnershipQualifier::Unknown; return false; } // Then try to parse one of our other initialization kinds. We do not support // parsing unknown here so we use that as our fail value. auto Tmp = llvm::StringSwitch<AssignOwnershipQualifier>(Str) .Case("reassign", AssignOwnershipQualifier::Reassign) .Case("reinit", AssignOwnershipQualifier::Reinit) .Case("init", AssignOwnershipQualifier::Init) .Default(AssignOwnershipQualifier::Unknown); // Thus return true (following the conventions in this file) if we fail. if (Tmp == AssignOwnershipQualifier::Unknown) return true; // Otherwise, assign Result and return false. Result = Tmp; return false; } // Parse a list of integer indices, prefaced with the given string label. // Returns true on error. static bool parseIndexList(Parser &P, StringRef label, SmallVectorImpl<unsigned> &indices, const Diagnostic &parseIndexDiag) { SourceLoc loc; // Parse `[<label> <integer_literal>...]`. if (P.parseToken(tok::l_square, diag::sil_autodiff_expected_lsquare, "index list") || P.parseSpecificIdentifier( label, diag::sil_autodiff_expected_index_list_label, label)) return true; while (P.Tok.is(tok::integer_literal)) { unsigned index; if (P.parseUnsignedInteger(index, loc, parseIndexDiag)) return true; indices.push_back(index); } if (P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare, "index list")) return true; return false; }; /// sil-differentiability-witness-config-and-function ::= /// '[' 'parameters' index-subset ']' /// '[' 'results' index-subset ']' /// ('<' 'where' derivative-generic-signature-requirements '>')? /// sil-function-ref /// /// e.g. parameters 0 1] [results 0] <T where T: Differentiable> /// @foo : <T> $(T) -> T static Optional<std::pair<AutoDiffConfig, SILFunction *>> parseSILDifferentiabilityWitnessConfigAndFunction(Parser &P, SILParser &SP, SILLocation L) { // Parse parameter and result indices. SmallVector<unsigned, 8> rawParameterIndices; SmallVector<unsigned, 8> rawResultIndices; if (parseIndexList(P, "parameters", rawParameterIndices, diag::sil_autodiff_expected_parameter_index)) return {}; if (parseIndexList(P, "results", rawResultIndices, diag::sil_autodiff_expected_result_index)) return {}; // Parse witness generic parameter clause. GenericSignature witnessGenSig = GenericSignature(); SourceLoc witnessGenSigStartLoc = P.getEndOfPreviousLoc(); { // Create a new scope to avoid type redefinition errors. Scope genericsScope(&P, ScopeKind::Generics); auto *genericParams = P.maybeParseGenericParams().getPtrOrNull(); if (genericParams) { auto *witnessGenEnv = handleSILGenericParams(genericParams, &P.SF); witnessGenSig = witnessGenEnv->getGenericSignature(); } } // Parse original function name and type. SILFunction *originalFunction = nullptr; if (SP.parseSILFunctionRef(L, originalFunction)) return {}; // Resolve parsed witness generic signature. if (witnessGenSig) { auto origGenSig = originalFunction->getLoweredFunctionType()->getSubstGenericSignature(); // Check whether original function generic signature and parsed witness // generic have the same generic parameters. auto areGenericParametersConsistent = [&]() { llvm::SmallDenseSet<GenericParamKey, 4> genericParamKeys; for (auto *origGP : origGenSig->getGenericParams()) genericParamKeys.insert(GenericParamKey(origGP)); for (auto *witnessGP : witnessGenSig->getGenericParams()) if (!genericParamKeys.erase(GenericParamKey(witnessGP))) return false; return genericParamKeys.empty(); }; if (!areGenericParametersConsistent()) { P.diagnose(witnessGenSigStartLoc, diag::sil_diff_witness_invalid_generic_signature, witnessGenSig->getAsString(), origGenSig->getAsString()); return {}; } // Combine parsed witness requirements with original function generic // signature requirements to form full witness generic signature. SmallVector<Requirement, 4> witnessRequirements( witnessGenSig->getRequirements().begin(), witnessGenSig->getRequirements().end()); witnessGenSig = evaluateOrDefault( P.Context.evaluator, AbstractGenericSignatureRequest{origGenSig.getPointer(), /*addedGenericParams=*/{}, std::move(witnessRequirements)}, nullptr); } auto origFnType = originalFunction->getLoweredFunctionType(); auto *parameterIndices = IndexSubset::get( P.Context, origFnType->getNumParameters(), rawParameterIndices); auto *resultIndices = IndexSubset::get(P.Context, origFnType->getNumResults(), rawResultIndices); AutoDiffConfig config(parameterIndices, resultIndices, witnessGenSig); return std::make_pair(config, originalFunction); } bool SILParser::parseSILDeclRef(SILDeclRef &Member, bool FnTypeRequired) { SourceLoc TyLoc; SmallVector<ValueDecl *, 4> values; if (parseSILDeclRef(Member, values)) return true; // : ( or : < means that what follows is function type. if (!P.Tok.is(tok::colon)) return false; if (FnTypeRequired && !P.peekToken().is(tok::l_paren) && !P.startsWithLess(P.peekToken())) return false; // Type of the SILDeclRef is optional to be compatible with the old format. if (!P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":")) { // Parse the type for SILDeclRef. Optional<Scope> GenericsScope; GenericsScope.emplace(&P, ScopeKind::Generics); ParserResult<TypeRepr> TyR = P.parseType(); GenericsScope.reset(); if (TyR.isNull()) return true; // The type can be polymorphic. GenericEnvironment *genericEnv = nullptr; if (auto fnType = dyn_cast<FunctionTypeRepr>(TyR.get())) { if (auto generics = fnType->getGenericParams()) { genericEnv = handleSILGenericParams(generics, &P.SF); fnType->setGenericEnvironment(genericEnv); } if (auto generics = fnType->getPatternGenericParams()) { genericEnv = handleSILGenericParams(generics, &P.SF); fnType->setPatternGenericEnvironment(genericEnv); } } const auto Ty = performTypeResolution(TyR.get(), /*IsSILType=*/false, genericEnv); if (Ty->hasError()) return true; // Pick the ValueDecl that has the right type. ValueDecl *TheDecl = nullptr; auto declTy = Ty->getCanonicalType(); for (unsigned I = 0, E = values.size(); I < E; ++I) { auto *decl = values[I]; auto lookupTy = decl->getInterfaceType() ->removeArgumentLabels(decl->getNumCurryLevels()); if (declTy == lookupTy->getCanonicalType()) { TheDecl = decl; // Update SILDeclRef to point to the right Decl. Member.loc = decl; break; } if (values.size() == 1 && !TheDecl) { P.diagnose(TyLoc, diag::sil_member_decl_type_mismatch, declTy, lookupTy); return true; } } if (!TheDecl) { P.diagnose(TyLoc, diag::sil_member_decl_not_found); return true; } } return false; } bool SILParser::parseKeyPathPatternComponent(KeyPathPatternComponent &component, SmallVectorImpl<SILType> &operandTypes, SourceLoc componentLoc, Identifier componentKind, SILLocation InstLoc, GenericEnvironment *patternEnv) { auto parseComponentIndices = [&](SmallVectorImpl<KeyPathPatternComponent::Index> &indexes) -> bool { while (true) { unsigned index; CanType formalTy; SILType loweredTy; if (P.parseToken(tok::oper_prefix, diag::expected_tok_in_sil_instr, "%") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$")) return true; if (!P.Tok.is(tok::integer_literal) || parseIntegerLiteral(P.Tok.getText(), 0, index)) return true; P.consumeToken(tok::integer_literal); SourceLoc formalTyLoc; SourceLoc loweredTyLoc; GenericEnvironment *ignoredParsedEnv; if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(formalTy, formalTyLoc, patternEnv) || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(loweredTy, loweredTyLoc, ignoredParsedEnv, patternEnv)) return true; if (patternEnv) loweredTy = SILType::getPrimitiveType( loweredTy.getASTType()->mapTypeOutOfContext() ->getCanonicalType(), loweredTy.getCategory()); // Formal type must be hashable. auto proto = P.Context.getProtocol(KnownProtocolKind::Hashable); Type contextFormalTy = formalTy; if (patternEnv) contextFormalTy = patternEnv->mapTypeIntoContext(formalTy); auto lookup = P.SF.getParentModule()->lookupConformance( contextFormalTy, proto); if (lookup.isInvalid()) { P.diagnose(formalTyLoc, diag::sil_keypath_index_not_hashable, formalTy); return true; } auto conformance = ProtocolConformanceRef(lookup); indexes.push_back({index, formalTy, loweredTy, conformance}); if (operandTypes.size() <= index) operandTypes.resize(index+1); if (operandTypes[index] && operandTypes[index] != loweredTy) { P.diagnose(loweredTyLoc, diag::sil_keypath_index_operand_type_conflict, index, operandTypes[index].getASTType(), loweredTy.getASTType()); return true; } operandTypes[index] = loweredTy; if (P.consumeIf(tok::comma)) continue; if (P.consumeIf(tok::r_square)) break; return true; } return false; }; if (componentKind.str() == "stored_property") { ValueDecl *prop; CanType ty; if (parseSILDottedPath(prop) || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(ty, patternEnv)) return true; component = KeyPathPatternComponent::forStoredProperty(cast<VarDecl>(prop), ty); return false; } else if (componentKind.str() == "gettable_property" || componentKind.str() == "settable_property") { bool isSettable = componentKind.str()[0] == 's'; CanType componentTy; if (P.parseToken(tok::sil_dollar,diag::expected_tok_in_sil_instr,"$") || parseASTType(componentTy, patternEnv) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; SILFunction *idFn = nullptr; SILDeclRef idDecl; VarDecl *idProperty = nullptr; SILFunction *getter = nullptr; SILFunction *setter = nullptr; SILFunction *equals = nullptr; SILFunction *hash = nullptr; AbstractStorageDecl *externalDecl = nullptr; SubstitutionMap externalSubs; SmallVector<KeyPathPatternComponent::Index, 4> indexes; while (true) { Identifier subKind; SourceLoc subKindLoc; if (parseSILIdentifier(subKind, subKindLoc, diag::sil_keypath_expected_component_kind)) return true; if (subKind.str() == "id") { // The identifier can be either a function ref, a SILDeclRef // to a class or protocol method, or a decl ref to a property: // @static_fn_ref : $... // #Type.method!whatever : (T) -> ... // ##Type.property if (P.Tok.is(tok::at_sign)) { if (parseSILFunctionRef(InstLoc, idFn)) return true; } else if (P.Tok.is(tok::pound)) { if (P.peekToken().is(tok::pound)) { ValueDecl *propertyValueDecl; P.consumeToken(tok::pound); if (parseSILDottedPath(propertyValueDecl)) return true; idProperty = cast<VarDecl>(propertyValueDecl); } else if (parseSILDeclRef(idDecl, /*fnType*/ true)) return true; } else { P.diagnose(subKindLoc, diag::expected_tok_in_sil_instr, "# or @"); return true; } } else if (subKind.str() == "getter" || subKind.str() == "setter") { bool isSetter = subKind.str()[0] == 's'; if (parseSILFunctionRef(InstLoc, isSetter ? setter : getter)) return true; } else if (subKind.str() == "indices") { if (P.parseToken(tok::l_square, diag::expected_tok_in_sil_instr, "[") || parseComponentIndices(indexes)) return true; } else if (subKind.str() == "indices_equals") { if (parseSILFunctionRef(InstLoc, equals)) return true; } else if (subKind.str() == "indices_hash") { if (parseSILFunctionRef(InstLoc, hash)) return true; } else if (subKind.str() == "external") { ValueDecl *parsedExternalDecl; SmallVector<ParsedSubstitution, 4> parsedSubs; if (parseSILDottedPath(parsedExternalDecl) || parseSubstitutions(parsedSubs, patternEnv)) return true; externalDecl = cast<AbstractStorageDecl>(parsedExternalDecl); if (!parsedSubs.empty()) { auto genericEnv = externalDecl->getInnermostDeclContext() ->getGenericEnvironmentOfContext(); if (!genericEnv) { P.diagnose(P.Tok, diag::sil_substitutions_on_non_polymorphic_type); return true; } externalSubs = getApplySubstitutionsFromParsed(*this, genericEnv, parsedSubs); if (!externalSubs) return true; // Map the substitutions out of the pattern context so that they // use interface types. externalSubs = externalSubs.mapReplacementTypesOutOfContext().getCanonical(); } } else { P.diagnose(subKindLoc, diag::sil_keypath_unknown_component_kind, subKind); return true; } if (!P.consumeIf(tok::comma)) break; } if ((idFn == nullptr && idDecl.isNull() && idProperty == nullptr) || getter == nullptr || (isSettable && setter == nullptr)) { P.diagnose(componentLoc, diag::sil_keypath_computed_property_missing_part, isSettable); return true; } if ((idFn != nullptr) + (!idDecl.isNull()) + (idProperty != nullptr) != 1) { P.diagnose(componentLoc, diag::sil_keypath_computed_property_missing_part, isSettable); return true; } KeyPathPatternComponent::ComputedPropertyId id; if (idFn) id = idFn; else if (!idDecl.isNull()) id = idDecl; else if (idProperty) id = idProperty; else llvm_unreachable("no id?!"); auto indexesCopy = P.Context.AllocateCopy(indexes); if (!indexes.empty() && (!equals || !hash)) { P.diagnose(componentLoc, diag::sil_keypath_computed_property_missing_part, isSettable); } if (isSettable) { component = KeyPathPatternComponent::forComputedSettableProperty( id, getter, setter, indexesCopy, equals, hash, externalDecl, externalSubs, componentTy); } else { component = KeyPathPatternComponent::forComputedGettableProperty( id, getter, indexesCopy, equals, hash, externalDecl, externalSubs, componentTy); } return false; } else if (componentKind.str() == "optional_wrap" || componentKind.str() == "optional_chain" || componentKind.str() == "optional_force") { CanType ty; if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(ty, patternEnv)) return true; KeyPathPatternComponent::Kind kind; if (componentKind.str() == "optional_wrap") { kind = KeyPathPatternComponent::Kind::OptionalWrap; } else if (componentKind.str() == "optional_chain") { kind = KeyPathPatternComponent::Kind::OptionalChain; } else if (componentKind.str() == "optional_force") { kind = KeyPathPatternComponent::Kind::OptionalForce; } else { llvm_unreachable("unpossible"); } component = KeyPathPatternComponent::forOptional(kind, ty); return false; } else if (componentKind.str() == "tuple_element") { unsigned tupleIndex; CanType ty; if (P.parseToken(tok::pound, diag::expected_sil_constant) || parseInteger(tupleIndex, diag::expected_sil_tuple_index) || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(ty, patternEnv)) return true; component = KeyPathPatternComponent::forTupleElement(tupleIndex, ty); return false; } else { P.diagnose(componentLoc, diag::sil_keypath_unknown_component_kind, componentKind); return true; } } bool SILParser::parseSpecificSILInstruction(SILBuilder &B, SILInstructionKind Opcode, SourceLoc OpcodeLoc, StringRef OpcodeName, SILInstruction *&ResultVal) { SmallVector<SILValue, 4> OpList; SILValue Val; SILType Ty; SILLocation InstLoc = RegularLocation(OpcodeLoc); auto parseFormalTypeAndValue = [&](CanType &formalType, SILValue &value) -> bool { return (parseASTType(formalType) || parseVerbatim("in") || parseTypedValueRef(value, B)); }; OpenedExistentialAccess AccessKind; auto parseOpenExistAddrKind = [&]() -> bool { Identifier accessKindToken; SourceLoc accessKindLoc; if (parseSILIdentifier(accessKindToken, accessKindLoc, diag::expected_tok_in_sil_instr, "opened existential access kind")) { return true; } auto kind = llvm::StringSwitch<Optional<OpenedExistentialAccess>>( accessKindToken.str()) .Case("mutable_access", OpenedExistentialAccess::Mutable) .Case("immutable_access", OpenedExistentialAccess::Immutable) .Default(None); if (kind) { AccessKind = kind.getValue(); return false; } P.diagnose(accessKindLoc, diag::expected_tok_in_sil_instr, "opened existential access kind"); return true; }; CanType SourceType, TargetType; SILValue SourceAddr, DestAddr; auto parseSourceAndDestAddress = [&] { return parseFormalTypeAndValue(SourceType, SourceAddr) || parseVerbatim("to") || parseFormalTypeAndValue(TargetType, DestAddr); }; Identifier SuccessBBName, FailureBBName; SourceLoc SuccessBBLoc, FailureBBLoc; auto parseConditionalBranchDestinations = [&] { return P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(SuccessBBName, SuccessBBLoc, diag::expected_sil_block_name) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(FailureBBName, FailureBBLoc, diag::expected_sil_block_name) || parseSILDebugLocation(InstLoc, B); }; // Validate the opcode name, and do opcode-specific parsing logic based on the // opcode we find. switch (Opcode) { case SILInstructionKind::AllocBoxInst: { bool hasDynamicLifetime = false; if (parseSILOptional(hasDynamicLifetime, *this, "dynamic_lifetime")) return true; SILType Ty; if (parseSILType(Ty)) return true; SILDebugVariable VarInfo; if (parseSILDebugVar(VarInfo)) return true; if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createAllocBox(InstLoc, Ty.castTo<SILBoxType>(), VarInfo, hasDynamicLifetime); break; } case SILInstructionKind::ApplyInst: case SILInstructionKind::BeginApplyInst: case SILInstructionKind::PartialApplyInst: case SILInstructionKind::TryApplyInst: if (parseCallInstruction(InstLoc, Opcode, B, ResultVal)) return true; break; case SILInstructionKind::AbortApplyInst: case SILInstructionKind::EndApplyInst: { UnresolvedValueName argName; if (parseValueName(argName)) return true; if (parseSILDebugLocation(InstLoc, B)) return true; SILType expectedTy = SILType::getSILTokenType(P.Context); SILValue op = getLocalValue(argName, expectedTy, InstLoc, B); if (Opcode == SILInstructionKind::AbortApplyInst) { ResultVal = B.createAbortApply(InstLoc, op); } else { ResultVal = B.createEndApply(InstLoc, op); } break; } case SILInstructionKind::IntegerLiteralInst: { SILType Ty; if (parseSILType(Ty) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; bool Negative = false; if (P.Tok.isAnyOperator() && P.Tok.getText() == "-") { Negative = true; P.consumeToken(); } if (P.Tok.getKind() != tok::integer_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer"); return true; } auto intTy = Ty.getAs<AnyBuiltinIntegerType>(); if (!intTy) { P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type); return true; } StringRef text = prepareIntegerLiteralForParsing(P.Tok.getText()); bool error; APInt value = intTy->getWidth().parse(text, 0, Negative, &error); if (error) { P.diagnose(P.Tok, diag::sil_integer_literal_not_well_formed, intTy); return true; } P.consumeToken(tok::integer_literal); if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createIntegerLiteral(InstLoc, Ty, value); break; } case SILInstructionKind::FloatLiteralInst: { SILType Ty; if (parseSILType(Ty) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; // The value is expressed as bits. if (P.Tok.getKind() != tok::integer_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer"); return true; } auto floatTy = Ty.getAs<BuiltinFloatType>(); if (!floatTy) { P.diagnose(P.Tok, diag::sil_float_literal_not_float_type); return true; } StringRef text = prepareIntegerLiteralForParsing(P.Tok.getText()); APInt bits(floatTy->getBitWidth(), 0); bool error = text.getAsInteger(0, bits); assert(!error && "float_literal token did not parse as APInt?!"); (void)error; if (bits.getBitWidth() != floatTy->getBitWidth()) bits = bits.zextOrTrunc(floatTy->getBitWidth()); APFloat value(floatTy->getAPFloatSemantics(), bits); if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createFloatLiteral(InstLoc, Ty, value); P.consumeToken(tok::integer_literal); break; } case SILInstructionKind::StringLiteralInst: { if (P.Tok.getKind() != tok::identifier) { P.diagnose(P.Tok, diag::sil_string_no_encoding); return true; } StringLiteralInst::Encoding encoding; if (P.Tok.getText() == "utf8") { encoding = StringLiteralInst::Encoding::UTF8; } else if (P.Tok.getText() == "objc_selector") { encoding = StringLiteralInst::Encoding::ObjCSelector; } else if (P.Tok.getText() == "bytes") { encoding = StringLiteralInst::Encoding::Bytes; } else { P.diagnose(P.Tok, diag::sil_string_invalid_encoding, P.Tok.getText()); return true; } P.consumeToken(tok::identifier); if (P.Tok.getKind() != tok::string_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string"); return true; } // Parse the string. SmallVector<Lexer::StringSegment, 1> segments; P.L->getStringLiteralSegments(P.Tok, segments); assert(segments.size() == 1); P.consumeToken(tok::string_literal); if (parseSILDebugLocation(InstLoc, B)) return true; SmallVector<char, 128> stringBuffer; if (encoding == StringLiteralInst::Encoding::Bytes) { // Decode hex bytes. CharSourceRange rawStringRange(segments.front().Loc, segments.front().Length); StringRef rawString = P.SourceMgr.extractText(rawStringRange); if (rawString.size() & 1) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "even number of hex bytes"); return true; } while (!rawString.empty()) { unsigned byte1 = llvm::hexDigitValue(rawString[0]); unsigned byte2 = llvm::hexDigitValue(rawString[1]); if (byte1 == -1U || byte2 == -1U) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "hex bytes should contain 0-9, a-f, A-F only"); return true; } stringBuffer.push_back((unsigned char)(byte1 << 4) | byte2); rawString = rawString.drop_front(2); } ResultVal = B.createStringLiteral(InstLoc, stringBuffer, encoding); break; } StringRef string = P.L->getEncodedStringSegment(segments.front(), stringBuffer); ResultVal = B.createStringLiteral(InstLoc, string, encoding); break; } case SILInstructionKind::CondFailInst: { if (parseTypedValueRef(Val, B)) return true; SmallVector<char, 128> stringBuffer; StringRef message; if (P.consumeIf(tok::comma)) { // Parse the string. if (P.Tok.getKind() != tok::string_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string"); return true; } SmallVector<Lexer::StringSegment, 1> segments; P.L->getStringLiteralSegments(P.Tok, segments); assert(segments.size() == 1); P.consumeToken(tok::string_literal); message = P.L->getEncodedStringSegment(segments.front(), stringBuffer); } if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createCondFail(InstLoc, Val, message); break; } case SILInstructionKind::AllocValueBufferInst: { SILType Ty; if (parseSILType(Ty) || parseVerbatim("in") || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createAllocValueBuffer(InstLoc, Ty, Val); break; } case SILInstructionKind::ProjectValueBufferInst: { SILType Ty; if (parseSILType(Ty) || parseVerbatim("in") || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createProjectValueBuffer(InstLoc, Ty, Val); break; } case SILInstructionKind::DeallocValueBufferInst: { SILType Ty; if (parseSILType(Ty) || parseVerbatim("in") || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeallocValueBuffer(InstLoc, Ty, Val); break; } case SILInstructionKind::ProjectBoxInst: { if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; if (!P.Tok.is(tok::integer_literal)) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer"); return true; } unsigned Index; bool error = parseIntegerLiteral(P.Tok.getText(), 0, Index); assert(!error && "project_box index did not parse as integer?!"); (void)error; P.consumeToken(tok::integer_literal); if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createProjectBox(InstLoc, Val, Index); break; } case SILInstructionKind::ProjectExistentialBoxInst: { SILType Ty; if (parseSILType(Ty) || parseVerbatim("in") || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createProjectExistentialBox(InstLoc, Ty, Val); break; } case SILInstructionKind::FunctionRefInst: { SILFunction *Fn; if (parseSILFunctionRef(InstLoc, Fn) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createFunctionRef(InstLoc, Fn); break; } case SILInstructionKind::DynamicFunctionRefInst: { SILFunction *Fn; if (parseSILFunctionRef(InstLoc, Fn) || parseSILDebugLocation(InstLoc, B)) return true; // Set a forward reference's dynamic property for the first time. if (!Fn->isDynamicallyReplaceable()) { if (!Fn->empty()) { P.diagnose(P.Tok, diag::expected_dynamic_func_attr); return true; } Fn->setIsDynamic(); } ResultVal = B.createDynamicFunctionRef(InstLoc, Fn); break; } case SILInstructionKind::PreviousDynamicFunctionRefInst: { SILFunction *Fn; if (parseSILFunctionRef(InstLoc, Fn) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createPreviousDynamicFunctionRef(InstLoc, Fn); break; } case SILInstructionKind::BuiltinInst: { if (P.Tok.getKind() != tok::string_literal) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "builtin name"); return true; } StringRef Str = P.Tok.getText(); Identifier Id = P.Context.getIdentifier(Str.substr(1, Str.size() - 2)); P.consumeToken(tok::string_literal); // Find the builtin in the Builtin module SmallVector<ValueDecl *, 2> foundBuiltins; P.Context.TheBuiltinModule->lookupMember( foundBuiltins, P.Context.TheBuiltinModule, Id, Identifier()); if (foundBuiltins.empty()) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "builtin name"); return true; } assert(foundBuiltins.size() == 1 && "ambiguous builtin name?!"); auto *builtinFunc = cast<FuncDecl>(foundBuiltins[0]); GenericEnvironment *genericEnv = builtinFunc->getGenericEnvironment(); SmallVector<ParsedSubstitution, 4> parsedSubs; SubstitutionMap subMap; if (parseSubstitutions(parsedSubs)) return true; if (!parsedSubs.empty()) { if (!genericEnv) { P.diagnose(P.Tok, diag::sil_substitutions_on_non_polymorphic_type); return true; } subMap = getApplySubstitutionsFromParsed(*this, genericEnv, parsedSubs); if (!subMap) return true; } if (P.Tok.getKind() != tok::l_paren) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "("); return true; } P.consumeToken(tok::l_paren); SmallVector<SILValue, 4> Args; while (true) { if (P.consumeIf(tok::r_paren)) break; SILValue Val; if (parseTypedValueRef(Val, B)) return true; Args.push_back(Val); if (P.consumeIf(tok::comma)) continue; if (P.consumeIf(tok::r_paren)) break; P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ")' or ',"); return true; } if (P.Tok.getKind() != tok::colon) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ":"); return true; } P.consumeToken(tok::colon); SILType ResultTy; if (parseSILType(ResultTy)) return true; if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createBuiltin(InstLoc, Id, ResultTy, subMap, Args); break; } case SILInstructionKind::OpenExistentialAddrInst: if (parseOpenExistAddrKind() || parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createOpenExistentialAddr(InstLoc, Val, Ty, AccessKind); break; case SILInstructionKind::OpenExistentialBoxInst: if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createOpenExistentialBox(InstLoc, Val, Ty); break; case SILInstructionKind::OpenExistentialBoxValueInst: if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createOpenExistentialBoxValue(InstLoc, Val, Ty); break; case SILInstructionKind::OpenExistentialMetatypeInst: if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createOpenExistentialMetatype(InstLoc, Val, Ty); break; case SILInstructionKind::OpenExistentialRefInst: if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createOpenExistentialRef(InstLoc, Val, Ty); break; case SILInstructionKind::OpenExistentialValueInst: if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createOpenExistentialValue(InstLoc, Val, Ty); break; #define UNARY_INSTRUCTION(ID) \ case SILInstructionKind::ID##Inst: \ if (parseTypedValueRef(Val, B)) \ return true; \ if (parseSILDebugLocation(InstLoc, B)) \ return true; \ ResultVal = B.create##ID(InstLoc, Val); \ break; #define REFCOUNTING_INSTRUCTION(ID) \ case SILInstructionKind::ID##Inst: { \ Atomicity atomicity = Atomicity::Atomic; \ StringRef Optional; \ if (parseSILOptional(Optional, *this)) { \ if (Optional == "nonatomic") { \ atomicity = Atomicity::NonAtomic; \ } else { \ return true; \ } \ } \ if (parseTypedValueRef(Val, B)) \ return true; \ if (parseSILDebugLocation(InstLoc, B)) \ return true; \ ResultVal = B.create##ID(InstLoc, Val, atomicity); \ } break; UNARY_INSTRUCTION(ClassifyBridgeObject) UNARY_INSTRUCTION(ValueToBridgeObject) UNARY_INSTRUCTION(FixLifetime) UNARY_INSTRUCTION(EndLifetime) UNARY_INSTRUCTION(CopyBlock) UNARY_INSTRUCTION(IsUnique) UNARY_INSTRUCTION(DestroyAddr) UNARY_INSTRUCTION(CopyValue) UNARY_INSTRUCTION(DestroyValue) UNARY_INSTRUCTION(EndBorrow) UNARY_INSTRUCTION(DestructureStruct) UNARY_INSTRUCTION(DestructureTuple) REFCOUNTING_INSTRUCTION(UnmanagedReleaseValue) REFCOUNTING_INSTRUCTION(UnmanagedRetainValue) REFCOUNTING_INSTRUCTION(UnmanagedAutoreleaseValue) REFCOUNTING_INSTRUCTION(StrongRetain) REFCOUNTING_INSTRUCTION(StrongRelease) REFCOUNTING_INSTRUCTION(AutoreleaseValue) REFCOUNTING_INSTRUCTION(SetDeallocating) REFCOUNTING_INSTRUCTION(ReleaseValue) REFCOUNTING_INSTRUCTION(RetainValue) REFCOUNTING_INSTRUCTION(ReleaseValueAddr) REFCOUNTING_INSTRUCTION(RetainValueAddr) #define UNCHECKED_REF_STORAGE(Name, ...) \ UNARY_INSTRUCTION(StrongCopy##Name##Value) #define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \ REFCOUNTING_INSTRUCTION(StrongRetain##Name) \ REFCOUNTING_INSTRUCTION(Name##Retain) \ REFCOUNTING_INSTRUCTION(Name##Release) \ UNARY_INSTRUCTION(StrongCopy##Name##Value) #include "swift/AST/ReferenceStorage.def" #undef UNARY_INSTRUCTION #undef REFCOUNTING_INSTRUCTION case SILInstructionKind::BeginCOWMutationInst: { bool native = false; if (parseSILOptional(native, *this, "native") || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createBeginCOWMutation(InstLoc, Val, native); break; } case SILInstructionKind::EndCOWMutationInst: { bool keepUnique = false; if (parseSILOptional(keepUnique, *this, "keep_unique") || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createEndCOWMutation(InstLoc, Val, keepUnique); break; } case SILInstructionKind::IsEscapingClosureInst: { bool IsObjcVerifcationType = false; if (parseSILOptional(IsObjcVerifcationType, *this, "objc")) return true; if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createIsEscapingClosure( InstLoc, Val, IsObjcVerifcationType ? IsEscapingClosureInst::ObjCEscaping : IsEscapingClosureInst::WithoutActuallyEscaping); break; } case SILInstructionKind::DebugValueInst: case SILInstructionKind::DebugValueAddrInst: { SILDebugVariable VarInfo; if (parseTypedValueRef(Val, B) || parseSILDebugVar(VarInfo) || parseSILDebugLocation(InstLoc, B)) return true; if (Opcode == SILInstructionKind::DebugValueInst) ResultVal = B.createDebugValue(InstLoc, Val, VarInfo); else ResultVal = B.createDebugValueAddr(InstLoc, Val, VarInfo); break; } // unchecked_ownership_conversion <reg> : <type>, <ownership> to <ownership> case SILInstructionKind::UncheckedOwnershipConversionInst: { ValueOwnershipKind LHSKind = ValueOwnershipKind::None; ValueOwnershipKind RHSKind = ValueOwnershipKind::None; SourceLoc Loc; if (parseTypedValueRef(Val, Loc, B) || P.parseToken(tok::comma, diag::expected_sil_colon, "unchecked_ownership_conversion value ownership kind " "conversion specification") || parseSILOwnership(LHSKind) || parseVerbatim("to") || parseSILOwnership(RHSKind) || parseSILDebugLocation(InstLoc, B)) { return true; } if (Val.getOwnershipKind() != LHSKind) { return true; } ResultVal = B.createUncheckedOwnershipConversion(InstLoc, Val, RHSKind); break; } case SILInstructionKind::LoadInst: { LoadOwnershipQualifier Qualifier; SourceLoc AddrLoc; if (parseLoadOwnershipQualifier(Qualifier, *this) || parseTypedValueRef(Val, AddrLoc, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createLoad(InstLoc, Val, Qualifier); break; } case SILInstructionKind::LoadBorrowInst: { SourceLoc AddrLoc; if (parseTypedValueRef(Val, AddrLoc, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createLoadBorrow(InstLoc, Val); break; } case SILInstructionKind::BeginBorrowInst: { SourceLoc AddrLoc; if (parseTypedValueRef(Val, AddrLoc, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createBeginBorrow(InstLoc, Val); break; } #define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \ case SILInstructionKind::Load##Name##Inst: { \ bool isTake = false; \ SourceLoc addrLoc; \ if (parseSILOptional(isTake, *this, "take") || \ parseTypedValueRef(Val, addrLoc, B) || \ parseSILDebugLocation(InstLoc, B)) \ return true; \ if (!Val->getType().is<Name##StorageType>()) { \ P.diagnose(addrLoc, diag::sil_operand_not_ref_storage_address, "source", \ OpcodeName, ReferenceOwnership::Name); \ } \ ResultVal = B.createLoad##Name(InstLoc, Val, IsTake_t(isTake)); \ break; \ } #include "swift/AST/ReferenceStorage.def" case SILInstructionKind::CopyBlockWithoutEscapingInst: { SILValue Closure; if (parseTypedValueRef(Val, B) || parseVerbatim("withoutEscaping") || parseTypedValueRef(Closure, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createCopyBlockWithoutEscaping(InstLoc, Val, Closure); break; } case SILInstructionKind::MarkDependenceInst: { SILValue Base; if (parseTypedValueRef(Val, B) || parseVerbatim("on") || parseTypedValueRef(Base, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createMarkDependence(InstLoc, Val, Base); break; } case SILInstructionKind::KeyPathInst: { SmallVector<KeyPathPatternComponent, 4> components; SILType Ty; if (parseSILType(Ty) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; GenericParamList *generics = nullptr; GenericEnvironment *patternEnv = nullptr; CanType rootType; StringRef objcString; SmallVector<SILType, 4> operandTypes; { Scope genericsScope(&P, ScopeKind::Generics); generics = P.maybeParseGenericParams().getPtrOrNull(); patternEnv = handleSILGenericParams(generics, &P.SF); if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "(")) return true; while (true) { Identifier componentKind; SourceLoc componentLoc; if (parseSILIdentifier(componentKind, componentLoc, diag::sil_keypath_expected_component_kind)) return true; if (componentKind.str() == "root") { if (P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(rootType, patternEnv)) return true; } else if (componentKind.str() == "objc") { auto tok = P.Tok; if (P.parseToken(tok::string_literal, diag::expected_tok_in_sil_instr, "string literal")) return true; auto objcStringValue = tok.getText().drop_front().drop_back(); objcString = StringRef(P.Context.AllocateCopy<char>(objcStringValue.begin(), objcStringValue.end()), objcStringValue.size()); } else { KeyPathPatternComponent component; if (parseKeyPathPatternComponent(component, operandTypes, componentLoc, componentKind, InstLoc, patternEnv)) return true; components.push_back(component); } if (!P.consumeIf(tok::semi)) break; } if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")") || parseSILDebugLocation(InstLoc, B)) return true; } if (rootType.isNull()) P.diagnose(InstLoc.getSourceLoc(), diag::sil_keypath_no_root); SmallVector<ParsedSubstitution, 4> parsedSubs; if (parseSubstitutions(parsedSubs, ContextGenericEnv)) return true; SubstitutionMap subMap; if (!parsedSubs.empty()) { if (!patternEnv) { P.diagnose(InstLoc.getSourceLoc(), diag::sil_substitutions_on_non_polymorphic_type); return true; } subMap = getApplySubstitutionsFromParsed(*this, patternEnv, parsedSubs); if (!subMap) return true; } SmallVector<SILValue, 4> operands; if (P.consumeIf(tok::l_paren)) { while (true) { SILValue v; if (operands.size() >= operandTypes.size() || !operandTypes[operands.size()]) { P.diagnose(P.Tok, diag::sil_keypath_no_use_of_operand_in_pattern, operands.size()); return true; } auto ty = operandTypes[operands.size()].subst(SILMod, subMap); if (parseValueRef(v, ty, RegularLocation(P.Tok.getLoc()), B)) return true; operands.push_back(v); if (P.consumeIf(tok::comma)) continue; if (P.consumeIf(tok::r_paren)) break; return true; } } if (parseSILDebugLocation(InstLoc, B)) return true; CanGenericSignature canSig; if (patternEnv && patternEnv->getGenericSignature()) { canSig = patternEnv->getGenericSignature().getCanonicalSignature(); } CanType leafType; if (!components.empty()) leafType = components.back().getComponentType(); else leafType = rootType; auto pattern = KeyPathPattern::get(B.getModule(), canSig, rootType, leafType, components, objcString); ResultVal = B.createKeyPath(InstLoc, pattern, subMap, operands, Ty); break; } // Conversion instructions. case SILInstructionKind::UncheckedRefCastInst: case SILInstructionKind::UncheckedAddrCastInst: case SILInstructionKind::UncheckedTrivialBitCastInst: case SILInstructionKind::UncheckedBitwiseCastInst: case SILInstructionKind::UncheckedValueCastInst: case SILInstructionKind::UpcastInst: case SILInstructionKind::AddressToPointerInst: case SILInstructionKind::BridgeObjectToRefInst: case SILInstructionKind::BridgeObjectToWordInst: case SILInstructionKind::RefToRawPointerInst: case SILInstructionKind::RawPointerToRefInst: #define LOADABLE_REF_STORAGE(Name, ...) \ case SILInstructionKind::RefTo##Name##Inst: \ case SILInstructionKind::Name##ToRefInst: #include "swift/AST/ReferenceStorage.def" case SILInstructionKind::ThinFunctionToPointerInst: case SILInstructionKind::PointerToThinFunctionInst: case SILInstructionKind::ThinToThickFunctionInst: case SILInstructionKind::ThickToObjCMetatypeInst: case SILInstructionKind::ObjCToThickMetatypeInst: case SILInstructionKind::ConvertFunctionInst: case SILInstructionKind::ConvertEscapeToNoEscapeInst: case SILInstructionKind::ObjCExistentialMetatypeToObjectInst: case SILInstructionKind::ObjCMetatypeToObjectInst: { SILType Ty; Identifier ToToken; SourceLoc ToLoc; bool not_guaranteed = false; bool without_actually_escaping = false; if (Opcode == SILInstructionKind::ConvertEscapeToNoEscapeInst) { StringRef attrName; if (parseSILOptional(attrName, *this)) { if (attrName.equals("not_guaranteed")) not_guaranteed = true; else return true; } } if (parseTypedValueRef(Val, B) || parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr, "to")) return true; if (ToToken.str() != "to") { P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to"); return true; } if (Opcode == SILInstructionKind::ConvertFunctionInst) { StringRef attrName; if (parseSILOptional(attrName, *this)) { if (attrName.equals("without_actually_escaping")) without_actually_escaping = true; else return true; } } if (parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; switch (Opcode) { default: llvm_unreachable("Out of sync with parent switch"); case SILInstructionKind::UncheckedRefCastInst: ResultVal = B.createUncheckedRefCast(InstLoc, Val, Ty); break; case SILInstructionKind::UncheckedAddrCastInst: ResultVal = B.createUncheckedAddrCast(InstLoc, Val, Ty); break; case SILInstructionKind::UncheckedTrivialBitCastInst: ResultVal = B.createUncheckedTrivialBitCast(InstLoc, Val, Ty); break; case SILInstructionKind::UncheckedBitwiseCastInst: ResultVal = B.createUncheckedBitwiseCast(InstLoc, Val, Ty); break; case SILInstructionKind::UncheckedValueCastInst: ResultVal = B.createUncheckedValueCast(InstLoc, Val, Ty); break; case SILInstructionKind::UpcastInst: ResultVal = B.createUpcast(InstLoc, Val, Ty); break; case SILInstructionKind::ConvertFunctionInst: ResultVal = B.createConvertFunction(InstLoc, Val, Ty, without_actually_escaping); break; case SILInstructionKind::ConvertEscapeToNoEscapeInst: ResultVal = B.createConvertEscapeToNoEscape(InstLoc, Val, Ty, !not_guaranteed); break; case SILInstructionKind::AddressToPointerInst: ResultVal = B.createAddressToPointer(InstLoc, Val, Ty); break; case SILInstructionKind::BridgeObjectToRefInst: ResultVal = B.createBridgeObjectToRef(InstLoc, Val, Ty); break; case SILInstructionKind::BridgeObjectToWordInst: ResultVal = B.createBridgeObjectToWord(InstLoc, Val); break; case SILInstructionKind::RefToRawPointerInst: ResultVal = B.createRefToRawPointer(InstLoc, Val, Ty); break; case SILInstructionKind::RawPointerToRefInst: ResultVal = B.createRawPointerToRef(InstLoc, Val, Ty); break; #define LOADABLE_REF_STORAGE(Name, ...) \ case SILInstructionKind::RefTo##Name##Inst: \ ResultVal = B.createRefTo##Name(InstLoc, Val, Ty); \ break; \ case SILInstructionKind::Name##ToRefInst: \ ResultVal = B.create##Name##ToRef(InstLoc, Val, Ty); \ break; #include "swift/AST/ReferenceStorage.def" case SILInstructionKind::ThinFunctionToPointerInst: ResultVal = B.createThinFunctionToPointer(InstLoc, Val, Ty); break; case SILInstructionKind::PointerToThinFunctionInst: ResultVal = B.createPointerToThinFunction(InstLoc, Val, Ty); break; case SILInstructionKind::ThinToThickFunctionInst: ResultVal = B.createThinToThickFunction(InstLoc, Val, Ty); break; case SILInstructionKind::ThickToObjCMetatypeInst: ResultVal = B.createThickToObjCMetatype(InstLoc, Val, Ty); break; case SILInstructionKind::ObjCToThickMetatypeInst: ResultVal = B.createObjCToThickMetatype(InstLoc, Val, Ty); break; case SILInstructionKind::ObjCMetatypeToObjectInst: ResultVal = B.createObjCMetatypeToObject(InstLoc, Val, Ty); break; case SILInstructionKind::ObjCExistentialMetatypeToObjectInst: ResultVal = B.createObjCExistentialMetatypeToObject(InstLoc, Val, Ty); break; } break; } case SILInstructionKind::PointerToAddressInst: { SILType Ty; Identifier ToToken; SourceLoc ToLoc; StringRef attr; if (parseTypedValueRef(Val, B) || parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr, "to")) return true; if (parseSILOptional(attr, *this) && attr.empty()) return true; if (parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; bool isStrict = attr.equals("strict"); bool isInvariant = attr.equals("invariant"); if (ToToken.str() != "to") { P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to"); return true; } ResultVal = B.createPointerToAddress(InstLoc, Val, Ty, isStrict, isInvariant); break; } case SILInstructionKind::RefToBridgeObjectInst: { SILValue BitsVal; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(BitsVal, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createRefToBridgeObject(InstLoc, Val, BitsVal); break; } case SILInstructionKind::CheckedCastAddrBranchInst: { Identifier consumptionKindToken; SourceLoc consumptionKindLoc; if (parseSILIdentifier(consumptionKindToken, consumptionKindLoc, diag::expected_tok_in_sil_instr, "cast consumption kind")) { return true; } // NOTE: BorrowAlways is not a supported cast kind for address types, so we // purposely do not parse it here. auto kind = llvm::StringSwitch<Optional<CastConsumptionKind>>( consumptionKindToken.str()) .Case("take_always", CastConsumptionKind::TakeAlways) .Case("take_on_success", CastConsumptionKind::TakeOnSuccess) .Case("copy_on_success", CastConsumptionKind::CopyOnSuccess) .Default(None); if (!kind) { P.diagnose(consumptionKindLoc, diag::expected_tok_in_sil_instr, "cast consumption kind"); return true; } auto consumptionKind = kind.getValue(); if (parseSourceAndDestAddress() || parseConditionalBranchDestinations() || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createCheckedCastAddrBranch( InstLoc, consumptionKind, SourceAddr, SourceType, DestAddr, TargetType, getBBForReference(SuccessBBName, SuccessBBLoc), getBBForReference(FailureBBName, FailureBBLoc)); break; } case SILInstructionKind::UncheckedRefCastAddrInst: if (parseSourceAndDestAddress() || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createUncheckedRefCastAddr(InstLoc, SourceAddr, SourceType, DestAddr, TargetType); break; case SILInstructionKind::UnconditionalCheckedCastAddrInst: if (parseSourceAndDestAddress() || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createUnconditionalCheckedCastAddr( InstLoc, SourceAddr, SourceType, DestAddr, TargetType); break; case SILInstructionKind::UnconditionalCheckedCastValueInst: { if (parseASTType(SourceType) || parseVerbatim("in") || parseTypedValueRef(Val, B) || parseVerbatim("to") || parseASTType(TargetType) || parseSILDebugLocation(InstLoc, B)) return true; auto opaque = Lowering::AbstractionPattern::getOpaque(); ResultVal = B.createUnconditionalCheckedCastValue( InstLoc, Val, SourceType, F->getLoweredType(opaque, TargetType), TargetType); break; } case SILInstructionKind::UnconditionalCheckedCastInst: { if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseASTType(TargetType)) return true; if (parseSILDebugLocation(InstLoc, B)) return true; auto opaque = Lowering::AbstractionPattern::getOpaque(); ResultVal = B.createUnconditionalCheckedCast( InstLoc, Val, F->getLoweredType(opaque, TargetType), TargetType); break; } case SILInstructionKind::CheckedCastBranchInst: { bool isExact = false; if (Opcode == SILInstructionKind::CheckedCastBranchInst && parseSILOptional(isExact, *this, "exact")) return true; if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseASTType(TargetType) || parseConditionalBranchDestinations()) return true; auto opaque = Lowering::AbstractionPattern::getOpaque(); ResultVal = B.createCheckedCastBranch( InstLoc, isExact, Val, F->getLoweredType(opaque, TargetType), TargetType, getBBForReference(SuccessBBName, SuccessBBLoc), getBBForReference(FailureBBName, FailureBBLoc)); break; } case SILInstructionKind::CheckedCastValueBranchInst: { if (parseASTType(SourceType) || parseVerbatim("in") || parseTypedValueRef(Val, B) || parseVerbatim("to") || parseASTType(TargetType) || parseConditionalBranchDestinations()) return true; auto opaque = Lowering::AbstractionPattern::getOpaque(); ResultVal = B.createCheckedCastValueBranch( InstLoc, Val, SourceType, F->getLoweredType(opaque, TargetType), TargetType, getBBForReference(SuccessBBName, SuccessBBLoc), getBBForReference(FailureBBName, FailureBBLoc)); break; } case SILInstructionKind::MarkUninitializedInst: { if (P.parseToken(tok::l_square, diag::expected_tok_in_sil_instr, "[")) return true; Identifier KindId; SourceLoc KindLoc = P.Tok.getLoc(); if (P.consumeIf(tok::kw_var)) KindId = P.Context.getIdentifier("var"); else if (P.parseIdentifier(KindId, KindLoc, diag::expected_tok_in_sil_instr, "kind")) return true; if (P.parseToken(tok::r_square, diag::expected_tok_in_sil_instr, "]")) return true; MarkUninitializedInst::Kind Kind; if (KindId.str() == "var") Kind = MarkUninitializedInst::Var; else if (KindId.str() == "rootself") Kind = MarkUninitializedInst::RootSelf; else if (KindId.str() == "crossmodulerootself") Kind = MarkUninitializedInst::CrossModuleRootSelf; else if (KindId.str() == "derivedself") Kind = MarkUninitializedInst::DerivedSelf; else if (KindId.str() == "derivedselfonly") Kind = MarkUninitializedInst::DerivedSelfOnly; else if (KindId.str() == "delegatingself") Kind = MarkUninitializedInst::DelegatingSelf; else if (KindId.str() == "delegatingselfallocated") Kind = MarkUninitializedInst::DelegatingSelfAllocated; else { P.diagnose(KindLoc, diag::expected_tok_in_sil_instr, "var, rootself, crossmodulerootself, derivedself, " "derivedselfonly, delegatingself, or delegatingselfallocated"); return true; } if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createMarkUninitialized(InstLoc, Val, Kind); break; } case SILInstructionKind::MarkFunctionEscapeInst: { SmallVector<SILValue, 4> OpList; do { if (parseTypedValueRef(Val, B)) return true; OpList.push_back(Val); } while (!peekSILDebugLocation(P) && P.consumeIf(tok::comma)); if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createMarkFunctionEscape(InstLoc, OpList); break; } case SILInstructionKind::AssignInst: case SILInstructionKind::StoreInst: { UnresolvedValueName From; SourceLoc ToLoc, AddrLoc; Identifier ToToken; SILValue AddrVal; StoreOwnershipQualifier StoreQualifier; AssignOwnershipQualifier AssignQualifier; bool IsStore = Opcode == SILInstructionKind::StoreInst; bool IsAssign = Opcode == SILInstructionKind::AssignInst; if (parseValueName(From) || parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr, "to")) return true; if (IsStore && parseStoreOwnershipQualifier(StoreQualifier, *this)) return true; if (IsAssign && parseAssignOwnershipQualifier(AssignQualifier, *this)) return true; if (parseTypedValueRef(AddrVal, AddrLoc, B) || parseSILDebugLocation(InstLoc, B)) return true; if (ToToken.str() != "to") { P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to"); return true; } if (!AddrVal->getType().isAddress()) { P.diagnose(AddrLoc, diag::sil_operand_not_address, "destination", OpcodeName); return true; } SILType ValType = AddrVal->getType().getObjectType(); if (IsStore) { ResultVal = B.createStore(InstLoc, getLocalValue(From, ValType, InstLoc, B), AddrVal, StoreQualifier); } else { assert(IsAssign); ResultVal = B.createAssign(InstLoc, getLocalValue(From, ValType, InstLoc, B), AddrVal, AssignQualifier); } break; } case SILInstructionKind::AssignByWrapperInst: { SILValue Src, DestAddr, InitFn, SetFn; SourceLoc DestLoc; AssignOwnershipQualifier AssignQualifier; if (parseTypedValueRef(Src, B) || parseVerbatim("to") || parseAssignOwnershipQualifier(AssignQualifier, *this) || parseTypedValueRef(DestAddr, DestLoc, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseVerbatim("init") || parseTypedValueRef(InitFn, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseVerbatim("set") || parseTypedValueRef(SetFn, B) || parseSILDebugLocation(InstLoc, B)) return true; if (!DestAddr->getType().isAddress()) { P.diagnose(DestLoc, diag::sil_operand_not_address, "destination", OpcodeName); return true; } ResultVal = B.createAssignByWrapper(InstLoc, Src, DestAddr, InitFn, SetFn, AssignQualifier); break; } case SILInstructionKind::BeginAccessInst: case SILInstructionKind::BeginUnpairedAccessInst: case SILInstructionKind::EndAccessInst: case SILInstructionKind::EndUnpairedAccessInst: { ParsedEnum<SILAccessKind> kind; ParsedEnum<SILAccessEnforcement> enforcement; ParsedEnum<bool> aborting; ParsedEnum<bool> noNestedConflict; ParsedEnum<bool> fromBuiltin; bool isBeginAccess = (Opcode == SILInstructionKind::BeginAccessInst || Opcode == SILInstructionKind::BeginUnpairedAccessInst); bool wantsEnforcement = (isBeginAccess || Opcode == SILInstructionKind::EndUnpairedAccessInst); while (P.consumeIf(tok::l_square)) { Identifier ident; SourceLoc identLoc; if (parseSILIdentifier(ident, identLoc, diag::expected_in_attribute_list)) { if (P.consumeIf(tok::r_square)) { continue; } else { return true; } } StringRef attr = ident.str(); auto setEnforcement = [&](SILAccessEnforcement value) { maybeSetEnum(wantsEnforcement, enforcement, value, attr, identLoc); }; auto setKind = [&](SILAccessKind value) { maybeSetEnum(isBeginAccess, kind, value, attr, identLoc); }; auto setAborting = [&](bool value) { maybeSetEnum(!isBeginAccess, aborting, value, attr, identLoc); }; auto setNoNestedConflict = [&](bool value) { maybeSetEnum(isBeginAccess, noNestedConflict, value, attr, identLoc); }; auto setFromBuiltin = [&](bool value) { maybeSetEnum(Opcode != SILInstructionKind::EndAccessInst, fromBuiltin, value, attr, identLoc); }; if (attr == "unknown") { setEnforcement(SILAccessEnforcement::Unknown); } else if (attr == "static") { setEnforcement(SILAccessEnforcement::Static); } else if (attr == "dynamic") { setEnforcement(SILAccessEnforcement::Dynamic); } else if (attr == "unsafe") { setEnforcement(SILAccessEnforcement::Unsafe); } else if (attr == "init") { setKind(SILAccessKind::Init); } else if (attr == "read") { setKind(SILAccessKind::Read); } else if (attr == "modify") { setKind(SILAccessKind::Modify); } else if (attr == "deinit") { setKind(SILAccessKind::Deinit); } else if (attr == "abort") { setAborting(true); } else if (attr == "no_nested_conflict") { setNoNestedConflict(true); } else if (attr == "builtin") { setFromBuiltin(true); } else { P.diagnose(identLoc, diag::unknown_attribute, attr); } if (!P.consumeIf(tok::r_square)) return true; } if (isBeginAccess && !kind.isSet()) { P.diagnose(OpcodeLoc, diag::sil_expected_access_kind, OpcodeName); kind.Value = SILAccessKind::Read; } if (wantsEnforcement && !enforcement.isSet()) { P.diagnose(OpcodeLoc, diag::sil_expected_access_enforcement, OpcodeName); enforcement.Value = SILAccessEnforcement::Unsafe; } if (!isBeginAccess && !aborting.isSet()) aborting.Value = false; if (isBeginAccess && !noNestedConflict.isSet()) noNestedConflict.Value = false; if (!fromBuiltin.isSet()) fromBuiltin.Value = false; SILValue addrVal; SourceLoc addrLoc; if (parseTypedValueRef(addrVal, addrLoc, B)) return true; SILValue bufferVal; SourceLoc bufferLoc; if (Opcode == SILInstructionKind::BeginUnpairedAccessInst && (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(bufferVal, bufferLoc, B))) return true; if (parseSILDebugLocation(InstLoc, B)) return true; if (!addrVal->getType().isAddress()) { P.diagnose(addrLoc, diag::sil_operand_not_address, "operand", OpcodeName); return true; } if (Opcode == SILInstructionKind::BeginAccessInst) { ResultVal = B.createBeginAccess(InstLoc, addrVal, *kind, *enforcement, *noNestedConflict, *fromBuiltin); } else if (Opcode == SILInstructionKind::EndAccessInst) { ResultVal = B.createEndAccess(InstLoc, addrVal, *aborting); } else if (Opcode == SILInstructionKind::BeginUnpairedAccessInst) { ResultVal = B.createBeginUnpairedAccess(InstLoc, addrVal, bufferVal, *kind, *enforcement, *noNestedConflict, *fromBuiltin); } else { ResultVal = B.createEndUnpairedAccess(InstLoc, addrVal, *enforcement, *aborting, *fromBuiltin); } break; } #define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \ case SILInstructionKind::Store##Name##Inst: #include "swift/AST/ReferenceStorage.def" case SILInstructionKind::StoreBorrowInst: { UnresolvedValueName from; bool isRefStorage = false; #define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \ isRefStorage |= Opcode == SILInstructionKind::Store##Name##Inst; #include "swift/AST/ReferenceStorage.def" SourceLoc toLoc, addrLoc; Identifier toToken; SILValue addrVal; bool isInit = false; if (parseValueName(from) || parseSILIdentifier(toToken, toLoc, diag::expected_tok_in_sil_instr, "to") || (isRefStorage && parseSILOptional(isInit, *this, "initialization")) || parseTypedValueRef(addrVal, addrLoc, B) || parseSILDebugLocation(InstLoc, B)) return true; if (toToken.str() != "to") { P.diagnose(toLoc, diag::expected_tok_in_sil_instr, "to"); return true; } if (!addrVal->getType().isAddress()) { P.diagnose(addrLoc, diag::sil_operand_not_address, "destination", OpcodeName); return true; } if (Opcode == SILInstructionKind::StoreBorrowInst) { SILType valueTy = addrVal->getType().getObjectType(); ResultVal = B.createStoreBorrow( InstLoc, getLocalValue(from, valueTy, InstLoc, B), addrVal); break; } #define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \ if (Opcode == SILInstructionKind::Store##Name##Inst) { \ auto refType = addrVal->getType().getAs<Name##StorageType>(); \ if (!refType) { \ P.diagnose(addrLoc, diag::sil_operand_not_ref_storage_address, \ "destination", OpcodeName, ReferenceOwnership::Name); \ return true; \ } \ auto valueTy = SILType::getPrimitiveObjectType(refType.getReferentType()); \ ResultVal = \ B.createStore##Name(InstLoc, getLocalValue(from, valueTy, InstLoc, B), \ addrVal, IsInitialization_t(isInit)); \ break; \ } #include "swift/AST/ReferenceStorage.def" break; } case SILInstructionKind::AllocStackInst: case SILInstructionKind::MetatypeInst: { bool hasDynamicLifetime = false; if (Opcode == SILInstructionKind::AllocStackInst && parseSILOptional(hasDynamicLifetime, *this, "dynamic_lifetime")) return true; SILType Ty; if (parseSILType(Ty)) return true; if (Opcode == SILInstructionKind::AllocStackInst) { SILDebugVariable VarInfo; if (parseSILDebugVar(VarInfo) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createAllocStack(InstLoc, Ty, VarInfo, hasDynamicLifetime); } else { assert(Opcode == SILInstructionKind::MetatypeInst); if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createMetatype(InstLoc, Ty); } break; } case SILInstructionKind::AllocRefInst: case SILInstructionKind::AllocRefDynamicInst: { bool IsObjC = false; bool OnStack = false; SmallVector<SILType, 2> ElementTypes; SmallVector<SILValue, 2> ElementCounts; while (P.consumeIf(tok::l_square)) { Identifier Id; parseSILIdentifier(Id, diag::expected_in_attribute_list); StringRef Optional = Id.str(); if (Optional == "objc") { IsObjC = true; } else if (Optional == "stack") { OnStack = true; } else if (Optional == "tail_elems") { SILType ElemTy; if (parseSILType(ElemTy) || !P.Tok.isAnyOperator() || P.Tok.getText() != "*") return true; P.consumeToken(); SILValue ElemCount; if (parseTypedValueRef(ElemCount, B)) return true; ElementTypes.push_back(ElemTy); ElementCounts.push_back(ElemCount); } else { return true; } P.parseToken(tok::r_square, diag::expected_in_attribute_list); } SILValue Metadata; if (Opcode == SILInstructionKind::AllocRefDynamicInst) { if (parseTypedValueRef(Metadata, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; } SILType ObjectType; if (parseSILType(ObjectType)) return true; if (parseSILDebugLocation(InstLoc, B)) return true; if (IsObjC && !ElementTypes.empty()) { P.diagnose(P.Tok, diag::sil_objc_with_tail_elements); return true; } if (Opcode == SILInstructionKind::AllocRefDynamicInst) { if (OnStack) return true; ResultVal = B.createAllocRefDynamic(InstLoc, Metadata, ObjectType, IsObjC, ElementTypes, ElementCounts); } else { ResultVal = B.createAllocRef(InstLoc, ObjectType, IsObjC, OnStack, ElementTypes, ElementCounts); } break; } case SILInstructionKind::DeallocStackInst: if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeallocStack(InstLoc, Val); break; case SILInstructionKind::DeallocRefInst: { bool OnStack = false; if (parseSILOptional(OnStack, *this, "stack")) return true; if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeallocRef(InstLoc, Val, OnStack); break; } case SILInstructionKind::DeallocPartialRefInst: { SILValue Metatype, Instance; if (parseTypedValueRef(Instance, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(Metatype, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeallocPartialRef(InstLoc, Instance, Metatype); break; } case SILInstructionKind::DeallocBoxInst: if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeallocBox(InstLoc, Val); break; case SILInstructionKind::ValueMetatypeInst: case SILInstructionKind::ExistentialMetatypeInst: { SILType Ty; if (parseSILType(Ty) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; switch (Opcode) { default: llvm_unreachable("Out of sync with parent switch"); case SILInstructionKind::ValueMetatypeInst: ResultVal = B.createValueMetatype(InstLoc, Ty, Val); break; case SILInstructionKind::ExistentialMetatypeInst: ResultVal = B.createExistentialMetatype(InstLoc, Ty, Val); break; case SILInstructionKind::DeallocBoxInst: ResultVal = B.createDeallocBox(InstLoc, Val); break; } break; } case SILInstructionKind::DeallocExistentialBoxInst: { CanType ConcreteTy; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(ConcreteTy) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeallocExistentialBox(InstLoc, ConcreteTy, Val); break; } case SILInstructionKind::TupleInst: { // Tuple instructions have two different syntaxes, one for simple tuple // types, one for complicated ones. if (P.Tok.isNot(tok::sil_dollar)) { // If there is no type, parse the simple form. if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "(")) return true; // TODO: Check for a type here. This is how tuples with "interesting" // types are described. // This form is used with tuples that have elements with no names or // default values. SmallVector<TupleTypeElt, 4> TypeElts; if (P.Tok.isNot(tok::r_paren)) { do { if (parseTypedValueRef(Val, B)) return true; OpList.push_back(Val); TypeElts.push_back(Val->getType().getASTType()); } while (P.consumeIf(tok::comma)); } HadError |= P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")"); auto Ty = TupleType::get(TypeElts, P.Context); auto Ty2 = SILType::getPrimitiveObjectType(Ty->getCanonicalType()); if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createTuple(InstLoc, Ty2, OpList); break; } // Otherwise, parse the fully general form. SILType Ty; if (parseSILType(Ty) || P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "(")) return true; TupleType *TT = Ty.getAs<TupleType>(); if (TT == nullptr) { P.diagnose(OpcodeLoc, diag::expected_tuple_type_in_tuple); return true; } SmallVector<TupleTypeElt, 4> TypeElts; if (P.Tok.isNot(tok::r_paren)) { do { if (TypeElts.size() > TT->getNumElements()) { P.diagnose(P.Tok, diag::sil_tuple_inst_wrong_value_count, TT->getNumElements()); return true; } Type EltTy = TT->getElement(TypeElts.size()).getType(); if (parseValueRef( Val, SILType::getPrimitiveObjectType(EltTy->getCanonicalType()), RegularLocation(P.Tok.getLoc()), B)) return true; OpList.push_back(Val); TypeElts.push_back(Val->getType().getASTType()); } while (P.consumeIf(tok::comma)); } HadError |= P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr,")"); if (TypeElts.size() != TT->getNumElements()) { P.diagnose(OpcodeLoc, diag::sil_tuple_inst_wrong_value_count, TT->getNumElements()); return true; } if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createTuple(InstLoc, Ty, OpList); break; } case SILInstructionKind::EnumInst: { SILType Ty; SILDeclRef Elt; SILValue Operand; if (parseSILType(Ty) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILDeclRef(Elt)) return true; if (P.Tok.is(tok::comma) && !peekSILDebugLocation(P)) { P.consumeToken(tok::comma); if (parseTypedValueRef(Operand, B)) return true; } if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createEnum(InstLoc, Operand, cast<EnumElementDecl>(Elt.getDecl()), Ty); break; } case SILInstructionKind::InitEnumDataAddrInst: case SILInstructionKind::UncheckedEnumDataInst: case SILInstructionKind::UncheckedTakeEnumDataAddrInst: { SILValue Operand; SILDeclRef EltRef; if (parseTypedValueRef(Operand, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILDeclRef(EltRef) || parseSILDebugLocation(InstLoc, B)) return true; EnumElementDecl *Elt = cast<EnumElementDecl>(EltRef.getDecl()); auto ResultTy = Operand->getType().getEnumElementType( Elt, SILMod, B.getTypeExpansionContext()); switch (Opcode) { case swift::SILInstructionKind::InitEnumDataAddrInst: ResultVal = B.createInitEnumDataAddr(InstLoc, Operand, Elt, ResultTy); break; case swift::SILInstructionKind::UncheckedTakeEnumDataAddrInst: ResultVal = B.createUncheckedTakeEnumDataAddr(InstLoc, Operand, Elt, ResultTy); break; case swift::SILInstructionKind::UncheckedEnumDataInst: ResultVal = B.createUncheckedEnumData(InstLoc, Operand, Elt, ResultTy); break; default: llvm_unreachable("switch out of sync"); } break; } case SILInstructionKind::InjectEnumAddrInst: { SILValue Operand; SILDeclRef EltRef; if (parseTypedValueRef(Operand, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILDeclRef(EltRef) || parseSILDebugLocation(InstLoc, B)) return true; EnumElementDecl *Elt = cast<EnumElementDecl>(EltRef.getDecl()); ResultVal = B.createInjectEnumAddr(InstLoc, Operand, Elt); break; } case SILInstructionKind::TupleElementAddrInst: case SILInstructionKind::TupleExtractInst: { SourceLoc NameLoc; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; unsigned Field = 0; TupleType *TT = Val->getType().getAs<TupleType>(); if (P.Tok.isNot(tok::integer_literal) || parseIntegerLiteral(P.Tok.getText(), 10, Field) || Field >= TT->getNumElements()) { P.diagnose(P.Tok, diag::sil_tuple_inst_wrong_field); return true; } P.consumeToken(tok::integer_literal); if (parseSILDebugLocation(InstLoc, B)) return true; auto ResultTy = TT->getElement(Field).getType()->getCanonicalType(); if (Opcode == SILInstructionKind::TupleElementAddrInst) ResultVal = B.createTupleElementAddr( InstLoc, Val, Field, SILType::getPrimitiveAddressType(ResultTy)); else ResultVal = B.createTupleExtract( InstLoc, Val, Field, SILType::getPrimitiveObjectType(ResultTy)); break; } case SILInstructionKind::ReturnInst: { if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createReturn(InstLoc, Val); break; } case SILInstructionKind::ThrowInst: { if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createThrow(InstLoc, Val); break; } case SILInstructionKind::UnwindInst: { if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createUnwind(InstLoc); break; } case SILInstructionKind::YieldInst: { SmallVector<SILValue, 6> values; // Parse a parenthesized (unless length-1), comma-separated list // of yielded values. if (P.consumeIf(tok::l_paren)) { if (!P.Tok.is(tok::r_paren)) { do { if (parseTypedValueRef(Val, B)) return true; values.push_back(Val); } while (P.consumeIf(tok::comma)); } if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")")) return true; } else { if (parseTypedValueRef(Val, B)) return true; values.push_back(Val); } Identifier resumeName, unwindName; SourceLoc resumeLoc, unwindLoc; if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseVerbatim("resume") || parseSILIdentifier(resumeName, resumeLoc, diag::expected_sil_block_name) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseVerbatim("unwind") || parseSILIdentifier(unwindName, unwindLoc, diag::expected_sil_block_name) || parseSILDebugLocation(InstLoc, B)) return true; auto resumeBB = getBBForReference(resumeName, resumeLoc); auto unwindBB = getBBForReference(unwindName, unwindLoc); ResultVal = B.createYield(InstLoc, values, resumeBB, unwindBB); break; } case SILInstructionKind::BranchInst: { Identifier BBName; SourceLoc NameLoc; if (parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name)) return true; SmallVector<SILValue, 6> Args; if (parseSILBBArgsAtBranch(Args, B)) return true; if (parseSILDebugLocation(InstLoc, B)) return true; // Note, the basic block here could be a reference to an undefined // basic block, which will be parsed later on. ResultVal = B.createBranch(InstLoc, getBBForReference(BBName, NameLoc), Args); break; } case SILInstructionKind::CondBranchInst: { UnresolvedValueName Cond; Identifier BBName, BBName2; SourceLoc NameLoc, NameLoc2; SmallVector<SILValue, 6> Args, Args2; if (parseValueName(Cond) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name) || parseSILBBArgsAtBranch(Args, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(BBName2, NameLoc2, diag::expected_sil_block_name) || parseSILBBArgsAtBranch(Args2, B) || parseSILDebugLocation(InstLoc, B)) return true; auto I1Ty = SILType::getBuiltinIntegerType(1, SILMod.getASTContext()); SILValue CondVal = getLocalValue(Cond, I1Ty, InstLoc, B); ResultVal = B.createCondBranch( InstLoc, CondVal, getBBForReference(BBName, NameLoc), Args, getBBForReference(BBName2, NameLoc2), Args2); break; } case SILInstructionKind::UnreachableInst: if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createUnreachable(InstLoc); break; case SILInstructionKind::ClassMethodInst: case SILInstructionKind::SuperMethodInst: case SILInstructionKind::ObjCMethodInst: case SILInstructionKind::ObjCSuperMethodInst: { SILDeclRef Member; SILType MethodTy; SourceLoc TyLoc; SmallVector<ValueDecl *, 4> values; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; if (parseSILDeclRef(Member, true)) return true; if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILType(MethodTy, TyLoc) || parseSILDebugLocation(InstLoc, B)) return true; switch (Opcode) { default: llvm_unreachable("Out of sync with parent switch"); case SILInstructionKind::ClassMethodInst: ResultVal = B.createClassMethod(InstLoc, Val, Member, MethodTy); break; case SILInstructionKind::SuperMethodInst: ResultVal = B.createSuperMethod(InstLoc, Val, Member, MethodTy); break; case SILInstructionKind::ObjCMethodInst: ResultVal = B.createObjCMethod(InstLoc, Val, Member, MethodTy); break; case SILInstructionKind::ObjCSuperMethodInst: ResultVal = B.createObjCSuperMethod(InstLoc, Val, Member, MethodTy); break; } break; } case SILInstructionKind::WitnessMethodInst: { CanType LookupTy; SILDeclRef Member; SILType MethodTy; SourceLoc TyLoc; if (P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(LookupTy) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")) return true; if (parseSILDeclRef(Member, true)) return true; // Optional operand. SILValue Operand; if (P.Tok.is(tok::comma)) { P.consumeToken(tok::comma); if (parseTypedValueRef(Operand, B)) return true; } if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(MethodTy, TyLoc) || parseSILDebugLocation(InstLoc, B)) return true; // If LookupTy is a non-archetype, look up its conformance. ProtocolDecl *proto = dyn_cast<ProtocolDecl>(Member.getDecl()->getDeclContext()); if (!proto) { P.diagnose(TyLoc, diag::sil_witness_method_not_protocol); return true; } auto conformance = P.SF.getParentModule()->lookupConformance(LookupTy, proto); if (conformance.isInvalid()) { P.diagnose(TyLoc, diag::sil_witness_method_type_does_not_conform); return true; } ResultVal = B.createWitnessMethod(InstLoc, LookupTy, conformance, Member, MethodTy); break; } case SILInstructionKind::CopyAddrInst: { bool IsTake = false, IsInit = false; UnresolvedValueName SrcLName; SILValue DestLVal; SourceLoc ToLoc, DestLoc; Identifier ToToken; if (parseSILOptional(IsTake, *this, "take") || parseValueName(SrcLName) || parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr, "to") || parseSILOptional(IsInit, *this, "initialization") || parseTypedValueRef(DestLVal, DestLoc, B) || parseSILDebugLocation(InstLoc, B)) return true; if (ToToken.str() != "to") { P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to"); return true; } if (!DestLVal->getType().isAddress()) { P.diagnose(DestLoc, diag::sil_invalid_instr_operands); return true; } SILValue SrcLVal = getLocalValue(SrcLName, DestLVal->getType(), InstLoc, B); ResultVal = B.createCopyAddr(InstLoc, SrcLVal, DestLVal, IsTake_t(IsTake), IsInitialization_t(IsInit)); break; } case SILInstructionKind::BindMemoryInst: { SILValue IndexVal; Identifier ToToken; SourceLoc ToLoc; SILType EltTy; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(IndexVal, B) || parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr, "to") || parseSILType(EltTy) || parseSILDebugLocation(InstLoc, B)) return true; if (ToToken.str() != "to") { P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to"); return true; } ResultVal = B.createBindMemory(InstLoc, Val, IndexVal, EltTy); break; } case SILInstructionKind::ObjectInst: case SILInstructionKind::StructInst: { SILType Ty; if (parseSILType(Ty) || P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "(")) return true; // Parse a list of SILValue. bool OpsAreTailElems = false; unsigned NumBaseElems = 0; if (P.Tok.isNot(tok::r_paren)) { do { if (Opcode == SILInstructionKind::ObjectInst) { if (parseSILOptional(OpsAreTailElems, *this, "tail_elems")) return true; } if (parseTypedValueRef(Val, B)) return true; OpList.push_back(Val); if (!OpsAreTailElems) NumBaseElems = OpList.size(); } while (P.consumeIf(tok::comma)); } if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")") || parseSILDebugLocation(InstLoc, B)) return true; if (Opcode == SILInstructionKind::StructInst) { ResultVal = B.createStruct(InstLoc, Ty, OpList); } else { ResultVal = B.createObject(InstLoc, Ty, OpList, NumBaseElems); } break; } case SILInstructionKind::StructElementAddrInst: case SILInstructionKind::StructExtractInst: { ValueDecl *FieldV; SourceLoc NameLoc = P.Tok.getLoc(); if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILDottedPath(FieldV) || parseSILDebugLocation(InstLoc, B)) return true; if (!FieldV || !isa<VarDecl>(FieldV)) { P.diagnose(NameLoc, diag::sil_struct_inst_wrong_field); return true; } VarDecl *Field = cast<VarDecl>(FieldV); // FIXME: substitution means this type should be explicit to improve // performance. auto ResultTy = Val->getType().getFieldType(Field, SILMod, B.getTypeExpansionContext()); if (Opcode == SILInstructionKind::StructElementAddrInst) ResultVal = B.createStructElementAddr(InstLoc, Val, Field, ResultTy.getAddressType()); else ResultVal = B.createStructExtract(InstLoc, Val, Field, ResultTy.getObjectType()); break; } case SILInstructionKind::RefElementAddrInst: { ValueDecl *FieldV; SourceLoc NameLoc; bool IsImmutable = false; if (parseSILOptional(IsImmutable, *this, "immutable") || parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILDottedPath(FieldV) || parseSILDebugLocation(InstLoc, B)) return true; if (!FieldV || !isa<VarDecl>(FieldV)) { P.diagnose(NameLoc, diag::sil_ref_inst_wrong_field); return true; } VarDecl *Field = cast<VarDecl>(FieldV); auto ResultTy = Val->getType().getFieldType(Field, SILMod, B.getTypeExpansionContext()); ResultVal = B.createRefElementAddr(InstLoc, Val, Field, ResultTy, IsImmutable); break; } case SILInstructionKind::RefTailAddrInst: { SourceLoc NameLoc; SILType ResultObjTy; bool IsImmutable = false; if (parseSILOptional(IsImmutable, *this, "immutable") || parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILType(ResultObjTy) || parseSILDebugLocation(InstLoc, B)) return true; SILType ResultTy = ResultObjTy.getAddressType(); ResultVal = B.createRefTailAddr(InstLoc, Val, ResultTy, IsImmutable); break; } case SILInstructionKind::IndexAddrInst: { SILValue IndexVal; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(IndexVal, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createIndexAddr(InstLoc, Val, IndexVal); break; } case SILInstructionKind::TailAddrInst: { SILValue IndexVal; SILType ResultObjTy; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(IndexVal, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILType(ResultObjTy) || parseSILDebugLocation(InstLoc, B)) return true; SILType ResultTy = ResultObjTy.getAddressType(); ResultVal = B.createTailAddr(InstLoc, Val, IndexVal, ResultTy); break; } case SILInstructionKind::IndexRawPointerInst: { SILValue IndexVal; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseTypedValueRef(IndexVal, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createIndexRawPointer(InstLoc, Val, IndexVal); break; } case SILInstructionKind::ObjCProtocolInst: { Identifier ProtocolName; SILType Ty; if (P.parseToken(tok::pound, diag::expected_sil_constant) || parseSILIdentifier(ProtocolName, diag::expected_sil_constant) || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; // Find the decl for the protocol name. ValueDecl *VD; SmallVector<ValueDecl *, 4> CurModuleResults; // Perform a module level lookup on the first component of the // fully-qualified name. P.SF.getParentModule()->lookupValue( ProtocolName, NLKind::UnqualifiedLookup, CurModuleResults); assert(CurModuleResults.size() == 1); VD = CurModuleResults[0]; ResultVal = B.createObjCProtocol(InstLoc, cast<ProtocolDecl>(VD), Ty); break; } case SILInstructionKind::AllocGlobalInst: { Identifier GlobalName; SourceLoc IdLoc; if (P.parseToken(tok::at_sign, diag::expected_sil_value_name) || parseSILIdentifier(GlobalName, IdLoc, diag::expected_sil_value_name) || parseSILDebugLocation(InstLoc, B)) return true; // Go through list of global variables in the SILModule. SILGlobalVariable *global = SILMod.lookUpGlobalVariable(GlobalName.str()); if (!global) { P.diagnose(IdLoc, diag::sil_global_variable_not_found, GlobalName); return true; } ResultVal = B.createAllocGlobal(InstLoc, global); break; } case SILInstructionKind::GlobalAddrInst: case SILInstructionKind::GlobalValueInst: { Identifier GlobalName; SourceLoc IdLoc; SILType Ty; if (P.parseToken(tok::at_sign, diag::expected_sil_value_name) || parseSILIdentifier(GlobalName, IdLoc, diag::expected_sil_value_name) || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(Ty) || parseSILDebugLocation(InstLoc, B)) return true; // Go through list of global variables in the SILModule. SILGlobalVariable *global = SILMod.lookUpGlobalVariable(GlobalName.str()); if (!global) { P.diagnose(IdLoc, diag::sil_global_variable_not_found, GlobalName); return true; } SILType expectedType = (Opcode == SILInstructionKind::GlobalAddrInst ? global->getLoweredType().getAddressType() : global->getLoweredType()); if (expectedType != Ty) { P.diagnose(IdLoc, diag::sil_value_use_type_mismatch, GlobalName.str(), global->getLoweredType().getASTType(), Ty.getASTType()); return true; } if (Opcode == SILInstructionKind::GlobalAddrInst) { ResultVal = B.createGlobalAddr(InstLoc, global); } else { ResultVal = B.createGlobalValue(InstLoc, global); } break; } case SILInstructionKind::BaseAddrForOffsetInst: { SILType Ty; if (parseSILType(Ty)) return true; if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createBaseAddrForOffset(InstLoc, Ty); break; } case SILInstructionKind::SelectEnumInst: case SILInstructionKind::SelectEnumAddrInst: { if (parseTypedValueRef(Val, B)) return true; SmallVector<std::pair<EnumElementDecl *, UnresolvedValueName>, 4> CaseValueNames; Optional<UnresolvedValueName> DefaultValueName; while (P.consumeIf(tok::comma)) { Identifier BBName; SourceLoc BBLoc; // Parse 'default' sil-value. UnresolvedValueName tmp; if (P.consumeIf(tok::kw_default)) { if (parseValueName(tmp)) return true; DefaultValueName = tmp; break; } // Parse 'case' sil-decl-ref ':' sil-value. if (P.consumeIf(tok::kw_case)) { SILDeclRef ElemRef; if (parseSILDeclRef(ElemRef)) return true; assert(ElemRef.hasDecl() && isa<EnumElementDecl>(ElemRef.getDecl())); P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":"); parseValueName(tmp); CaseValueNames.push_back( std::make_pair(cast<EnumElementDecl>(ElemRef.getDecl()), tmp)); continue; } P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "case or default"); return true; } // Parse the type of the result operands. SILType ResultType; if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(ResultType) || parseSILDebugLocation(InstLoc, B)) return true; // Resolve the results. SmallVector<std::pair<EnumElementDecl *, SILValue>, 4> CaseValues; SILValue DefaultValue; if (DefaultValueName) DefaultValue = getLocalValue(*DefaultValueName, ResultType, InstLoc, B); for (auto &caseName : CaseValueNames) CaseValues.push_back(std::make_pair( caseName.first, getLocalValue(caseName.second, ResultType, InstLoc, B))); if (Opcode == SILInstructionKind::SelectEnumInst) ResultVal = B.createSelectEnum(InstLoc, Val, ResultType, DefaultValue, CaseValues); else ResultVal = B.createSelectEnumAddr(InstLoc, Val, ResultType, DefaultValue, CaseValues); break; } case SILInstructionKind::SwitchEnumInst: case SILInstructionKind::SwitchEnumAddrInst: { if (parseTypedValueRef(Val, B)) return true; SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 4> CaseBBs; SILBasicBlock *DefaultBB = nullptr; while (!peekSILDebugLocation(P) && P.consumeIf(tok::comma)) { Identifier BBName; SourceLoc BBLoc; // Parse 'default' sil-identifier. if (P.consumeIf(tok::kw_default)) { parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name); DefaultBB = getBBForReference(BBName, BBLoc); break; } // Parse 'case' sil-decl-ref ':' sil-identifier. if (P.consumeIf(tok::kw_case)) { SILDeclRef ElemRef; if (parseSILDeclRef(ElemRef)) return true; assert(ElemRef.hasDecl() && isa<EnumElementDecl>(ElemRef.getDecl())); P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":"); parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name); CaseBBs.push_back({cast<EnumElementDecl>(ElemRef.getDecl()), getBBForReference(BBName, BBLoc)}); continue; } P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "case or default"); return true; } if (parseSILDebugLocation(InstLoc, B)) return true; if (Opcode == SILInstructionKind::SwitchEnumInst) ResultVal = B.createSwitchEnum(InstLoc, Val, DefaultBB, CaseBBs); else ResultVal = B.createSwitchEnumAddr(InstLoc, Val, DefaultBB, CaseBBs); break; } case SILInstructionKind::SwitchValueInst: { if (parseTypedValueRef(Val, B)) return true; SmallVector<std::pair<SILValue, SILBasicBlock *>, 4> CaseBBs; SILBasicBlock *DefaultBB = nullptr; while (!peekSILDebugLocation(P) && P.consumeIf(tok::comma)) { Identifier BBName; SourceLoc BBLoc; SILValue CaseVal; // Parse 'default' sil-identifier. if (P.consumeIf(tok::kw_default)) { parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name); DefaultBB = getBBForReference(BBName, BBLoc); break; } // Parse 'case' value-ref ':' sil-identifier. if (P.consumeIf(tok::kw_case)) { if (parseValueRef(CaseVal, Val->getType(), RegularLocation(P.Tok.getLoc()), B)) { // TODO: Issue a proper error message here P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "reference to a value"); return true; } auto intTy = Val->getType().getAs<BuiltinIntegerType>(); auto functionTy = Val->getType().getAs<SILFunctionType>(); if (!intTy && !functionTy) { P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type); return true; } if (intTy) { // If it is a switch on an integer type, check that all case values // are integer literals or undef. if (!isa<SILUndef>(CaseVal)) { auto *IL = dyn_cast<IntegerLiteralInst>(CaseVal); if (!IL) { P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type); return true; } APInt CaseValue = IL->getValue(); if (CaseValue.getBitWidth() != intTy->getGreatestWidth()) CaseVal = B.createIntegerLiteral( IL->getLoc(), Val->getType(), CaseValue.zextOrTrunc(intTy->getGreatestWidth())); } } if (functionTy) { // If it is a switch on a function type, check that all case values // are function references or undef. if (!isa<SILUndef>(CaseVal)) { auto *FR = dyn_cast<FunctionRefInst>(CaseVal); if (!FR) { if (auto *CF = dyn_cast<ConvertFunctionInst>(CaseVal)) { FR = dyn_cast<FunctionRefInst>(CF->getOperand()); } } if (!FR) { P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type); return true; } } } P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":"); parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name); CaseBBs.push_back({CaseVal, getBBForReference(BBName, BBLoc)}); continue; } P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "case or default"); return true; } if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createSwitchValue(InstLoc, Val, DefaultBB, CaseBBs); break; } case SILInstructionKind::SelectValueInst: { if (parseTypedValueRef(Val, B)) return true; SmallVector<std::pair<UnresolvedValueName, UnresolvedValueName>, 4> CaseValueAndResultNames; Optional<UnresolvedValueName> DefaultResultName; while (P.consumeIf(tok::comma)) { Identifier BBName; SourceLoc BBLoc; // Parse 'default' sil-value. UnresolvedValueName tmp; if (P.consumeIf(tok::kw_default)) { if (parseValueName(tmp)) return true; DefaultResultName = tmp; break; } // Parse 'case' sil-decl-ref ':' sil-value. if (P.consumeIf(tok::kw_case)) { UnresolvedValueName casevalue; parseValueName(casevalue); P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":"); parseValueName(tmp); CaseValueAndResultNames.push_back(std::make_pair(casevalue, tmp)); continue; } P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "case or default"); return true; } if (!DefaultResultName) { P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "default"); return true; } // Parse the type of the result operands. SILType ResultType; if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(ResultType) || parseSILDebugLocation(InstLoc, B)) return true; // Resolve the results. SmallVector<std::pair<SILValue, SILValue>, 4> CaseValues; SILValue DefaultValue; if (DefaultResultName) DefaultValue = getLocalValue(*DefaultResultName, ResultType, InstLoc, B); SILType ValType = Val->getType(); for (auto &caseName : CaseValueAndResultNames) CaseValues.push_back(std::make_pair( getLocalValue(caseName.first, ValType, InstLoc, B), getLocalValue(caseName.second, ResultType, InstLoc, B))); ResultVal = B.createSelectValue(InstLoc, Val, ResultType, DefaultValue, CaseValues); break; } case SILInstructionKind::DeinitExistentialAddrInst: { if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeinitExistentialAddr(InstLoc, Val); break; } case SILInstructionKind::DeinitExistentialValueInst: { if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDeinitExistentialValue(InstLoc, Val); break; } case SILInstructionKind::InitExistentialAddrInst: { CanType Ty; SourceLoc TyLoc; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(Ty, TyLoc) || parseSILDebugLocation(InstLoc, B)) return true; // Lower the type at the abstraction level of the existential. auto archetype = OpenedArchetypeType::get(Val->getType().getASTType()) ->getCanonicalType(); auto &F = B.getFunction(); SILType LoweredTy = F.getLoweredType(Lowering::AbstractionPattern(archetype), Ty) .getAddressType(); // Collect conformances for the type. ArrayRef<ProtocolConformanceRef> conformances = collectExistentialConformances(P, Ty, TyLoc, Val->getType().getASTType()); ResultVal = B.createInitExistentialAddr(InstLoc, Val, Ty, LoweredTy, conformances); break; } case SILInstructionKind::InitExistentialValueInst: { CanType FormalConcreteTy; SILType ExistentialTy; SourceLoc TyLoc; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(FormalConcreteTy, TyLoc) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILType(ExistentialTy) || parseSILDebugLocation(InstLoc, B)) return true; ArrayRef<ProtocolConformanceRef> conformances = collectExistentialConformances(P, FormalConcreteTy, TyLoc, ExistentialTy.getASTType()); ResultVal = B.createInitExistentialValue( InstLoc, ExistentialTy, FormalConcreteTy, Val, conformances); break; } case SILInstructionKind::AllocExistentialBoxInst: { SILType ExistentialTy; CanType ConcreteFormalTy; SourceLoc TyLoc; if (parseSILType(ExistentialTy) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(ConcreteFormalTy, TyLoc) || parseSILDebugLocation(InstLoc, B)) return true; // Collect conformances for the type. ArrayRef<ProtocolConformanceRef> conformances = collectExistentialConformances(P, ConcreteFormalTy, TyLoc, ExistentialTy.getASTType()); ResultVal = B.createAllocExistentialBox(InstLoc, ExistentialTy, ConcreteFormalTy, conformances); break; } case SILInstructionKind::InitExistentialRefInst: { CanType FormalConcreteTy; SILType ExistentialTy; SourceLoc TyLoc; if (parseTypedValueRef(Val, B) || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") || parseASTType(FormalConcreteTy, TyLoc) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILType(ExistentialTy) || parseSILDebugLocation(InstLoc, B)) return true; ArrayRef<ProtocolConformanceRef> conformances = collectExistentialConformances(P, FormalConcreteTy, TyLoc, ExistentialTy.getASTType()); // FIXME: Conformances in InitExistentialRefInst is currently not included // in SIL.rst. ResultVal = B.createInitExistentialRef( InstLoc, ExistentialTy, FormalConcreteTy, Val, conformances); break; } case SILInstructionKind::InitExistentialMetatypeInst: { SourceLoc TyLoc; SILType ExistentialTy; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILType(ExistentialTy, TyLoc) || parseSILDebugLocation(InstLoc, B)) return true; auto baseExType = ExistentialTy.getASTType(); auto formalConcreteType = Val->getType().getASTType(); while (auto instExType = dyn_cast<ExistentialMetatypeType>(baseExType)) { baseExType = instExType.getInstanceType(); formalConcreteType = cast<MetatypeType>(formalConcreteType).getInstanceType(); } ArrayRef<ProtocolConformanceRef> conformances = collectExistentialConformances(P, formalConcreteType, TyLoc, baseExType); ResultVal = B.createInitExistentialMetatype(InstLoc, Val, ExistentialTy, conformances); break; } case SILInstructionKind::DynamicMethodBranchInst: { SILDeclRef Member; Identifier BBName, BBName2; SourceLoc NameLoc, NameLoc2; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILDeclRef(Member) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(BBName2, NameLoc2, diag::expected_sil_block_name) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDynamicMethodBranch( InstLoc, Val, Member, getBBForReference(BBName, NameLoc), getBBForReference(BBName2, NameLoc2)); break; } case SILInstructionKind::ProjectBlockStorageInst: { if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createProjectBlockStorage(InstLoc, Val); break; } case SILInstructionKind::InitBlockStorageHeaderInst: { Identifier invoke, type; SourceLoc invokeLoc, typeLoc; UnresolvedValueName invokeName; SILType invokeTy; GenericEnvironment *invokeGenericEnv; SILType blockType; SmallVector<ParsedSubstitution, 4> parsedSubs; if (parseTypedValueRef(Val, B) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(invoke, invokeLoc, diag::expected_tok_in_sil_instr, "invoke") || parseValueName(invokeName) || parseSubstitutions(parsedSubs) || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(invokeTy, invokeGenericEnv) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseSILIdentifier(type, typeLoc, diag::expected_tok_in_sil_instr, "type") || parseSILType(blockType) || parseSILDebugLocation(InstLoc, B)) return true; if (invoke.str() != "invoke") { P.diagnose(invokeLoc, diag::expected_tok_in_sil_instr, "invoke"); return true; } if (type.str() != "type") { P.diagnose(invokeLoc, diag::expected_tok_in_sil_instr, "type"); return true; } auto invokeVal = getLocalValue(invokeName, invokeTy, InstLoc, B); SubstitutionMap subMap; if (!parsedSubs.empty()) { if (!invokeGenericEnv) { P.diagnose(typeLoc, diag::sil_substitutions_on_non_polymorphic_type); return true; } subMap = getApplySubstitutionsFromParsed(*this, invokeGenericEnv, parsedSubs); if (!subMap) return true; } ResultVal = B.createInitBlockStorageHeader(InstLoc, Val, invokeVal, blockType, subMap); break; } case SILInstructionKind::DifferentiableFunctionInst: { // e.g. differentiable_function [parameters 0 1 2] [results 0] %0 : $T // // e.g. differentiable_function [parameters 0 1 2] [results 0] %0 : $T // with_derivative {%1 : $T, %2 : $T} // ^~ jvp ^~ vjp // Parse `[parameters <integer_literal>...]`. SmallVector<unsigned, 8> rawParameterIndices; if (parseIndexList(P, "parameters", rawParameterIndices, diag::sil_autodiff_expected_parameter_index)) return true; SmallVector<unsigned, 2> rawResultIndices; if (parseIndexList(P, "results", rawResultIndices, diag::sil_autodiff_expected_result_index)) return true; // Parse the original function value. SILValue original; SourceLoc originalOperandLoc; if (parseTypedValueRef(original, originalOperandLoc, B)) return true; auto fnType = original->getType().getAs<SILFunctionType>(); if (!fnType) { P.diagnose(originalOperandLoc, diag::sil_inst_autodiff_expected_function_type_operand); return true; } Optional<std::pair<SILValue, SILValue>> derivativeFunctions = None; // Parse an optional operand list // `with_derivative { <operand> , <operand> }`. if (P.Tok.is(tok::identifier) && P.Tok.getText() == "with_derivative") { P.consumeToken(tok::identifier); // Parse derivative function values as an operand list. // FIXME(rxwei): Change this to *not* require a type signature once // we can infer derivative function types. derivativeFunctions = std::make_pair(SILValue(), SILValue()); if (P.parseToken( tok::l_brace, diag::sil_inst_autodiff_operand_list_expected_lbrace) || parseTypedValueRef(derivativeFunctions->first, B) || P.parseToken(tok::comma, diag::sil_inst_autodiff_operand_list_expected_comma) || parseTypedValueRef(derivativeFunctions->second, B) || P.parseToken(tok::r_brace, diag::sil_inst_autodiff_operand_list_expected_rbrace)) return true; } if (parseSILDebugLocation(InstLoc, B)) return true; auto *parameterIndices = IndexSubset::get( P.Context, fnType->getNumParameters(), rawParameterIndices); auto *resultIndices = IndexSubset::get( P.Context, fnType->getNumResults() + fnType->getNumIndirectMutatingParameters(), rawResultIndices); ResultVal = B.createDifferentiableFunction(InstLoc, parameterIndices, resultIndices, original, derivativeFunctions); break; } case SILInstructionKind::LinearFunctionInst: { // e.g. linear_function [parameters 0 1 2] %0 : $T // e.g. linear_function [parameters 0 1 2] %0 : $T with_transpose %1 : $T // Parse `[parameters <integer_literal>...]`. SmallVector<unsigned, 8> rawParameterIndices; if (parseIndexList(P, "parameters", rawParameterIndices, diag::sil_autodiff_expected_parameter_index)) return true; // Parse the original function value. SILValue original; SourceLoc originalOperandLoc; if (parseTypedValueRef(original, originalOperandLoc, B)) return true; auto fnType = original->getType().getAs<SILFunctionType>(); if (!fnType) { P.diagnose(originalOperandLoc, diag::sil_inst_autodiff_expected_function_type_operand); return true; } // Parse an optional transpose function. Optional<SILValue> transpose = None; if (P.Tok.is(tok::identifier) && P.Tok.getText() == "with_transpose") { P.consumeToken(tok::identifier); transpose = SILValue(); if (parseTypedValueRef(*transpose, B)) return true; } if (parseSILDebugLocation(InstLoc, B)) return true; auto *parameterIndicesSubset = IndexSubset::get( P.Context, fnType->getNumParameters(), rawParameterIndices); ResultVal = B.createLinearFunction( InstLoc, parameterIndicesSubset, original, transpose); break; } case SILInstructionKind::DifferentiableFunctionExtractInst: { // Parse the rest of the instruction: an extractee, a differentiable // function operand, an optional explicit extractee type, and a debug // location. NormalDifferentiableFunctionTypeComponent extractee; StringRef extracteeNames[3] = {"original", "jvp", "vjp"}; SILValue functionOperand; SourceLoc lastLoc; if (P.parseToken( tok::l_square, diag::sil_inst_autodiff_expected_differentiable_extractee_kind) || parseSILIdentifierSwitch( extractee, extracteeNames, diag::sil_inst_autodiff_expected_differentiable_extractee_kind) || P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare, "extractee kind")) return true; if (parseTypedValueRef(functionOperand, B)) return true; // Parse an optional explicit extractee type. Optional<SILType> extracteeType = None; if (P.consumeIf(tok::kw_as)) { extracteeType = SILType(); if (parseSILType(*extracteeType)) return true; } if (parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createDifferentiableFunctionExtract( InstLoc, extractee, functionOperand, extracteeType); break; } case SILInstructionKind::LinearFunctionExtractInst: { // Parse the rest of the instruction: an extractee, a linear function // operand, and a debug location. LinearDifferentiableFunctionTypeComponent extractee; StringRef extracteeNames[2] = {"original", "transpose"}; SILValue functionOperand; SourceLoc lastLoc; if (P.parseToken(tok::l_square, diag::sil_inst_autodiff_expected_linear_extractee_kind) || parseSILIdentifierSwitch(extractee, extracteeNames, diag::sil_inst_autodiff_expected_linear_extractee_kind) || P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare, "extractee kind")) return true; if (parseTypedValueRef(functionOperand, B) || parseSILDebugLocation(InstLoc, B)) return true; ResultVal = B.createLinearFunctionExtract( InstLoc, extractee, functionOperand); break; } case SILInstructionKind::DifferentiabilityWitnessFunctionInst: { // e.g. differentiability_witness_function // [jvp] [parameters 0 1] [results 0] <T where T: Differentiable> // @foo : <T> $(T) -> T DifferentiabilityWitnessFunctionKind witnessKind; StringRef witnessKindNames[3] = {"jvp", "vjp", "transpose"}; if (P.parseToken( tok::l_square, diag:: sil_inst_autodiff_expected_differentiability_witness_kind) || parseSILIdentifierSwitch( witnessKind, witnessKindNames, diag:: sil_inst_autodiff_expected_differentiability_witness_kind) || P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare, "differentiability witness function kind")) return true; SourceLoc keyStartLoc = P.Tok.getLoc(); auto configAndFn = parseSILDifferentiabilityWitnessConfigAndFunction(P, *this, InstLoc); if (!configAndFn) return true; auto config = configAndFn->first; auto originalFn = configAndFn->second; auto *witness = SILMod.lookUpDifferentiabilityWitness( {originalFn->getName(), config}); if (!witness) { P.diagnose(keyStartLoc, diag::sil_diff_witness_undefined); return true; } // Parse an optional explicit function type. Optional<SILType> functionType = None; if (P.consumeIf(tok::kw_as)) { functionType = SILType(); if (parseSILType(*functionType)) return true; } ResultVal = B.createDifferentiabilityWitnessFunction( InstLoc, witnessKind, witness, functionType); break; } } return false; } /// sil-instruction-result ::= sil-value-name '=' /// sil-instruction-result ::= '(' sil-value-name? ')' /// sil-instruction-result ::= '(' sil-value-name (',' sil-value-name)* ')' /// sil-instruction-source-info ::= (',' sil-scope-ref)? (',' sil-loc)? /// sil-instruction-def ::= /// (sil-instruction-result '=')? sil-instruction sil-instruction-source-info bool SILParser::parseSILInstruction(SILBuilder &B) { // We require SIL instructions to be at the start of a line to assist // recovery. if (!P.Tok.isAtStartOfLine()) { P.diagnose(P.Tok, diag::expected_sil_instr_start_of_line); return true; } SmallVector<Located<StringRef>, 4> resultNames; SourceLoc resultClauseBegin; // If the instruction has a name '%foo =', parse it. if (P.Tok.is(tok::sil_local_name)) { resultClauseBegin = P.Tok.getLoc(); resultNames.push_back({P.Tok.getText(), P.Tok.getLoc()}); P.consumeToken(tok::sil_local_name); // If the instruction has a '(%foo, %bar) = ', parse it. } else if (P.consumeIf(tok::l_paren)) { resultClauseBegin = P.PreviousLoc; if (!P.consumeIf(tok::r_paren)) { while (true) { if (!P.Tok.is(tok::sil_local_name)) { P.diagnose(P.Tok, diag::expected_sil_value_name); return true; } resultNames.push_back({P.Tok.getText(), P.Tok.getLoc()}); P.consumeToken(tok::sil_local_name); if (P.consumeIf(tok::comma)) continue; if (P.consumeIf(tok::r_paren)) break; P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ","); return true; } } } if (resultClauseBegin.isValid()) { if (P.parseToken(tok::equal, diag::expected_equal_in_sil_instr)) return true; } SILInstructionKind Opcode; SourceLoc OpcodeLoc; StringRef OpcodeName; // Parse the opcode name. if (parseSILOpcode(Opcode, OpcodeLoc, OpcodeName)) return true; // Perform opcode specific parsing. SILInstruction *ResultVal; if (parseSpecificSILInstruction(B, Opcode, OpcodeLoc, OpcodeName, ResultVal)) return true; // Match the results clause if we had one. if (resultClauseBegin.isValid()) { auto results = ResultVal->getResults(); if (results.size() != resultNames.size()) { P.diagnose(resultClauseBegin, diag::wrong_result_count_in_sil_instr, results.size()); } else { for (size_t i : indices(results)) { setLocalValue(results[i], resultNames[i].Item, resultNames[i].Loc); } } } return false; } bool SILParser::parseCallInstruction(SILLocation InstLoc, SILInstructionKind Opcode, SILBuilder &B, SILInstruction *&ResultVal) { UnresolvedValueName FnName; SmallVector<UnresolvedValueName, 4> ArgNames; auto PartialApplyConvention = ParameterConvention::Direct_Owned; bool IsNonThrowingApply = false; bool IsNoEscape = false; StringRef AttrName; while (parseSILOptional(AttrName, *this)) { if (AttrName.equals("nothrow")) IsNonThrowingApply = true; else if (AttrName.equals("callee_guaranteed")) PartialApplyConvention = ParameterConvention::Direct_Guaranteed; else if (AttrName.equals("on_stack")) IsNoEscape = true; else return true; } if (parseValueName(FnName)) return true; SmallVector<ParsedSubstitution, 4> parsedSubs; if (parseSubstitutions(parsedSubs)) return true; if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "(")) return true; if (P.Tok.isNot(tok::r_paren)) { do { UnresolvedValueName Arg; if (parseValueName(Arg)) return true; ArgNames.push_back(Arg); } while (P.consumeIf(tok::comma)); } SILType Ty; SourceLoc TypeLoc; GenericEnvironment *GenericEnv = nullptr; if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")") || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") || parseSILType(Ty, TypeLoc, GenericEnv)) return true; auto FTI = Ty.getAs<SILFunctionType>(); if (!FTI) { P.diagnose(TypeLoc, diag::expected_sil_type_kind, "be a function"); return true; } SubstitutionMap subs; if (!parsedSubs.empty()) { if (!GenericEnv) { P.diagnose(TypeLoc, diag::sil_substitutions_on_non_polymorphic_type); return true; } subs = getApplySubstitutionsFromParsed(*this, GenericEnv, parsedSubs); if (!subs) return true; } SILValue FnVal = getLocalValue(FnName, Ty, InstLoc, B); SILType FnTy = FnVal->getType(); CanSILFunctionType substFTI = FTI; if (!subs.empty()) { auto silFnTy = FnTy.castTo<SILFunctionType>(); substFTI = silFnTy->substGenericArgs(SILMod, subs, B.getTypeExpansionContext()); FnTy = SILType::getPrimitiveObjectType(substFTI); } SILFunctionConventions substConv(substFTI, B.getModule()); // Validate the operand count. if (substConv.getNumSILArguments() != ArgNames.size() && Opcode != SILInstructionKind::PartialApplyInst) { P.diagnose(TypeLoc, diag::expected_sil_type_kind, "to have the same number of arg names as arg types"); return true; } // Validate the coroutine kind. if (Opcode == SILInstructionKind::ApplyInst || Opcode == SILInstructionKind::TryApplyInst) { if (FTI->getCoroutineKind() != SILCoroutineKind::None) { P.diagnose(TypeLoc, diag::expected_sil_type_kind, "to not be a coroutine"); return true; } } else if (Opcode == SILInstructionKind::BeginApplyInst) { if (FTI->getCoroutineKind() != SILCoroutineKind::YieldOnce) { P.diagnose(TypeLoc, diag::expected_sil_type_kind, "to be a yield_once coroutine"); return true; } } else { assert(Opcode == SILInstructionKind::PartialApplyInst); // partial_apply accepts all kinds of function } switch (Opcode) { default: llvm_unreachable("Unexpected case"); case SILInstructionKind::ApplyInst : { if (parseSILDebugLocation(InstLoc, B)) return true; unsigned ArgNo = 0; SmallVector<SILValue, 4> Args; for (auto &ArgName : ArgNames) { SILType expectedTy = substConv.getSILArgumentType(ArgNo++, B.getTypeExpansionContext()); Args.push_back(getLocalValue(ArgName, expectedTy, InstLoc, B)); } ResultVal = B.createApply(InstLoc, FnVal, subs, Args, IsNonThrowingApply); break; } case SILInstructionKind::BeginApplyInst: { if (parseSILDebugLocation(InstLoc, B)) return true; unsigned ArgNo = 0; SmallVector<SILValue, 4> Args; for (auto &ArgName : ArgNames) { SILType expectedTy = substConv.getSILArgumentType(ArgNo++, B.getTypeExpansionContext()); Args.push_back(getLocalValue(ArgName, expectedTy, InstLoc, B)); } ResultVal = B.createBeginApply(InstLoc, FnVal, subs, Args, IsNonThrowingApply); break; } case SILInstructionKind::PartialApplyInst: { if (parseSILDebugLocation(InstLoc, B)) return true; // Compute the result type of the partial_apply, based on which arguments // are getting applied. SmallVector<SILValue, 4> Args; unsigned ArgNo = substConv.getNumSILArguments() - ArgNames.size(); for (auto &ArgName : ArgNames) { SILType expectedTy = substConv.getSILArgumentType(ArgNo++, B.getTypeExpansionContext()); Args.push_back(getLocalValue(ArgName, expectedTy, InstLoc, B)); } // FIXME: Why the arbitrary order difference in IRBuilder type argument? ResultVal = B.createPartialApply( InstLoc, FnVal, subs, Args, PartialApplyConvention, IsNoEscape ? PartialApplyInst::OnStackKind::OnStack : PartialApplyInst::OnStackKind::NotOnStack); break; } case SILInstructionKind::TryApplyInst: { Identifier normalBBName, errorBBName; SourceLoc normalBBLoc, errorBBLoc; if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseVerbatim("normal") || parseSILIdentifier(normalBBName, normalBBLoc, diag::expected_sil_block_name) || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") || parseVerbatim("error") || parseSILIdentifier(errorBBName, errorBBLoc, diag::expected_sil_block_name) || parseSILDebugLocation(InstLoc, B)) return true; unsigned argNo = 0; SmallVector<SILValue, 4> args; for (auto &argName : ArgNames) { SILType expectedTy = substConv.getSILArgumentType(argNo++, B.getTypeExpansionContext()); args.push_back(getLocalValue(argName, expectedTy, InstLoc, B)); } SILBasicBlock *normalBB = getBBForReference(normalBBName, normalBBLoc); SILBasicBlock *errorBB = getBBForReference(errorBBName, errorBBLoc); ResultVal = B.createTryApply(InstLoc, FnVal, subs, args, normalBB, errorBB); break; } } return false; } bool SILParser::parseSILFunctionRef(SILLocation InstLoc, SILFunction *&ResultFn) { Identifier Name; SILType Ty; SourceLoc Loc = P.Tok.getLoc(); if (parseGlobalName(Name) || P.parseToken(tok::colon, diag::expected_sil_colon_value_ref) || parseSILType(Ty)) return true; auto FnTy = Ty.getAs<SILFunctionType>(); if (!FnTy || !Ty.isObject()) { P.diagnose(Loc, diag::expected_sil_function_type); return true; } ResultFn = getGlobalNameForReference(Name, FnTy, Loc); return false; } /// True if the current token sequence looks like the start of a SIL /// instruction. This can be one of: /// /// 1. %name /// 2. () /// 3. (%name1 /// 4. identifier | keyword /// where the identifier is not followed by a ':' or '(', or it is /// followed by '(' and is an instruction name. The exceptions here /// are for recognizing block names. bool SILParser::isStartOfSILInstruction() { if (P.Tok.is(tok::sil_local_name)) return true; if (P.Tok.is(tok::l_paren) && (P.peekToken().is(tok::sil_local_name) || P.peekToken().is(tok::r_paren))) return true; if (P.Tok.is(tok::identifier) || P.Tok.isKeyword()) { auto &peek = P.peekToken(); if (peek.is(tok::l_paren)) return getOpcodeByName(P.Tok.getText()).hasValue(); return !peek.is(tok::colon); } return false; } /// sil-basic-block: /// sil-instruction+ /// identifier sil-bb-argument-list? ':' sil-instruction+ /// sil-bb-argument-list: /// '(' sil-typed-valueref (',' sil-typed-valueref)+ ')' bool SILParser::parseSILBasicBlock(SILBuilder &B) { SILBasicBlock *BB; // The basic block name is optional. if (P.Tok.is(tok::sil_local_name)) { BB = getBBForDefinition(Identifier(), SourceLoc()); } else { Identifier BBName; SourceLoc NameLoc; if (parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name)) return true; BB = getBBForDefinition(BBName, NameLoc); // For now, since we always assume that PhiArguments have // ValueOwnershipKind::None, do not parse or do anything special. Eventually // we will parse the convention. bool IsEntry = BB->isEntry(); // If there is a basic block argument list, process it. if (P.consumeIf(tok::l_paren)) { do { SILType Ty; ValueOwnershipKind OwnershipKind = ValueOwnershipKind::None; SourceLoc NameLoc; StringRef Name = P.Tok.getText(); if (P.parseToken(tok::sil_local_name, NameLoc, diag::expected_sil_value_name) || P.parseToken(tok::colon, diag::expected_sil_colon_value_ref)) return true; // If SILOwnership is enabled and we are not assuming that we are // parsing unqualified SIL, look for printed value ownership kinds. if (F->hasOwnership() && parseSILOwnership(OwnershipKind)) return true; if (parseSILType(Ty)) return true; SILArgument *Arg; if (IsEntry) { Arg = BB->createFunctionArgument(Ty); // Today, we construct the ownership kind straight from the function // type. Make sure they are in sync, otherwise bail. We want this to // be an exact check rather than a compatibility check since we do not // want incompatibilities in between @any and other types of ownership // to be ignored. if (F->hasOwnership() && Arg->getOwnershipKind() != OwnershipKind) { auto diagID = diag::silfunc_and_silarg_have_incompatible_sil_value_ownership; P.diagnose(NameLoc, diagID, Arg->getOwnershipKind().asString(), OwnershipKind.asString()); return true; } } else { Arg = BB->createPhiArgument(Ty, OwnershipKind); } setLocalValue(Arg, Name, NameLoc); } while (P.consumeIf(tok::comma)); if (P.parseToken(tok::r_paren, diag::sil_basicblock_arg_rparen)) return true; } if (P.parseToken(tok::colon, diag::expected_sil_block_colon)) return true; } // Make sure the block is at the end of the function so that forward // references don't affect block layout. F->getBlocks().remove(BB); F->getBlocks().push_back(BB); B.setInsertionPoint(BB); do { if (parseSILInstruction(B)) return true; } while (isStartOfSILInstruction()); return false; } /// decl-sil: [[only in SIL mode]] /// 'sil' sil-linkage '@' identifier ':' sil-type decl-sil-body? /// decl-sil-body: /// '{' sil-basic-block+ '}' bool SILParserState::parseDeclSIL(Parser &P) { // Inform the lexer that we're lexing the body of the SIL declaration. Do // this before we consume the 'sil' token so that all later tokens are // properly handled. Lexer::SILBodyRAII Tmp(*P.L); P.consumeToken(tok::kw_sil); SILParser FunctionState(P); Optional<SILLinkage> FnLinkage; Identifier FnName; SILType FnType; SourceLoc FnNameLoc; Scope S(&P, ScopeKind::TopLevel); bool isTransparent = false; IsSerialized_t isSerialized = IsNotSerialized; bool isCanonical = false; IsDynamicallyReplaceable_t isDynamic = IsNotDynamic; IsExactSelfClass_t isExactSelfClass = IsNotExactSelfClass; bool hasOwnershipSSA = false; IsThunk_t isThunk = IsNotThunk; SILFunction::Purpose specialPurpose = SILFunction::Purpose::None; bool isWeakImported = false; AvailabilityContext availability = AvailabilityContext::alwaysAvailable(); bool isWithoutActuallyEscapingThunk = false; Inline_t inlineStrategy = InlineDefault; OptimizationMode optimizationMode = OptimizationMode::NotSet; SmallVector<std::string, 1> Semantics; SmallVector<ParsedSpecAttr, 4> SpecAttrs; ValueDecl *ClangDecl = nullptr; EffectsKind MRK = EffectsKind::Unspecified; SILFunction *DynamicallyReplacedFunction = nullptr; Identifier objCReplacementFor; if (parseSILLinkage(FnLinkage, P) || parseDeclSILOptional( &isTransparent, &isSerialized, &isCanonical, &hasOwnershipSSA, &isThunk, &isDynamic, &isExactSelfClass, &DynamicallyReplacedFunction, &objCReplacementFor, &specialPurpose, &inlineStrategy, &optimizationMode, nullptr, &isWeakImported, &availability, &isWithoutActuallyEscapingThunk, &Semantics, &SpecAttrs, &ClangDecl, &MRK, FunctionState, M) || P.parseToken(tok::at_sign, diag::expected_sil_function_name) || P.parseIdentifier(FnName, FnNameLoc, diag::expected_sil_function_name) || P.parseToken(tok::colon, diag::expected_sil_type)) return true; { // Construct a Scope for the function body so TypeAliasDecl can be added to // the scope. Scope Body(&P, ScopeKind::FunctionBody); GenericEnvironment *GenericEnv; if (FunctionState.parseSILType(FnType, GenericEnv, true /*IsFuncDecl*/)) return true; auto SILFnType = FnType.getAs<SILFunctionType>(); if (!SILFnType || !FnType.isObject()) { P.diagnose(FnNameLoc, diag::expected_sil_function_type); return true; } FunctionState.F = FunctionState.getGlobalNameForDefinition(FnName, SILFnType, FnNameLoc); FunctionState.F->setBare(IsBare); FunctionState.F->setTransparent(IsTransparent_t(isTransparent)); FunctionState.F->setSerialized(IsSerialized_t(isSerialized)); FunctionState.F->setWasDeserializedCanonical(isCanonical); if (!hasOwnershipSSA) FunctionState.F->setOwnershipEliminated(); FunctionState.F->setThunk(IsThunk_t(isThunk)); FunctionState.F->setIsDynamic(isDynamic); FunctionState.F->setIsExactSelfClass(isExactSelfClass); FunctionState.F->setDynamicallyReplacedFunction( DynamicallyReplacedFunction); if (!objCReplacementFor.empty()) FunctionState.F->setObjCReplacement(objCReplacementFor); FunctionState.F->setSpecialPurpose(specialPurpose); FunctionState.F->setAlwaysWeakImported(isWeakImported); FunctionState.F->setAvailabilityForLinkage(availability); FunctionState.F->setWithoutActuallyEscapingThunk( isWithoutActuallyEscapingThunk); FunctionState.F->setInlineStrategy(inlineStrategy); FunctionState.F->setOptimizationMode(optimizationMode); FunctionState.F->setEffectsKind(MRK); if (ClangDecl) FunctionState.F->setClangNodeOwner(ClangDecl); for (auto &Attr : Semantics) { FunctionState.F->addSemanticsAttr(Attr); } // Now that we have a SILFunction parse the body, if present. bool isDefinition = false; SourceLoc LBraceLoc = P.Tok.getLoc(); if (P.consumeIf(tok::l_brace)) { isDefinition = true; FunctionState.ContextGenericEnv = GenericEnv; FunctionState.F->setGenericEnvironment(GenericEnv); if (GenericEnv && !SpecAttrs.empty()) { for (auto &Attr : SpecAttrs) { SmallVector<Requirement, 2> requirements; // Resolve types and convert requirements. FunctionState.convertRequirements(FunctionState.F, Attr.requirements, requirements); auto *fenv = FunctionState.F->getGenericEnvironment(); auto genericSig = evaluateOrDefault( P.Context.evaluator, AbstractGenericSignatureRequest{ fenv->getGenericSignature().getPointer(), /*addedGenericParams=*/{ }, std::move(requirements)}, GenericSignature()); FunctionState.F->addSpecializeAttr(SILSpecializeAttr::create( FunctionState.F->getModule(), genericSig, Attr.exported, Attr.kind)); } } // Parse the basic block list. SILOpenedArchetypesTracker OpenedArchetypesTracker(FunctionState.F); SILBuilder B(*FunctionState.F); // Track the archetypes just like SILGen. This // is required for adding typedef operands to instructions. B.setOpenedArchetypesTracker(&OpenedArchetypesTracker); // Define a callback to be invoked on the deserialized types. auto OldParsedTypeCallback = FunctionState.ParsedTypeCallback; SWIFT_DEFER { FunctionState.ParsedTypeCallback = OldParsedTypeCallback; }; FunctionState.ParsedTypeCallback = [&OpenedArchetypesTracker](Type ty) { OpenedArchetypesTracker.registerUsedOpenedArchetypes( ty->getCanonicalType()); }; do { if (FunctionState.parseSILBasicBlock(B)) return true; } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof)); SourceLoc RBraceLoc; P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace, LBraceLoc); // Check that there are no unresolved forward definitions of opened // archetypes. if (OpenedArchetypesTracker.hasUnresolvedOpenedArchetypeDefinitions()) llvm_unreachable( "All forward definitions of opened archetypes should be resolved"); } FunctionState.F->setLinkage(resolveSILLinkage(FnLinkage, isDefinition)); } if (FunctionState.diagnoseProblems()) return true; // If SIL parsing succeeded, verify the generated SIL. if (!P.Diags.hadAnyError()) FunctionState.F->verify(); return false; } /// decl-sil-stage: [[only in SIL mode]] /// 'sil_stage' ('raw' | 'canonical') bool SILParserState::parseDeclSILStage(Parser &P) { SourceLoc stageLoc = P.consumeToken(tok::kw_sil_stage); if (!P.Tok.is(tok::identifier)) { P.diagnose(P.Tok, diag::expected_sil_stage_name); return true; } SILStage stage; if (P.Tok.isContextualKeyword("raw")) { stage = SILStage::Raw; P.consumeToken(); } else if (P.Tok.isContextualKeyword("canonical")) { stage = SILStage::Canonical; P.consumeToken(); } else if (P.Tok.isContextualKeyword("lowered")) { stage = SILStage::Lowered; P.consumeToken(); } else { P.diagnose(P.Tok, diag::expected_sil_stage_name); P.consumeToken(); return true; } if (DidParseSILStage) { P.diagnose(stageLoc, diag::multiple_sil_stage_decls); return false; } M.setStage(stage); DidParseSILStage = true; return false; } /// Lookup a global variable declaration from its demangled name. /// /// A variable declaration exists for all sil_global variables defined in /// Swift. A Swift global defined outside this module will be exposed /// via an addressor rather than as a sil_global. Globals imported /// from clang will produce a sil_global but will not have any corresponding /// VarDecl. /// /// FIXME: lookupGlobalDecl() can handle collisions between private or /// fileprivate global variables in the same SIL Module, but the typechecker /// will still incorrectly diagnose this as an "invalid redeclaration" and give /// all but the first declaration an error type. static Optional<VarDecl *> lookupGlobalDecl(Identifier GlobalName, SILLinkage GlobalLinkage, SILType GlobalType, Parser &P) { // Create a set of DemangleOptions to produce the global variable's // identifier, which is used as a search key in the declaration context. Demangle::DemangleOptions demangleOpts; demangleOpts.QualifyEntities = false; demangleOpts.ShowPrivateDiscriminators = false; demangleOpts.DisplayEntityTypes = false; std::string GlobalDeclName = Demangle::demangleSymbolAsString( GlobalName.str(), demangleOpts); SmallVector<ValueDecl *, 4> CurModuleResults; P.SF.getParentModule()->lookupValue( P.Context.getIdentifier(GlobalDeclName), NLKind::UnqualifiedLookup, CurModuleResults); // Bail-out on clang-imported globals. if (CurModuleResults.empty()) return nullptr; // private and fileprivate globals of the same name may be merged into a // single SIL module. Find the declaration with the correct type and // linkage. (If multiple globals have the same type and linkage then it // doesn't matter which declaration we use). for (ValueDecl *ValDecl : CurModuleResults) { auto *VD = cast<VarDecl>(ValDecl); CanType DeclTy = VD->getType()->getCanonicalType(); if (DeclTy == GlobalType.getASTType() && getDeclSILLinkage(VD) == GlobalLinkage) { return VD; } } return None; } /// decl-sil-global: [[only in SIL mode]] /// 'sil_global' sil-linkage @name : sil-type [external] bool SILParserState::parseSILGlobal(Parser &P) { // Inform the lexer that we're lexing the body of the SIL declaration. Lexer::SILBodyRAII Tmp(*P.L); P.consumeToken(tok::kw_sil_global); Optional<SILLinkage> GlobalLinkage; Identifier GlobalName; SILType GlobalType; SourceLoc NameLoc; IsSerialized_t isSerialized = IsNotSerialized; bool isLet = false; Scope S(&P, ScopeKind::TopLevel); SILParser State(P); if (parseSILLinkage(GlobalLinkage, P) || parseDeclSILOptional(nullptr, &isSerialized, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &isLet, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, State, M) || P.parseToken(tok::at_sign, diag::expected_sil_value_name) || P.parseIdentifier(GlobalName, NameLoc, diag::expected_sil_value_name) || P.parseToken(tok::colon, diag::expected_sil_type)) return true; if (State.parseSILType(GlobalType)) return true; // Non-external global variables are definitions by default. if (!GlobalLinkage.hasValue()) GlobalLinkage = SILLinkage::DefaultForDefinition; // Lookup the global variable declaration for this sil_global. auto VD = lookupGlobalDecl(GlobalName, GlobalLinkage.getValue(), GlobalType, P); if (!VD) { P.diagnose(NameLoc, diag::sil_global_variable_not_found, GlobalName); return true; } auto *GV = SILGlobalVariable::create( M, GlobalLinkage.getValue(), isSerialized, GlobalName.str(), GlobalType, RegularLocation(NameLoc), VD.getValue()); GV->setLet(isLet); // Parse static initializer if exists. if (State.P.consumeIf(tok::equal) && State.P.consumeIf(tok::l_brace)) { SILBuilder B(GV); do { State.parseSILInstruction(B); } while (! State.P.consumeIf(tok::r_brace)); } return false; } /// decl-sil-property: [[only in SIL mode]] /// 'sil_property' sil-decl-ref '(' sil-key-path-pattern-component ')' bool SILParserState::parseSILProperty(Parser &P) { Lexer::SILBodyRAII Tmp(*P.L); auto loc = P.consumeToken(tok::kw_sil_property); auto InstLoc = RegularLocation(loc); SILParser SP(P); IsSerialized_t Serialized = IsNotSerialized; if (parseDeclSILOptional(nullptr, &Serialized, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, SP, M)) return true; ValueDecl *VD; if (SP.parseSILDottedPath(VD)) return true; GenericParamList *generics; GenericEnvironment *patternEnv; Scope toplevelScope(&P, ScopeKind::TopLevel); Scope genericsScope(&P, ScopeKind::Generics); generics = P.maybeParseGenericParams().getPtrOrNull(); patternEnv = handleSILGenericParams(generics, &P.SF); if (patternEnv) { if (patternEnv->getGenericSignature().getCanonicalSignature() != VD->getInnermostDeclContext() ->getGenericSignatureOfContext() .getCanonicalSignature()) { P.diagnose(loc, diag::sil_property_generic_signature_mismatch); return true; } } else { if (VD->getInnermostDeclContext()->getGenericSignatureOfContext()) { P.diagnose(loc, diag::sil_property_generic_signature_mismatch); return true; } } Identifier ComponentKind; Optional<KeyPathPatternComponent> Component; SourceLoc ComponentLoc; SmallVector<SILType, 4> OperandTypes; if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "(")) return true; if (!P.consumeIf(tok::r_paren)) { KeyPathPatternComponent parsedComponent; if (P.parseIdentifier(ComponentKind, ComponentLoc, diag::expected_tok_in_sil_instr, "component kind") || SP.parseKeyPathPatternComponent(parsedComponent, OperandTypes, ComponentLoc, ComponentKind, InstLoc, patternEnv) || P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")")) return true; Component = std::move(parsedComponent); } SILProperty::create(M, Serialized, cast<AbstractStorageDecl>(VD), Component); return false; } /// decl-sil-vtable: [[only in SIL mode]] /// 'sil_vtable' ClassName decl-sil-vtable-body /// decl-sil-vtable-body: /// '{' sil-vtable-entry* '}' /// sil-vtable-entry: /// SILDeclRef ':' SILFunctionName bool SILParserState::parseSILVTable(Parser &P) { P.consumeToken(tok::kw_sil_vtable); SILParser VTableState(P); IsSerialized_t Serialized = IsNotSerialized; if (parseDeclSILOptional(nullptr, &Serialized, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, VTableState, M)) return true; // Parse the class name. Identifier Name; SourceLoc Loc; if (VTableState.parseSILIdentifier(Name, Loc, diag::expected_sil_value_name)) return true; // Find the class decl. llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res = lookupTopDecl(P, Name, /*typeLookup=*/true); assert(Res.is<ValueDecl*>() && "Class look-up should return a Decl"); ValueDecl *VD = Res.get<ValueDecl*>(); if (!VD) { P.diagnose(Loc, diag::sil_vtable_class_not_found, Name); return true; } auto *theClass = dyn_cast<ClassDecl>(VD); if (!theClass) { P.diagnose(Loc, diag::sil_vtable_class_not_found, Name); return true; } SourceLoc LBraceLoc = P.Tok.getLoc(); P.consumeToken(tok::l_brace); // We need to turn on InSILBody to parse SILDeclRef. Lexer::SILBodyRAII Tmp(*P.L); Scope S(&P, ScopeKind::TopLevel); // Parse the entry list. std::vector<SILVTable::Entry> vtableEntries; if (P.Tok.isNot(tok::r_brace)) { do { SILDeclRef Ref; Identifier FuncName; SourceLoc FuncLoc; if (VTableState.parseSILDeclRef(Ref, true)) return true; SILFunction *Func = nullptr; if (P.Tok.is(tok::kw_nil)) { P.consumeToken(); } else { if (P.parseToken(tok::colon, diag::expected_sil_vtable_colon) || P.parseToken(tok::at_sign, diag::expected_sil_function_name) || VTableState.parseSILIdentifier(FuncName, FuncLoc, diag::expected_sil_value_name)) return true; Func = M.lookUpFunction(FuncName.str()); if (!Func) { P.diagnose(FuncLoc, diag::sil_vtable_func_not_found, FuncName); return true; } } auto Kind = SILVTable::Entry::Kind::Normal; bool NonOverridden = false; while (P.Tok.is(tok::l_square)) { P.consumeToken(tok::l_square); if (P.Tok.isNot(tok::identifier)) { P.diagnose(P.Tok.getLoc(), diag::sil_vtable_bad_entry_kind); return true; } if (P.Tok.getText() == "override") { P.consumeToken(); Kind = SILVTable::Entry::Kind::Override; } else if (P.Tok.getText() == "inherited") { P.consumeToken(); Kind = SILVTable::Entry::Kind::Inherited; } else if (P.Tok.getText() == "nonoverridden") { P.consumeToken(); NonOverridden = true; } else { P.diagnose(P.Tok.getLoc(), diag::sil_vtable_bad_entry_kind); return true; } if (P.parseToken(tok::r_square, diag::sil_vtable_expect_rsquare)) return true; } vtableEntries.emplace_back(Ref, Func, Kind, NonOverridden); } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof)); } SourceLoc RBraceLoc; P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace, LBraceLoc); SILVTable::create(M, theClass, Serialized, vtableEntries); return false; } static ProtocolDecl *parseProtocolDecl(Parser &P, SILParser &SP) { Identifier DeclName; SourceLoc DeclLoc; if (SP.parseSILIdentifier(DeclName, DeclLoc, diag::expected_sil_value_name)) return nullptr; // Find the protocol decl. The protocol can be imported. llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res = lookupTopDecl(P, DeclName, /*typeLookup=*/true); assert(Res.is<ValueDecl*>() && "Protocol look-up should return a Decl"); ValueDecl *VD = Res.get<ValueDecl*>(); if (!VD) { P.diagnose(DeclLoc, diag::sil_witness_protocol_not_found, DeclName); return nullptr; } auto *proto = dyn_cast<ProtocolDecl>(VD); if (!proto) P.diagnose(DeclLoc, diag::sil_witness_protocol_not_found, DeclName); return proto; } static AssociatedTypeDecl *parseAssociatedTypeDecl(Parser &P, SILParser &SP, ProtocolDecl *proto) { Identifier DeclName; SourceLoc DeclLoc; if (SP.parseSILIdentifier(DeclName, DeclLoc, diag::expected_sil_value_name)) return nullptr; // We can return multiple decls, for now, we use the first lookup result. // One example is two decls when searching for Generator of Sequence: // one from Sequence, the other from _Sequence_Type. SmallVector<ValueDecl *, 4> values; auto VD = lookupMember(P, proto->getInterfaceType(), DeclName, DeclLoc, values, true/*ExpectMultipleResults*/); if (!VD) { P.diagnose(DeclLoc, diag::sil_witness_assoc_not_found, DeclName); return nullptr; } return dyn_cast<AssociatedTypeDecl>(VD); } static bool parseAssociatedTypePath(SILParser &SP, SmallVectorImpl<Identifier> &path) { do { Identifier name; SourceLoc loc; if (SP.parseSILIdentifier(name, loc, diag::expected_sil_value_name)) return false; path.push_back(name); } while (SP.P.consumeIf(tok::period)); return true; } static bool matchesAssociatedTypePath(CanType assocType, ArrayRef<Identifier> path) { if (auto memberType = dyn_cast<DependentMemberType>(assocType)) { return (!path.empty() && memberType->getName() == path.back() && matchesAssociatedTypePath(memberType.getBase(), path.drop_back())); } else { assert(isa<GenericTypeParamType>(assocType)); return path.empty(); } } static CanType parseAssociatedTypePath(Parser &P, SILParser &SP, ProtocolDecl *proto) { SourceLoc loc = SP.P.Tok.getLoc(); SmallVector<Identifier, 4> path; if (!parseAssociatedTypePath(SP, path)) return CanType(); // This is only used for parsing associated conformances, so we can // go ahead and just search the requirement signature for something that // matches the path. for (auto &reqt : proto->getRequirementSignature()) { if (reqt.getKind() != RequirementKind::Conformance) continue; CanType assocType = reqt.getFirstType()->getCanonicalType(); if (matchesAssociatedTypePath(assocType, path)) return assocType; } SmallString<128> name; name += path[0].str(); for (auto elt : makeArrayRef(path).slice(1)) { name += '.'; name += elt.str(); } P.diagnose(loc, diag::sil_witness_assoc_conf_not_found, name); return CanType(); } static bool isSelfConformance(Type conformingType, ProtocolDecl *protocol) { if (auto protoTy = conformingType->getAs<ProtocolType>()) return protoTy->getDecl() == protocol; return false; } static ProtocolConformanceRef parseRootProtocolConformance(Parser &P, SILParser &SP, Type ConformingTy, ProtocolDecl *&proto, ConformanceContext context) { Identifier ModuleKeyword, ModuleName; SourceLoc Loc, KeywordLoc; proto = parseProtocolDecl(P, SP); if (!proto) return ProtocolConformanceRef(); if (P.parseIdentifier(ModuleKeyword, KeywordLoc, diag::expected_tok_in_sil_instr, "module") || SP.parseSILIdentifier(ModuleName, Loc, diag::expected_sil_value_name)) return ProtocolConformanceRef(); if (ModuleKeyword.str() != "module") { P.diagnose(KeywordLoc, diag::expected_tok_in_sil_instr, "module"); return ProtocolConformanceRef(); } // Calling lookupConformance on a BoundGenericType will return a specialized // conformance. We use UnboundGenericType to find the normal conformance. Type lookupTy = ConformingTy; if (auto bound = lookupTy->getAs<BoundGenericType>()) lookupTy = bound->getDecl()->getDeclaredType(); auto lookup = P.SF.getParentModule()->lookupConformance(lookupTy, proto); if (lookup.isInvalid()) { P.diagnose(KeywordLoc, diag::sil_witness_protocol_conformance_not_found); return ProtocolConformanceRef(); } // Use a concrete self-conformance if we're parsing this for a witness table. if (context == ConformanceContext::WitnessTable && !lookup.isConcrete() && isSelfConformance(ConformingTy, proto)) { lookup = ProtocolConformanceRef(P.Context.getSelfConformance(proto)); } return lookup; } /// protocol-conformance ::= normal-protocol-conformance /// protocol-conformance ::= /// generic-parameter-list? type: 'inherit' '(' protocol-conformance ')' /// protocol-conformance ::= /// generic-parameter-list? type: 'specialize' '<' substitution* '>' /// '(' protocol-conformance ')' /// normal-protocol-conformance ::= /// generic-parameter-list? type: protocolName module ModuleName /// Note that generic-parameter-list is already parsed before calling this. ProtocolConformanceRef SILParser::parseProtocolConformance( ProtocolDecl *&proto, GenericEnvironment *&genericEnv, ConformanceContext context, ProtocolDecl *defaultForProto) { // Parse generic params for the protocol conformance. We need to make sure // they have the right scope. Optional<Scope> GenericsScope; if (context == ConformanceContext::Ordinary) GenericsScope.emplace(&P, ScopeKind::Generics); // Make sure we don't leave it uninitialized in the caller genericEnv = nullptr; auto *genericParams = P.maybeParseGenericParams().getPtrOrNull(); if (genericParams) { genericEnv = handleSILGenericParams(genericParams, &P.SF); } else if (defaultForProto) { genericEnv = defaultForProto->getGenericEnvironment(); } auto retVal = parseProtocolConformanceHelper(proto, genericEnv, context, defaultForProto); if (GenericsScope) { GenericsScope.reset(); } return retVal; } ProtocolConformanceRef SILParser::parseProtocolConformanceHelper( ProtocolDecl *&proto, GenericEnvironment *witnessEnv, ConformanceContext context, ProtocolDecl *defaultForProto) { // Parse AST type. ParserResult<TypeRepr> TyR = P.parseType(); if (TyR.isNull()) return ProtocolConformanceRef(); if (defaultForProto) { bindProtocolSelfInTypeRepr(TyR.get(), defaultForProto); } const auto ConformingTy = performTypeResolution(TyR.get(), /*IsSILType=*/false, witnessEnv); if (ConformingTy->hasError()) return ProtocolConformanceRef(); if (P.parseToken(tok::colon, diag::expected_sil_witness_colon)) return ProtocolConformanceRef(); if (P.Tok.is(tok::identifier) && P.Tok.getText() == "specialize") { P.consumeToken(); // Parse substitutions for specialized conformance. SmallVector<ParsedSubstitution, 4> parsedSubs; if (parseSubstitutions(parsedSubs, witnessEnv, defaultForProto)) return ProtocolConformanceRef(); if (P.parseToken(tok::l_paren, diag::expected_sil_witness_lparen)) return ProtocolConformanceRef(); ProtocolDecl *dummy; GenericEnvironment *specializedEnv; auto genericConform = parseProtocolConformance(dummy, specializedEnv, ConformanceContext::Ordinary, defaultForProto); if (genericConform.isInvalid() || !genericConform.isConcrete()) return ProtocolConformanceRef(); if (P.parseToken(tok::r_paren, diag::expected_sil_witness_rparen)) return ProtocolConformanceRef(); SubstitutionMap subMap = getApplySubstitutionsFromParsed(*this, specializedEnv, parsedSubs); if (!subMap) return ProtocolConformanceRef(); auto result = P.Context.getSpecializedConformance( ConformingTy, genericConform.getConcrete(), subMap); return ProtocolConformanceRef(result); } if (P.Tok.is(tok::identifier) && P.Tok.getText() == "inherit") { P.consumeToken(); if (P.parseToken(tok::l_paren, diag::expected_sil_witness_lparen)) return ProtocolConformanceRef(); auto baseConform = parseProtocolConformance(defaultForProto, ConformanceContext::Ordinary); if (baseConform.isInvalid() || !baseConform.isConcrete()) return ProtocolConformanceRef(); if (P.parseToken(tok::r_paren, diag::expected_sil_witness_rparen)) return ProtocolConformanceRef(); auto result = P.Context.getInheritedConformance(ConformingTy, baseConform.getConcrete()); return ProtocolConformanceRef(result); } auto retVal = parseRootProtocolConformance(P, *this, ConformingTy, proto, context); return retVal; } /// Parser a single SIL vtable entry and add it to either \p witnessEntries /// or \c conditionalConformances. static bool parseSILVTableEntry( Parser &P, SILModule &M, ProtocolDecl *proto, GenericEnvironment *witnessEnv, SILParser &witnessState, bool isDefaultWitnessTable, std::vector<SILWitnessTable::Entry> &witnessEntries, std::vector<SILWitnessTable::ConditionalConformance> &conditionalConformances) { ProtocolDecl *defaultForProto = isDefaultWitnessTable ? proto : nullptr; Identifier EntryKeyword; SourceLoc KeywordLoc; if (P.parseIdentifier(EntryKeyword, KeywordLoc, diag::expected_tok_in_sil_instr, "method, associated_type, associated_type_protocol, base_protocol" ", no_default")) return true; if (EntryKeyword.str() == "no_default") { witnessEntries.push_back(SILDefaultWitnessTable::Entry()); return false; } if (EntryKeyword.str() == "base_protocol") { ProtocolDecl *proto = parseProtocolDecl(P, witnessState); if (!proto) return true; if (P.parseToken(tok::colon, diag::expected_sil_witness_colon)) return true; auto conform = witnessState.parseProtocolConformance(defaultForProto, ConformanceContext::Ordinary); // Ignore invalid and abstract witness entries. if (conform.isInvalid() || !conform.isConcrete()) return false; witnessEntries.push_back( SILWitnessTable::BaseProtocolWitness{proto, conform.getConcrete()}); return false; } if (EntryKeyword.str() == "associated_type_protocol" || EntryKeyword.str() == "conditional_conformance") { if (P.parseToken(tok::l_paren, diag::expected_sil_witness_lparen)) return true; CanType assocOrSubject; if (EntryKeyword.str() == "associated_type_protocol") { assocOrSubject = parseAssociatedTypePath(P, witnessState, proto); } else { // Parse AST type. ParserResult<TypeRepr> TyR = P.parseType(); if (TyR.isNull()) return true; if (isDefaultWitnessTable) bindProtocolSelfInTypeRepr(TyR.get(), proto); const auto Ty = swift::performTypeResolution(TyR.get(), P.Context, /*isSILMode=*/false, /*isSILType=*/false, witnessEnv, &P.SF); if (Ty->hasError()) return true; assocOrSubject = Ty->getCanonicalType(); } if (!assocOrSubject) return true; if (P.parseToken(tok::colon, diag::expected_sil_witness_colon)) return true; ProtocolDecl *proto = parseProtocolDecl(P, witnessState); if (!proto) return true; if (P.parseToken(tok::r_paren, diag::expected_sil_witness_rparen) || P.parseToken(tok::colon, diag::expected_sil_witness_colon)) return true; ProtocolConformanceRef conformance(proto); if (P.Tok.getText() != "dependent") { auto concrete = witnessState.parseProtocolConformance(defaultForProto, ConformanceContext::Ordinary); // Ignore invalid and abstract witness entries. if (concrete.isInvalid() || !concrete.isConcrete()) return false; conformance = concrete; } else { P.consumeToken(); } if (EntryKeyword.str() == "associated_type_protocol") witnessEntries.push_back( SILWitnessTable::AssociatedTypeProtocolWitness{assocOrSubject, proto, conformance}); else conditionalConformances.push_back( SILWitnessTable::ConditionalConformance{assocOrSubject, conformance}); return false; } if (EntryKeyword.str() == "associated_type") { AssociatedTypeDecl *assoc = parseAssociatedTypeDecl(P, witnessState, proto); if (!assoc) return true; if (P.parseToken(tok::colon, diag::expected_sil_witness_colon)) return true; // Parse AST type. ParserResult<TypeRepr> TyR = P.parseType(); if (TyR.isNull()) return true; if (isDefaultWitnessTable) bindProtocolSelfInTypeRepr(TyR.get(), proto); const auto Ty = swift::performTypeResolution(TyR.get(), P.Context, /*isSILMode=*/false, /*isSILType=*/false, witnessEnv, &P.SF); if (Ty->hasError()) return true; witnessEntries.push_back( SILWitnessTable::AssociatedTypeWitness{assoc, Ty->getCanonicalType()}); return false; } if (EntryKeyword.str() != "method") { P.diagnose(KeywordLoc, diag::expected_tok_in_sil_instr, "method"); return true; } SILDeclRef Ref; Identifier FuncName; SourceLoc FuncLoc; if (witnessState.parseSILDeclRef(Ref, true) || P.parseToken(tok::colon, diag::expected_sil_witness_colon)) return true; SILFunction *Func = nullptr; if (P.Tok.is(tok::kw_nil)) { P.consumeToken(); } else { if (P.parseToken(tok::at_sign, diag::expected_sil_function_name) || witnessState.parseSILIdentifier(FuncName, FuncLoc, diag::expected_sil_value_name)) return true; Func = M.lookUpFunction(FuncName.str()); if (!Func) { P.diagnose(FuncLoc, diag::sil_witness_func_not_found, FuncName); return true; } } witnessEntries.push_back(SILWitnessTable::MethodWitness{ Ref, Func }); return false; } /// decl-sil-witness ::= 'sil_witness_table' sil-linkage? /// normal-protocol-conformance decl-sil-witness-body /// normal-protocol-conformance ::= /// generic-parameter-list? type: protocolName module ModuleName /// decl-sil-witness-body: /// '{' sil-witness-entry* '}' /// sil-witness-entry: /// method SILDeclRef ':' @SILFunctionName /// associated_type AssociatedTypeDeclName: Type /// associated_type_protocol (AssocName: ProtocolName): /// protocol-conformance|dependent /// base_protocol ProtocolName: protocol-conformance bool SILParserState::parseSILWitnessTable(Parser &P) { P.consumeToken(tok::kw_sil_witness_table); SILParser WitnessState(P); // Parse the linkage. Optional<SILLinkage> Linkage; parseSILLinkage(Linkage, P); IsSerialized_t isSerialized = IsNotSerialized; if (parseDeclSILOptional(nullptr, &isSerialized, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, WitnessState, M)) return true; Scope S(&P, ScopeKind::TopLevel); // We should use WitnessTableBody. This ensures that the generic params // are visible. Optional<Scope> BodyScope; BodyScope.emplace(&P, ScopeKind::FunctionBody); // Parse the protocol conformance. ProtocolDecl *proto; GenericEnvironment *witnessEnv; auto conf = WitnessState.parseProtocolConformance(proto, witnessEnv, ConformanceContext::WitnessTable, nullptr); WitnessState.ContextGenericEnv = witnessEnv; // FIXME: should we really allow a specialized or inherited conformance here? RootProtocolConformance *theConformance = nullptr; if (conf.isConcrete()) theConformance = conf.getConcrete()->getRootConformance(); SILWitnessTable *wt = nullptr; if (theConformance) { wt = M.lookUpWitnessTable(theConformance, false); assert((!wt || wt->isDeclaration()) && "Attempting to create duplicate witness table."); } // If we don't have an lbrace, then this witness table is a declaration. if (P.Tok.getKind() != tok::l_brace) { // Default to public external linkage. if (!Linkage) Linkage = SILLinkage::PublicExternal; // We ignore empty witness table without normal protocol conformance. if (!wt && theConformance) wt = SILWitnessTable::create(M, *Linkage, theConformance); BodyScope.reset(); return false; } if (!theConformance) { P.diagnose(P.Tok, diag::sil_witness_protocol_conformance_not_found); return true; } SourceLoc LBraceLoc = P.Tok.getLoc(); P.consumeToken(tok::l_brace); // We need to turn on InSILBody to parse SILDeclRef. Lexer::SILBodyRAII Tmp(*P.L); // Parse the entry list. std::vector<SILWitnessTable::Entry> witnessEntries; std::vector<SILWitnessTable::ConditionalConformance> conditionalConformances; if (P.Tok.isNot(tok::r_brace)) { do { if (parseSILVTableEntry(P, M, proto, witnessEnv, WitnessState, false, witnessEntries, conditionalConformances)) return true; } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof)); } SourceLoc RBraceLoc; P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace, LBraceLoc); // Default to public linkage. if (!Linkage) Linkage = SILLinkage::Public; if (!wt) wt = SILWitnessTable::create(M, *Linkage, theConformance); else wt->setLinkage(*Linkage); wt->convertToDefinition(witnessEntries, conditionalConformances, isSerialized); BodyScope.reset(); return false; } /// decl-sil-default-witness ::= 'sil_default_witness_table' /// sil-linkage identifier /// decl-sil-default-witness-body /// decl-sil-default-witness-body: /// '{' sil-default-witness-entry* '}' /// sil-default-witness-entry: /// sil-witness-entry /// 'no_default' bool SILParserState::parseSILDefaultWitnessTable(Parser &P) { P.consumeToken(tok::kw_sil_default_witness_table); SILParser WitnessState(P); // Parse the linkage. Optional<SILLinkage> Linkage; parseSILLinkage(Linkage, P); Scope S(&P, ScopeKind::TopLevel); // We should use WitnessTableBody. This ensures that the generic params // are visible. Optional<Scope> BodyScope; BodyScope.emplace(&P, ScopeKind::FunctionBody); // Parse the protocol. ProtocolDecl *protocol = parseProtocolDecl(P, WitnessState); if (!protocol) return true; // Parse the body. SourceLoc LBraceLoc = P.Tok.getLoc(); P.consumeToken(tok::l_brace); // We need to turn on InSILBody to parse SILDeclRef. Lexer::SILBodyRAII Tmp(*P.L); // Parse the entry list. std::vector<SILWitnessTable::Entry> witnessEntries; std::vector<SILWitnessTable::ConditionalConformance> conditionalConformances; if (P.Tok.isNot(tok::r_brace)) { do { if (parseSILVTableEntry(P, M, protocol, protocol->getGenericEnvironment(), WitnessState, true, witnessEntries, conditionalConformances)) return true; } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof)); } SourceLoc RBraceLoc; P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace, LBraceLoc); // Default to public linkage. if (!Linkage) Linkage = SILLinkage::Public; SILDefaultWitnessTable::create(M, *Linkage, protocol, witnessEntries); BodyScope.reset(); return false; } /// decl-sil-differentiability-witness ::= /// 'sil_differentiability_witness' /// ('[' 'serialized' ']')? /// sil-linkage? /// sil-differentiability-witness-config-and-function /// decl-sil-differentiability-witness-body? /// /// decl-sil-differentiability-witness-body ::= /// '{' /// ('jvp' sil-function-name ':' sil-type)? /// ('vjp' sil-function-name ':' sil-type)? /// '}' /// /// index-subset ::= /// [0-9]+ (' ' [0-9]+)* bool SILParserState::parseSILDifferentiabilityWitness(Parser &P) { auto loc = P.consumeToken(tok::kw_sil_differentiability_witness); auto silLoc = RegularLocation(loc); SILParser State(P); // Parse the linkage. Optional<SILLinkage> linkage; if (parseSILLinkage(linkage, P)) return true; // Parse '[serialized]' flag (optional). bool isSerialized = false; SourceLoc serializedTokLoc; if (P.Tok.is(tok::l_square) && P.isIdentifier(P.peekToken(), "serialized")) { isSerialized = true; serializedTokLoc = P.Tok.getLoc(); P.consumeToken(tok::l_square); P.consumeToken(tok::identifier); if (P.parseToken(tok::r_square, diag::sil_diff_witness_expected_token, "]")) return true; } Scope scope(&P, ScopeKind::TopLevel); Scope body(&P, ScopeKind::FunctionBody); // We need to turn on InSILBody to parse the function references. Lexer::SILBodyRAII tmp(*P.L); auto configAndFn = parseSILDifferentiabilityWitnessConfigAndFunction(P, State, silLoc); if (!configAndFn) { return true; } auto config = configAndFn->first; auto originalFn = configAndFn->second; // If this is just a declaration, create the declaration now and return. if (!P.Tok.is(tok::l_brace)) { if (isSerialized) { P.diagnose(serializedTokLoc, diag::sil_diff_witness_serialized_declaration); return true; } SILDifferentiabilityWitness::createDeclaration( M, linkage ? *linkage : SILLinkage::DefaultForDeclaration, originalFn, config.parameterIndices, config.resultIndices, config.derivativeGenericSignature); return false; } // This is a definition, so parse differentiability witness body. SILFunction *jvp = nullptr; SILFunction *vjp = nullptr; if (P.Tok.is(tok::l_brace)) { // Parse '{'. SourceLoc lBraceLoc; P.consumeIf(tok::l_brace, lBraceLoc); // Parse JVP (optional). if (P.isIdentifier(P.Tok, "jvp")) { P.consumeToken(tok::identifier); if (P.parseToken(tok::colon, diag::sil_diff_witness_expected_token, ":")) return true; Scope body(&P, ScopeKind::FunctionBody); if (State.parseSILFunctionRef(silLoc, jvp)) return true; } // Parse VJP (optional). if (P.isIdentifier(P.Tok, "vjp")) { P.consumeToken(tok::identifier); if (P.parseToken(tok::colon, diag::sil_diff_witness_expected_token, ":")) return true; Scope body(&P, ScopeKind::FunctionBody); if (State.parseSILFunctionRef(silLoc, vjp)) return true; } // Parse '}'. SourceLoc rBraceLoc; if (P.parseMatchingToken(tok::r_brace, rBraceLoc, diag::expected_sil_rbrace, lBraceLoc)) return true; } SILDifferentiabilityWitness::createDefinition( M, linkage ? *linkage : SILLinkage::DefaultForDefinition, originalFn, config.parameterIndices, config.resultIndices, config.derivativeGenericSignature, jvp, vjp, isSerialized); return false; } llvm::Optional<llvm::coverage::Counter> SILParser::parseSILCoverageExpr( llvm::coverage::CounterExpressionBuilder &Builder) { if (P.Tok.is(tok::integer_literal)) { unsigned CounterId; if (parseInteger(CounterId, diag::sil_coverage_invalid_counter)) return None; return llvm::coverage::Counter::getCounter(CounterId); } if (P.Tok.is(tok::identifier)) { Identifier Zero; SourceLoc Loc; if (parseSILIdentifier(Zero, Loc, diag::sil_coverage_invalid_counter)) return None; if (Zero.str() != "zero") { P.diagnose(Loc, diag::sil_coverage_invalid_counter); return None; } return llvm::coverage::Counter::getZero(); } if (P.Tok.is(tok::l_paren)) { P.consumeToken(tok::l_paren); auto LHS = parseSILCoverageExpr(Builder); if (!LHS) return None; Identifier Operator; SourceLoc Loc; if (P.parseAnyIdentifier(Operator, Loc, diag::sil_coverage_invalid_operator)) return None; if (Operator.str() != "+" && Operator.str() != "-") { P.diagnose(Loc, diag::sil_coverage_invalid_operator); return None; } auto RHS = parseSILCoverageExpr(Builder); if (!RHS) return None; if (P.parseToken(tok::r_paren, diag::sil_coverage_expected_rparen)) return None; if (Operator.str() == "+") return Builder.add(*LHS, *RHS); return Builder.subtract(*LHS, *RHS); } P.diagnose(P.Tok, diag::sil_coverage_invalid_counter); return None; } /// decl-sil-coverage-map ::= 'sil_coverage_map' CoveredName PGOFuncName CoverageHash /// decl-sil-coverage-body /// decl-sil-coverage-body: /// '{' sil-coverage-entry* '}' /// sil-coverage-entry: /// sil-coverage-loc ':' sil-coverage-expr /// sil-coverage-loc: /// StartLine ':' StartCol '->' EndLine ':' EndCol /// sil-coverage-expr: /// ... bool SILParserState::parseSILCoverageMap(Parser &P) { P.consumeToken(tok::kw_sil_coverage_map); SILParser State(P); // Parse the filename. Identifier Filename; SourceLoc FileLoc; if (State.parseSILIdentifier(Filename, FileLoc, diag::expected_sil_value_name)) return true; // Parse the covered name. if (!P.Tok.is(tok::string_literal)) { P.diagnose(P.Tok, diag::sil_coverage_expected_quote); return true; } StringRef FuncName = P.Tok.getText().drop_front().drop_back(); P.consumeToken(); // Parse the PGO func name. if (!P.Tok.is(tok::string_literal)) { P.diagnose(P.Tok, diag::sil_coverage_expected_quote); return true; } StringRef PGOFuncName = P.Tok.getText().drop_front().drop_back(); P.consumeToken(); uint64_t Hash; if (State.parseInteger(Hash, diag::sil_coverage_invalid_hash)) return true; if (!P.Tok.is(tok::l_brace)) { P.diagnose(P.Tok, diag::sil_coverage_expected_lbrace); return true; } SourceLoc LBraceLoc = P.Tok.getLoc(); P.consumeToken(tok::l_brace); llvm::coverage::CounterExpressionBuilder Builder; std::vector<SILCoverageMap::MappedRegion> Regions; bool BodyHasError = false; if (P.Tok.isNot(tok::r_brace)) { do { unsigned StartLine, StartCol, EndLine, EndCol; if (State.parseInteger(StartLine, diag::sil_coverage_expected_loc) || P.parseToken(tok::colon, diag::sil_coverage_expected_loc) || State.parseInteger(StartCol, diag::sil_coverage_expected_loc) || P.parseToken(tok::arrow, diag::sil_coverage_expected_arrow) || State.parseInteger(EndLine, diag::sil_coverage_expected_loc) || P.parseToken(tok::colon, diag::sil_coverage_expected_loc) || State.parseInteger(EndCol, diag::sil_coverage_expected_loc)) { BodyHasError = true; break; } if (P.parseToken(tok::colon, diag::sil_coverage_expected_colon)) { BodyHasError = true; break; } auto Counter = State.parseSILCoverageExpr(Builder); if (!Counter) { BodyHasError = true; break; } Regions.emplace_back(StartLine, StartCol, EndLine, EndCol, *Counter); } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof)); } if (BodyHasError) P.skipUntilDeclRBrace(); SourceLoc RBraceLoc; P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace, LBraceLoc); if (!BodyHasError) SILCoverageMap::create(M, Filename.str(), FuncName.str(), PGOFuncName.str(), Hash, Regions, Builder.getExpressions()); return false; } /// sil-scope-ref ::= 'scope' [0-9]+ /// sil-scope ::= 'sil_scope' [0-9]+ '{' /// debug-loc /// 'parent' scope-parent /// ('inlined_at' sil-scope-ref)? /// '}' /// scope-parent ::= sil-function-name ':' sil-type /// scope-parent ::= sil-scope-ref /// debug-loc ::= 'loc' string-literal ':' [0-9]+ ':' [0-9]+ bool SILParserState::parseSILScope(Parser &P) { P.consumeToken(tok::kw_sil_scope); SILParser ScopeState(P); SourceLoc SlotLoc = P.Tok.getLoc(); unsigned Slot; if (ScopeState.parseInteger(Slot, diag::sil_invalid_scope_slot)) return true; SourceLoc LBraceLoc = P.Tok.getLoc(); P.consumeToken(tok::l_brace); StringRef Key = P.Tok.getText(); RegularLocation Loc{SILLocation::DebugLoc()}; if (Key == "loc") if (ScopeState.parseSILLocation(Loc)) return true; ScopeState.parseVerbatim("parent"); Identifier FnName; SILDebugScope *Parent = nullptr; SILFunction *ParentFn = nullptr; if (P.Tok.is(tok::integer_literal)) { /// scope-parent ::= sil-scope-ref if (ScopeState.parseScopeRef(Parent)) return true; } else { /// scope-parent ::= sil-function-name SILType Ty; SourceLoc FnLoc = P.Tok.getLoc(); // We need to turn on InSILBody to parse the function reference. Lexer::SILBodyRAII Tmp(*P.L); GenericEnvironment *IgnoredEnv; Scope S(&P, ScopeKind::TopLevel); Scope Body(&P, ScopeKind::FunctionBody); if ((ScopeState.parseGlobalName(FnName)) || P.parseToken(tok::colon, diag::expected_sil_colon_value_ref) || ScopeState.parseSILType(Ty, IgnoredEnv, true)) return true; // The function doesn't exist yet. Create a zombie forward declaration. auto FnTy = Ty.getAs<SILFunctionType>(); if (!FnTy || !Ty.isObject()) { P.diagnose(FnLoc, diag::expected_sil_function_type); return true; } ParentFn = ScopeState.getGlobalNameForReference(FnName, FnTy, FnLoc, true); ScopeState.TUState.PotentialZombieFns.insert(ParentFn); } SILDebugScope *InlinedAt = nullptr; if (P.Tok.getText() == "inlined_at") { P.consumeToken(); if (ScopeState.parseScopeRef(InlinedAt)) return true; } SourceLoc RBraceLoc; P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace, LBraceLoc); auto &Scope = ScopeSlots[Slot]; if (Scope) { P.diagnose(SlotLoc, diag::sil_scope_redefined, Slot); return true; } Scope = new (M) SILDebugScope(Loc, ParentFn, Parent, InlinedAt); return false; }
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * 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 "frontend/ObjectEmitter.h" #include "mozilla/Assertions.h" // MOZ_ASSERT #include "frontend/BytecodeEmitter.h" // BytecodeEmitter #include "frontend/IfEmitter.h" // IfEmitter #include "frontend/ParseNode.h" // AccessorType #include "frontend/SharedContext.h" // SharedContext #include "gc/AllocKind.h" // AllocKind #include "js/Id.h" // jsid #include "js/Value.h" // UndefinedHandleValue #include "vm/BytecodeUtil.h" // IsHiddenInitOp #include "vm/FunctionPrefixKind.h" // FunctionPrefixKind #include "vm/JSContext.h" // JSContext #include "vm/JSObject.h" // TenuredObject #include "vm/NativeObject.h" // NativeDefineDataProperty #include "vm/Opcodes.h" // JSOp #include "vm/Runtime.h" // cx->parserNames() #include "vm/SharedStencil.h" // GCThingIndex #include "gc/ObjectKind-inl.h" // GetGCObjectKind #include "vm/JSAtom-inl.h" // AtomToId #include "vm/JSObject-inl.h" // NewBuiltinClassInstance using namespace js; using namespace js::frontend; using mozilla::Maybe; PropertyEmitter::PropertyEmitter(BytecodeEmitter* bce) : bce_(bce) {} bool PropertyEmitter::prepareForProtoValue(const Maybe<uint32_t>& keyPos) { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); // [stack] CTOR? OBJ CTOR? if (keyPos) { if (!bce_->updateSourceCoordNotes(*keyPos)) { return false; } } #ifdef DEBUG propertyState_ = PropertyState::ProtoValue; #endif return true; } bool PropertyEmitter::emitMutateProto() { MOZ_ASSERT(propertyState_ == PropertyState::ProtoValue); // [stack] OBJ PROTO if (!bce_->emit1(JSOp::MutateProto)) { // [stack] OBJ return false; } #ifdef DEBUG propertyState_ = PropertyState::Init; #endif return true; } bool PropertyEmitter::prepareForSpreadOperand( const Maybe<uint32_t>& spreadPos) { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); // [stack] OBJ if (spreadPos) { if (!bce_->updateSourceCoordNotes(*spreadPos)) { return false; } } if (!bce_->emit1(JSOp::Dup)) { // [stack] OBJ OBJ return false; } #ifdef DEBUG propertyState_ = PropertyState::SpreadOperand; #endif return true; } bool PropertyEmitter::emitSpread() { MOZ_ASSERT(propertyState_ == PropertyState::SpreadOperand); // [stack] OBJ OBJ VAL if (!bce_->emitCopyDataProperties(BytecodeEmitter::CopyOption::Unfiltered)) { // [stack] OBJ return false; } #ifdef DEBUG propertyState_ = PropertyState::Init; #endif return true; } MOZ_ALWAYS_INLINE bool PropertyEmitter::prepareForProp( const Maybe<uint32_t>& keyPos, bool isStatic, bool isIndexOrComputed) { isStatic_ = isStatic; isIndexOrComputed_ = isIndexOrComputed; // [stack] CTOR? OBJ if (keyPos) { if (!bce_->updateSourceCoordNotes(*keyPos)) { return false; } } if (isStatic_) { if (!bce_->emit1(JSOp::Dup2)) { // [stack] CTOR HOMEOBJ CTOR HOMEOBJ return false; } if (!bce_->emit1(JSOp::Pop)) { // [stack] CTOR HOMEOBJ CTOR return false; } } return true; } bool PropertyEmitter::prepareForPrivateMethod() { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); #ifdef DEBUG propertyState_ = PropertyState::PrivateMethodValue; #endif return true; } bool PropertyEmitter::prepareForPropValue(const Maybe<uint32_t>& keyPos, Kind kind /* = Kind::Prototype */) { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); // [stack] CTOR? OBJ if (!prepareForProp(keyPos, /* isStatic_ = */ kind == Kind::Static, /* isIndexOrComputed = */ false)) { // [stack] CTOR? OBJ CTOR? return false; } #ifdef DEBUG propertyState_ = PropertyState::PropValue; #endif return true; } bool PropertyEmitter::prepareForIndexPropKey( const Maybe<uint32_t>& keyPos, Kind kind /* = Kind::Prototype */) { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); // [stack] CTOR? OBJ if (!prepareForProp(keyPos, /* isStatic_ = */ kind == Kind::Static, /* isIndexOrComputed = */ true)) { // [stack] CTOR? OBJ CTOR? return false; } #ifdef DEBUG propertyState_ = PropertyState::IndexKey; #endif return true; } bool PropertyEmitter::prepareForIndexPropValue() { MOZ_ASSERT(propertyState_ == PropertyState::IndexKey); // [stack] CTOR? OBJ CTOR? KEY #ifdef DEBUG propertyState_ = PropertyState::IndexValue; #endif return true; } bool PropertyEmitter::prepareForComputedPropKey( const Maybe<uint32_t>& keyPos, Kind kind /* = Kind::Prototype */) { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); // [stack] CTOR? OBJ if (!prepareForProp(keyPos, /* isStatic_ = */ kind == Kind::Static, /* isIndexOrComputed = */ true)) { // [stack] CTOR? OBJ CTOR? return false; } #ifdef DEBUG propertyState_ = PropertyState::ComputedKey; #endif return true; } bool PropertyEmitter::prepareForComputedPropValue() { MOZ_ASSERT(propertyState_ == PropertyState::ComputedKey); // [stack] CTOR? OBJ CTOR? KEY if (!bce_->emit1(JSOp::ToPropertyKey)) { // [stack] CTOR? OBJ CTOR? KEY return false; } #ifdef DEBUG propertyState_ = PropertyState::ComputedValue; #endif return true; } bool PropertyEmitter::emitInitHomeObject() { MOZ_ASSERT(propertyState_ == PropertyState::PropValue || propertyState_ == PropertyState::PrivateMethodValue || propertyState_ == PropertyState::IndexValue || propertyState_ == PropertyState::ComputedValue); // [stack] CTOR? HOMEOBJ CTOR? KEY? FUN // There are the following values on the stack conditionally, between // HOMEOBJ and FUN: // * the 2nd CTOR if isStatic_ // * KEY if isIndexOrComputed_ // // JSOp::InitHomeObject uses one of the following: // * HOMEOBJ if !isStatic_ // (`super.foo` points the super prototype property) // * the 2nd CTOR if isStatic_ // (`super.foo` points the super constructor property) if (!bce_->emitDupAt(1 + isIndexOrComputed_)) { // [stack] # non-static method // [stack] CTOR? HOMEOBJ CTOR KEY? FUN CTOR // [stack] # static method // [stack] CTOR? HOMEOBJ KEY? FUN HOMEOBJ return false; } if (!bce_->emit1(JSOp::InitHomeObject)) { // [stack] CTOR? HOMEOBJ CTOR? KEY? FUN return false; } #ifdef DEBUG if (propertyState_ == PropertyState::PropValue) { propertyState_ = PropertyState::InitHomeObj; } else if (propertyState_ == PropertyState::PrivateMethodValue) { propertyState_ = PropertyState::InitHomeObjForPrivateMethod; } else if (propertyState_ == PropertyState::IndexValue) { propertyState_ = PropertyState::InitHomeObjForIndex; } else { propertyState_ = PropertyState::InitHomeObjForComputed; } #endif return true; } bool PropertyEmitter::emitInit(AccessorType accessorType, TaggedParserAtomIndex key) { switch (accessorType) { case AccessorType::None: return emitInit(isClass_ ? JSOp::InitHiddenProp : JSOp::InitProp, key); case AccessorType::Getter: return emitInit( isClass_ ? JSOp::InitHiddenPropGetter : JSOp::InitPropGetter, key); case AccessorType::Setter: return emitInit( isClass_ ? JSOp::InitHiddenPropSetter : JSOp::InitPropSetter, key); default: MOZ_CRASH("Invalid op"); } } bool PropertyEmitter::emitInitIndexOrComputed(AccessorType accessorType) { switch (accessorType) { case AccessorType::None: return emitInitIndexOrComputed(isClass_ ? JSOp::InitHiddenElem : JSOp::InitElem); case AccessorType::Getter: return emitInitIndexOrComputed(isClass_ ? JSOp::InitHiddenElemGetter : JSOp::InitElemGetter); case AccessorType::Setter: return emitInitIndexOrComputed(isClass_ ? JSOp::InitHiddenElemSetter : JSOp::InitElemSetter); default: MOZ_CRASH("Invalid op"); } } bool PropertyEmitter::emitInit(JSOp op, TaggedParserAtomIndex key) { MOZ_ASSERT(propertyState_ == PropertyState::PropValue || propertyState_ == PropertyState::InitHomeObj); MOZ_ASSERT(op == JSOp::InitProp || op == JSOp::InitHiddenProp || op == JSOp::InitPropGetter || op == JSOp::InitHiddenPropGetter || op == JSOp::InitPropSetter || op == JSOp::InitHiddenPropSetter); // [stack] CTOR? OBJ CTOR? VAL if (!bce_->emitAtomOp(op, key)) { // [stack] CTOR? OBJ CTOR? return false; } if (!emitPopClassConstructor()) { return false; } #ifdef DEBUG propertyState_ = PropertyState::Init; #endif return true; } bool PropertyEmitter::skipInit() { MOZ_ASSERT(propertyState_ == PropertyState::PrivateMethodValue || propertyState_ == PropertyState::InitHomeObjForPrivateMethod); #ifdef DEBUG propertyState_ = PropertyState::Init; #endif return true; } bool PropertyEmitter::emitInitIndexOrComputed(JSOp op) { MOZ_ASSERT(propertyState_ == PropertyState::IndexValue || propertyState_ == PropertyState::InitHomeObjForIndex || propertyState_ == PropertyState::ComputedValue || propertyState_ == PropertyState::InitHomeObjForComputed); MOZ_ASSERT(op == JSOp::InitElem || op == JSOp::InitHiddenElem || op == JSOp::InitElemGetter || op == JSOp::InitHiddenElemGetter || op == JSOp::InitElemSetter || op == JSOp::InitHiddenElemSetter); // [stack] CTOR? OBJ CTOR? KEY VAL if (!bce_->emit1(op)) { // [stack] CTOR? OBJ CTOR? return false; } if (!emitPopClassConstructor()) { return false; } #ifdef DEBUG propertyState_ = PropertyState::Init; #endif return true; } bool PropertyEmitter::emitPopClassConstructor() { if (isStatic_) { // [stack] CTOR HOMEOBJ CTOR if (!bce_->emit1(JSOp::Pop)) { // [stack] CTOR HOMEOBJ return false; } } return true; } ObjectEmitter::ObjectEmitter(BytecodeEmitter* bce) : PropertyEmitter(bce) {} bool ObjectEmitter::emitObject(size_t propertyCount) { MOZ_ASSERT(propertyState_ == PropertyState::Start); MOZ_ASSERT(objectState_ == ObjectState::Start); // [stack] // Emit code for {p:a, '%q':b, 2:c} that is equivalent to constructing // a new object and defining (in source order) each property on the object // (or mutating the object's [[Prototype]], in the case of __proto__). if (!bce_->emit1(JSOp::NewInit)) { // [stack] OBJ return false; } #ifdef DEBUG objectState_ = ObjectState::Object; #endif return true; } bool ObjectEmitter::emitObjectWithTemplateOnStack() { MOZ_ASSERT(propertyState_ == PropertyState::Start); MOZ_ASSERT(objectState_ == ObjectState::Start); #ifdef DEBUG objectState_ = ObjectState::Object; #endif return true; } bool ObjectEmitter::emitEnd() { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); MOZ_ASSERT(objectState_ == ObjectState::Object); // [stack] OBJ #ifdef DEBUG objectState_ = ObjectState::End; #endif return true; } AutoSaveLocalStrictMode::AutoSaveLocalStrictMode(SharedContext* sc) : sc_(sc) { savedStrictness_ = sc_->setLocalStrictMode(true); } AutoSaveLocalStrictMode::~AutoSaveLocalStrictMode() { if (sc_) { restore(); } } void AutoSaveLocalStrictMode::restore() { MOZ_ALWAYS_TRUE(sc_->setLocalStrictMode(savedStrictness_)); sc_ = nullptr; } ClassEmitter::ClassEmitter(BytecodeEmitter* bce) : PropertyEmitter(bce), strictMode_(bce->sc) { isClass_ = true; } bool ClassEmitter::emitScope(LexicalScope::ParserData* scopeBindings) { MOZ_ASSERT(propertyState_ == PropertyState::Start); MOZ_ASSERT(classState_ == ClassState::Start); tdzCache_.emplace(bce_); innerScope_.emplace(bce_); if (!innerScope_->enterLexical(bce_, ScopeKind::Lexical, scopeBindings)) { return false; } #ifdef DEBUG classState_ = ClassState::Scope; #endif return true; } bool ClassEmitter::emitBodyScope(ClassBodyScope::ParserData* scopeBindings) { MOZ_ASSERT(propertyState_ == PropertyState::Start); MOZ_ASSERT(classState_ == ClassState::Start || classState_ == ClassState::Scope); bodyTdzCache_.emplace(bce_); bodyScope_.emplace(bce_); if (!bodyScope_->enterClassBody(bce_, ScopeKind::ClassBody, scopeBindings)) { return false; } #ifdef DEBUG classState_ = ClassState::BodyScope; #endif return true; } bool ClassEmitter::emitClass(TaggedParserAtomIndex name, TaggedParserAtomIndex nameForAnonymousClass, bool hasNameOnStack) { MOZ_ASSERT(propertyState_ == PropertyState::Start); MOZ_ASSERT(classState_ == ClassState::Start || classState_ == ClassState::Scope || classState_ == ClassState::BodyScope); MOZ_ASSERT_IF(nameForAnonymousClass || hasNameOnStack, !name); MOZ_ASSERT(!(nameForAnonymousClass && hasNameOnStack)); // [stack] name_ = name; nameForAnonymousClass_ = nameForAnonymousClass; hasNameOnStack_ = hasNameOnStack; isDerived_ = false; if (!bce_->emit1(JSOp::NewInit)) { // [stack] HOMEOBJ return false; } #ifdef DEBUG classState_ = ClassState::Class; #endif return true; } bool ClassEmitter::emitDerivedClass(TaggedParserAtomIndex name, TaggedParserAtomIndex nameForAnonymousClass, bool hasNameOnStack) { MOZ_ASSERT(propertyState_ == PropertyState::Start); MOZ_ASSERT(classState_ == ClassState::Start || classState_ == ClassState::Scope || classState_ == ClassState::BodyScope); MOZ_ASSERT_IF(nameForAnonymousClass || hasNameOnStack, !name); MOZ_ASSERT(!nameForAnonymousClass || !hasNameOnStack); // [stack] HERITAGE name_ = name; nameForAnonymousClass_ = nameForAnonymousClass; hasNameOnStack_ = hasNameOnStack; isDerived_ = true; InternalIfEmitter ifThenElse(bce_); // Heritage must be null or a non-generator constructor if (!bce_->emit1(JSOp::CheckClassHeritage)) { // [stack] HERITAGE return false; } // [IF] (heritage !== null) if (!bce_->emit1(JSOp::Dup)) { // [stack] HERITAGE HERITAGE return false; } if (!bce_->emit1(JSOp::Null)) { // [stack] HERITAGE HERITAGE NULL return false; } if (!bce_->emit1(JSOp::StrictNe)) { // [stack] HERITAGE NE return false; } // [THEN] funProto = heritage, objProto = heritage.prototype if (!ifThenElse.emitThenElse()) { return false; } if (!bce_->emit1(JSOp::Dup)) { // [stack] HERITAGE HERITAGE return false; } if (!bce_->emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::prototype())) { // [stack] HERITAGE PROTO return false; } // [ELSE] funProto = %FunctionPrototype%, objProto = null if (!ifThenElse.emitElse()) { return false; } if (!bce_->emit1(JSOp::Pop)) { // [stack] return false; } if (!bce_->emitBuiltinObject(BuiltinObjectKind::FunctionPrototype)) { // [stack] PROTO return false; } if (!bce_->emit1(JSOp::Null)) { // [stack] PROTO NULL return false; } // [ENDIF] if (!ifThenElse.emitEnd()) { return false; } if (!bce_->emit1(JSOp::ObjWithProto)) { // [stack] HERITAGE HOMEOBJ return false; } if (!bce_->emit1(JSOp::Swap)) { // [stack] HOMEOBJ HERITAGE return false; } #ifdef DEBUG classState_ = ClassState::Class; #endif return true; } bool ClassEmitter::emitInitConstructor(bool needsHomeObject) { MOZ_ASSERT(propertyState_ == PropertyState::Start); MOZ_ASSERT(classState_ == ClassState::Class || classState_ == ClassState::InstanceMemberInitializersEnd); // [stack] HOMEOBJ CTOR if (needsHomeObject) { if (!bce_->emitDupAt(1)) { // [stack] HOMEOBJ CTOR HOMEOBJ return false; } if (!bce_->emit1(JSOp::InitHomeObject)) { // [stack] HOMEOBJ CTOR return false; } } if (!initProtoAndCtor()) { // [stack] CTOR HOMEOBJ return false; } #ifdef DEBUG classState_ = ClassState::InitConstructor; #endif return true; } bool ClassEmitter::initProtoAndCtor() { // [stack] NAME? HOMEOBJ CTOR if (hasNameOnStack_) { if (!bce_->emitDupAt(2)) { // [stack] NAME HOMEOBJ CTOR NAME return false; } if (!bce_->emit2(JSOp::SetFunName, uint8_t(FunctionPrefixKind::None))) { // [stack] NAME HOMEOBJ CTOR return false; } } if (!bce_->emit1(JSOp::Swap)) { // [stack] NAME? CTOR HOMEOBJ return false; } if (!bce_->emit1(JSOp::Dup2)) { // [stack] NAME? CTOR HOMEOBJ CTOR HOMEOBJ return false; } if (!bce_->emitAtomOp(JSOp::InitLockedProp, TaggedParserAtomIndex::WellKnown::prototype())) { // [stack] NAME? CTOR HOMEOBJ CTOR return false; } if (!bce_->emitAtomOp(JSOp::InitHiddenProp, TaggedParserAtomIndex::WellKnown::constructor())) { // [stack] NAME? CTOR HOMEOBJ return false; } return true; } bool ClassEmitter::prepareForMemberInitializers(size_t numInitializers, bool isStatic) { MOZ_ASSERT_IF(!isStatic, classState_ == ClassState::Class); MOZ_ASSERT_IF(isStatic, classState_ == ClassState::InitConstructor); MOZ_ASSERT(memberState_ == MemberState::Start); // .initializers is a variable that stores an array of lambdas containing // code (the initializer) for each field. Upon an object's construction, // these lambdas will be called, defining the values. auto initializers = isStatic ? TaggedParserAtomIndex::WellKnown::dotStaticInitializers() : TaggedParserAtomIndex::WellKnown::dotInitializers(); initializersAssignment_.emplace(bce_, initializers, NameOpEmitter::Kind::Initialize); if (!initializersAssignment_->prepareForRhs()) { return false; } if (!bce_->emitUint32Operand(JSOp::NewArray, numInitializers)) { // [stack] ARRAY return false; } initializerIndex_ = 0; #ifdef DEBUG if (isStatic) { classState_ = ClassState::StaticMemberInitializers; } else { classState_ = ClassState::InstanceMemberInitializers; } numInitializers_ = numInitializers; #endif return true; } bool ClassEmitter::prepareForMemberInitializer() { MOZ_ASSERT(classState_ == ClassState::InstanceMemberInitializers || classState_ == ClassState::StaticMemberInitializers); MOZ_ASSERT(memberState_ == MemberState::Start); #ifdef DEBUG memberState_ = MemberState::Initializer; #endif return true; } bool ClassEmitter::emitMemberInitializerHomeObject(bool isStatic) { MOZ_ASSERT(memberState_ == MemberState::Initializer); // [stack] OBJ HERITAGE? ARRAY METHOD // or: // [stack] CTOR HOMEOBJ ARRAY METHOD if (isStatic) { if (!bce_->emitDupAt(3)) { // [stack] CTOR HOMEOBJ ARRAY METHOD CTOR return false; } } else { if (!bce_->emitDupAt(isDerived_ ? 3 : 2)) { // [stack] OBJ HERITAGE? ARRAY METHOD OBJ return false; } } if (!bce_->emit1(JSOp::InitHomeObject)) { // [stack] OBJ HERITAGE? ARRAY METHOD // or: // [stack] CTOR HOMEOBJ ARRAY METHOD return false; } #ifdef DEBUG memberState_ = MemberState::InitializerWithHomeObject; #endif return true; } bool ClassEmitter::emitStoreMemberInitializer() { MOZ_ASSERT(memberState_ == MemberState::Initializer || memberState_ == MemberState::InitializerWithHomeObject); MOZ_ASSERT(initializerIndex_ < numInitializers_); // [stack] HOMEOBJ HERITAGE? ARRAY METHOD if (!bce_->emitUint32Operand(JSOp::InitElemArray, initializerIndex_)) { // [stack] HOMEOBJ HERITAGE? ARRAY return false; } initializerIndex_++; #ifdef DEBUG memberState_ = MemberState::Start; #endif return true; } bool ClassEmitter::emitMemberInitializersEnd() { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); MOZ_ASSERT(classState_ == ClassState::InstanceMemberInitializers || classState_ == ClassState::StaticMemberInitializers); MOZ_ASSERT(memberState_ == MemberState::Start); MOZ_ASSERT(initializerIndex_ == numInitializers_); if (!initializersAssignment_->emitAssignment()) { // [stack] HOMEOBJ HERITAGE? ARRAY return false; } initializersAssignment_.reset(); if (!bce_->emit1(JSOp::Pop)) { // [stack] HOMEOBJ HERITAGE? return false; } #ifdef DEBUG if (classState_ == ClassState::InstanceMemberInitializers) { classState_ = ClassState::InstanceMemberInitializersEnd; } else { classState_ = ClassState::StaticMemberInitializersEnd; } #endif return true; } bool ClassEmitter::emitBinding() { MOZ_ASSERT(propertyState_ == PropertyState::Start || propertyState_ == PropertyState::Init); MOZ_ASSERT(classState_ == ClassState::InitConstructor || classState_ == ClassState::InstanceMemberInitializersEnd || classState_ == ClassState::StaticMemberInitializersEnd); // [stack] CTOR HOMEOBJ if (!bce_->emit1(JSOp::Pop)) { // [stack] CTOR return false; } if (name_) { MOZ_ASSERT(innerScope_.isSome()); if (!bce_->emitLexicalInitialization(name_)) { // [stack] CTOR return false; } } // [stack] CTOR #ifdef DEBUG classState_ = ClassState::BoundName; #endif return true; } bool ClassEmitter::emitEnd(Kind kind) { MOZ_ASSERT(classState_ == ClassState::BoundName); // [stack] CTOR if (bodyScope_.isSome()) { MOZ_ASSERT(bodyTdzCache_.isSome()); if (!bodyScope_->leave(bce_)) { return false; } bodyScope_.reset(); bodyTdzCache_.reset(); } if (innerScope_.isSome()) { MOZ_ASSERT(tdzCache_.isSome()); if (!innerScope_->leave(bce_)) { return false; } innerScope_.reset(); tdzCache_.reset(); } else { MOZ_ASSERT(kind == Kind::Expression); MOZ_ASSERT(tdzCache_.isNothing()); } if (kind == Kind::Declaration) { MOZ_ASSERT(name_); if (!bce_->emitLexicalInitialization(name_)) { // [stack] CTOR return false; } // Only class statements make outer bindings, and they do not leave // themselves on the stack. if (!bce_->emit1(JSOp::Pop)) { // [stack] return false; } } // [stack] # class declaration // [stack] // [stack] # class expression // [stack] CTOR strictMode_.restore(); #ifdef DEBUG classState_ = ClassState::End; #endif return true; }
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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 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. */ /** * @file * This file implements PBKDF2 using AES-CMAC-PRF-128 */ #include "pbkdf2_cmac.h" #include <string.h> #include "common/debug.hpp" #include <mbedtls/cmac.h> #if OPENTHREAD_CONFIG_COMMISSIONER_ENABLE && OPENTHREAD_FTD void otPbkdf2Cmac(const uint8_t *aPassword, uint16_t aPasswordLen, const uint8_t *aSalt, uint16_t aSaltLen, uint32_t aIterationCounter, uint16_t aKeyLen, uint8_t * aKey) { const size_t kBlockSize = MBEDTLS_CIPHER_BLKSIZE_MAX; uint8_t prfInput[OT_PBKDF2_SALT_MAX_LEN + 4]; // Salt || INT(), for U1 calculation long prfOne[kBlockSize / sizeof(long)]; long prfTwo[kBlockSize / sizeof(long)]; long keyBlock[kBlockSize / sizeof(long)]; uint32_t blockCounter = 0; uint8_t * key = aKey; uint16_t keyLen = aKeyLen; uint16_t useLen = 0; memcpy(prfInput, aSalt, aSaltLen); OT_ASSERT(aIterationCounter % 2 == 0); aIterationCounter /= 2; while (keyLen) { ++blockCounter; prfInput[aSaltLen + 0] = static_cast<uint8_t>(blockCounter >> 24); prfInput[aSaltLen + 1] = static_cast<uint8_t>(blockCounter >> 16); prfInput[aSaltLen + 2] = static_cast<uint8_t>(blockCounter >> 8); prfInput[aSaltLen + 3] = static_cast<uint8_t>(blockCounter); // Calculate U_1 mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, prfInput, aSaltLen + 4, reinterpret_cast<uint8_t *>(keyBlock)); // Calculate U_2 mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast<const uint8_t *>(keyBlock), kBlockSize, reinterpret_cast<uint8_t *>(prfOne)); for (uint32_t j = 0; j < kBlockSize / sizeof(long); ++j) { keyBlock[j] ^= prfOne[j]; } for (uint32_t i = 1; i < aIterationCounter; ++i) { // Calculate U_{2 * i - 1} mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast<const uint8_t *>(prfOne), kBlockSize, reinterpret_cast<uint8_t *>(prfTwo)); // Calculate U_{2 * i} mbedtls_aes_cmac_prf_128(aPassword, aPasswordLen, reinterpret_cast<const uint8_t *>(prfTwo), kBlockSize, reinterpret_cast<uint8_t *>(prfOne)); for (uint32_t j = 0; j < kBlockSize / sizeof(long); ++j) { keyBlock[j] ^= prfOne[j] ^ prfTwo[j]; } } useLen = (keyLen < kBlockSize) ? keyLen : kBlockSize; memcpy(key, keyBlock, useLen); key += useLen; keyLen -= useLen; } } #endif // OPENTHREAD_CONFIG_COMMISSIONER_ENABLE && OPENTHREAD_FTD
int Solution::divide(int p, int q) { long long A = p,B = q; if(B==0) return INT_MAX; if(B==1) return A; bool sign = 0; long long int ans = 0; if(A<0) sign = (!sign); if(B<0) sign = (!sign); A = abs(A),B = abs(B); if(B>A) return 0; while(A>B){ for(long long int i=31;i>=0;i--){ if((B<<i)<=A){ ans = (ans|((long long)1<<(i))); A = (A-(B<<(i))); break; } } } if(ans>INT_MAX) return INT_MAX; if(!sign)return ans; else return 0-ans; }
/* Copyright 2015 The TensorFlow Authors. 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 "tensorflow/core/graph/graph_def_builder.h" #include "tensorflow/core/common_runtime/graph_def_builder_util.h" #include "tensorflow/core/framework/versions.pb.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/kernels/ops_util.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/version.h" namespace tensorflow { namespace { TEST(GraphDefBuilderTest, Version) { // Verify that our assertions will be nontrivial ASSERT_LT(0, TF_GRAPH_DEF_VERSION); // Newly built graphs should use the current version GraphDefBuilder builder(GraphDefBuilder::kFailImmediately); // Check version when we convert to a Graph Graph graph(OpRegistry::Global()); TF_EXPECT_OK(GraphDefBuilderToGraph(builder, &graph)); ASSERT_EQ(graph.versions().producer(), TF_GRAPH_DEF_VERSION); ASSERT_EQ(graph.versions().min_consumer(), TF_GRAPH_DEF_VERSION_MIN_CONSUMER); // Check version when we convert to a GraphDef GraphDef graph_def; TF_EXPECT_OK(builder.ToGraphDef(&graph_def)); ASSERT_EQ(graph_def.versions().producer(), TF_GRAPH_DEF_VERSION); ASSERT_EQ(graph_def.versions().min_consumer(), TF_GRAPH_DEF_VERSION_MIN_CONSUMER); } } // namespace } // namespace tensorflow
#include "ShimClient.h" #include "trace.h" #include <iostream> #include <Arduino.h> #include <ctime> extern "C" { uint32_t millis(void) { return time(0)*1000; } } ShimClient::ShimClient() { this->responseBuffer = new Buffer(); this->expectBuffer = new Buffer(); this->_allowConnect = true; this->_connected = false; this->_error = false; this->expectAnything = true; this->_received = 0; this->_expectedPort = 0; } int ShimClient::connect(IPAddress ip, uint16_t port) { if (this->_allowConnect) { this->_connected = true; } if (this->_expectedPort !=0) { // if (memcmp(ip,this->_expectedIP,4) != 0) { // TRACE( "ip mismatch\n"); // this->_error = true; // } if (port != this->_expectedPort) { TRACE( "port mismatch\n"); this->_error = true; } } return this->_connected; } int ShimClient::connect(const char *host, uint16_t port) { if (this->_allowConnect) { this->_connected = true; } if (this->_expectedPort !=0) { if (strcmp(host,this->_expectedHost) != 0) { TRACE( "host mismatch\n"); this->_error = true; } if (port != this->_expectedPort) { TRACE( "port mismatch\n"); this->_error = true; } } return this->_connected; } size_t ShimClient::write(uint8_t b) { this->_received += 1; TRACE(std::hex << (unsigned int)b); if (!this->expectAnything) { if (this->expectBuffer->available()) { uint8_t expected = this->expectBuffer->next(); if (expected != b) { this->_error = true; TRACE("!=" << (unsigned int)expected); } } else { this->_error = true; } } TRACE("\n"<< std::dec); return 1; } size_t ShimClient::write(const uint8_t *buf, size_t size) { this->_received += size; TRACE( "[" << std::dec << (unsigned int)(size) << "] "); uint16_t i=0; for (;i<size;i++) { if (i>0) { TRACE(":"); } TRACE(std::hex << (unsigned int)(buf[i])); if (!this->expectAnything) { if (this->expectBuffer->available()) { uint8_t expected = this->expectBuffer->next(); if (expected != buf[i]) { this->_error = true; TRACE("!=" << (unsigned int)expected); } } else { this->_error = true; } } } TRACE("\n"<<std::dec); return size; } int ShimClient::available() { return this->responseBuffer->available(); } int ShimClient::read() { return this->responseBuffer->next(); } int ShimClient::read(uint8_t *buf, size_t size) { uint16_t i = 0; for (;i<size;i++) { buf[i] = this->read(); } return size; } int ShimClient::peek() { return 0; } void ShimClient::flush() {} void ShimClient::stop() { this->setConnected(false); } uint8_t ShimClient::connected() { return this->_connected; } ShimClient::operator bool() { return true; } ShimClient* ShimClient::respond(uint8_t *buf, size_t size) { this->responseBuffer->add(buf,size); return this; } ShimClient* ShimClient::expect(uint8_t *buf, size_t size) { this->expectAnything = false; this->expectBuffer->add(buf,size); return this; } void ShimClient::setConnected(bool b) { this->_connected = b; } void ShimClient::setAllowConnect(bool b) { this->_allowConnect = b; } bool ShimClient::error() { return this->_error; } uint16_t ShimClient::received() { return this->_received; } void ShimClient::expectConnect(IPAddress ip, uint16_t port) { this->_expectedIP = ip; this->_expectedPort = port; } void ShimClient::expectConnect(const char *host, uint16_t port) { this->_expectedHost = host; this->_expectedPort = port; }
//===----------------------------------------------------------------------===// // // PelotonDB // // workload.cpp // // Identification: benchmark/tpcc/workload.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <unordered_map> #include <vector> #include <chrono> #include <iostream> #include <ctime> #include <cassert> #include <thread> #include <algorithm> #include <random> #include <cstddef> #include <limits> #include "backend/benchmark/tpcc/tpcc_workload.h" #include "backend/benchmark/tpcc/tpcc_configuration.h" #include "backend/benchmark/tpcc/tpcc_loader.h" #include "backend/catalog/manager.h" #include "backend/catalog/schema.h" #include "backend/common/types.h" #include "backend/common/value.h" #include "backend/common/value_factory.h" #include "backend/common/logger.h" #include "backend/common/timer.h" #include "backend/common/generator.h" #include "backend/concurrency/transaction.h" #include "backend/concurrency/transaction_manager_factory.h" #include "backend/executor/executor_context.h" #include "backend/executor/abstract_executor.h" #include "backend/executor/logical_tile.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/materialization_executor.h" #include "backend/executor/update_executor.h" #include "backend/executor/index_scan_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/constant_value_expression.h" #include "backend/expression/tuple_value_expression.h" #include "backend/expression/comparison_expression.h" #include "backend/expression/expression_util.h" #include "backend/expression/container_tuple.h" #include "backend/index/index_factory.h" #include "backend/logging/log_manager.h" #include "backend/planner/abstract_plan.h" #include "backend/planner/materialization_plan.h" #include "backend/planner/insert_plan.h" #include "backend/planner/update_plan.h" #include "backend/planner/index_scan_plan.h" #include "backend/storage/data_table.h" #include "backend/storage/table_factory.h" namespace peloton { namespace benchmark { namespace tpcc { ///////////////////////////////////////////////////////// // TRANSACTION TYPES ///////////////////////////////////////////////////////// bool RunStockLevel(); bool RunDelivery(); bool RunOrderStatus(); bool RunPayment(); bool RunNewOrder(); ///////////////////////////////////////////////////////// // WORKLOAD ///////////////////////////////////////////////////////// volatile bool is_running = true; oid_t *abort_counts; oid_t *commit_counts; void RunBackend(oid_t thread_id) { UniformGenerator generator; oid_t &execution_count_ref = abort_counts[thread_id]; oid_t &transaction_count_ref = commit_counts[thread_id]; // Run these many transactions while (true) { if (is_running == false) { break; } auto rng_val = generator.GetSample(); if (rng_val <= 0.04) { while (RunStockLevel() == false) { execution_count_ref++; } } else if (rng_val <= 0.08) { while (RunDelivery() == false) { execution_count_ref++; } } else if (rng_val <= 0.12) { while (RunOrderStatus() == false) { execution_count_ref++; } } else if (rng_val <= 0.55) { while (RunPayment() == false) { execution_count_ref++; } } else { while (RunNewOrder() == false) { execution_count_ref++; } } transaction_count_ref++; } } void RunWorkload() { // Execute the workload to build the log std::vector<std::thread> thread_group; oid_t num_threads = state.backend_count; abort_counts = new oid_t[num_threads]; memset(abort_counts, 0, sizeof(oid_t) * num_threads); commit_counts = new oid_t[num_threads]; memset(commit_counts, 0, sizeof(oid_t) * num_threads); size_t snapshot_round = (size_t)(state.duration / state.snapshot_duration); oid_t **abort_counts_snapshots = new oid_t *[snapshot_round]; for (size_t round_id = 0; round_id < snapshot_round; ++round_id) { abort_counts_snapshots[round_id] = new oid_t[num_threads]; } oid_t **commit_counts_snapshots = new oid_t *[snapshot_round]; for (size_t round_id = 0; round_id < snapshot_round; ++round_id) { commit_counts_snapshots[round_id] = new oid_t[num_threads]; } // Launch a group of threads for (oid_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group.push_back(std::move(std::thread(RunBackend, thread_itr))); } for (size_t round_id = 0; round_id < snapshot_round; ++round_id) { std::this_thread::sleep_for( std::chrono::milliseconds(int(state.snapshot_duration * 1000))); memcpy(abort_counts_snapshots[round_id], abort_counts, sizeof(oid_t) * num_threads); memcpy(commit_counts_snapshots[round_id], commit_counts, sizeof(oid_t) * num_threads); } is_running = false; // Join the threads with the main thread for (oid_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group[thread_itr].join(); } // calculate the throughput and abort rate for the first round. oid_t total_commit_count = 0; for (size_t i = 0; i < num_threads; ++i) { total_commit_count += commit_counts_snapshots[0][i]; } oid_t total_abort_count = 0; for (size_t i = 0; i < num_threads; ++i) { total_abort_count += abort_counts_snapshots[0][i]; } state.snapshot_throughput .push_back(total_commit_count * 1.0 / state.snapshot_duration); state.snapshot_abort_rate .push_back(total_abort_count * 1.0 / total_commit_count); // calculate the throughput and abort rate for the remaining rounds. for (size_t round_id = 0; round_id < snapshot_round - 1; ++round_id) { total_commit_count = 0; for (size_t i = 0; i < num_threads; ++i) { total_commit_count += commit_counts_snapshots[round_id + 1][i] - commit_counts_snapshots[round_id][i]; } total_abort_count = 0; for (size_t i = 0; i < num_threads; ++i) { total_abort_count += abort_counts_snapshots[round_id + 1][i] - abort_counts_snapshots[round_id][i]; } state.snapshot_throughput .push_back(total_commit_count * 1.0 / state.snapshot_duration); state.snapshot_abort_rate .push_back(total_abort_count * 1.0 / total_commit_count); } // calculate the aggregated throughput and abort rate. total_commit_count = 0; for (size_t i = 0; i < num_threads; ++i) { total_commit_count += commit_counts_snapshots[snapshot_round - 1][i]; } total_abort_count = 0; for (size_t i = 0; i < num_threads; ++i) { total_abort_count += abort_counts_snapshots[snapshot_round - 1][i]; } state.throughput = total_commit_count * 1.0 / state.duration; state.abort_rate = total_abort_count * 1.0 / total_commit_count; // cleanup everything. for (size_t round_id = 0; round_id < snapshot_round; ++round_id) { delete[] abort_counts_snapshots[round_id]; abort_counts_snapshots[round_id] = nullptr; } for (size_t round_id = 0; round_id < snapshot_round; ++round_id) { delete[] commit_counts_snapshots[round_id]; commit_counts_snapshots[round_id] = nullptr; } delete[] abort_counts_snapshots; abort_counts_snapshots = nullptr; delete[] commit_counts_snapshots; commit_counts_snapshots = nullptr; delete[] abort_counts; abort_counts = nullptr; delete[] commit_counts; commit_counts = nullptr; } ///////////////////////////////////////////////////////// // TABLES ///////////////////////////////////////////////////////// /* CREATE TABLE WAREHOUSE ( 0 W_ID SMALLINT DEFAULT '0' NOT NULL, 1 W_NAME VARCHAR(16) DEFAULT NULL, 2 W_STREET_1 VARCHAR(32) DEFAULT NULL, 3 W_STREET_2 VARCHAR(32) DEFAULT NULL, 4 W_CITY VARCHAR(32) DEFAULT NULL, 5 W_STATE VARCHAR(2) DEFAULT NULL, 6 W_ZIP VARCHAR(9) DEFAULT NULL, 7 W_TAX FLOAT DEFAULT NULL, 8 W_YTD FLOAT DEFAULT NULL, CONSTRAINT W_PK_ARRAY PRIMARY KEY (W_ID) ); INDEXES: 0 W_ID */ /* CREATE TABLE DISTRICT ( 0 D_ID TINYINT DEFAULT '0' NOT NULL, 1 D_W_ID SMALLINT DEFAULT '0' NOT NULL REFERENCES WAREHOUSE (W_ID), 2 D_NAME VARCHAR(16) DEFAULT NULL, 3 D_STREET_1 VARCHAR(32) DEFAULT NULL, 4 D_STREET_2 VARCHAR(32) DEFAULT NULL, 5 D_CITY VARCHAR(32) DEFAULT NULL, 6 D_STATE VARCHAR(2) DEFAULT NULL, 7 D_ZIP VARCHAR(9) DEFAULT NULL, 8 D_TAX FLOAT DEFAULT NULL, 9 D_YTD FLOAT DEFAULT NULL, 10 D_NEXT_O_ID INT DEFAULT NULL, PRIMARY KEY (D_W_ID,D_ID) ); INDEXES: 0, 1 D_ID, D_W_ID */ /* CREATE TABLE ITEM ( 0 I_ID INTEGER DEFAULT '0' NOT NULL, 1 I_IM_ID INTEGER DEFAULT NULL, 2 I_NAME VARCHAR(32) DEFAULT NULL, 3 I_PRICE FLOAT DEFAULT NULL, 4 I_DATA VARCHAR(64) DEFAULT NULL, CONSTRAINT I_PK_ARRAY PRIMARY KEY (I_ID) ); INDEXES: 0 I_ID */ /* CREATE TABLE CUSTOMER ( 0 C_ID INTEGER DEFAULT '0' NOT NULL, 1 C_D_ID TINYINT DEFAULT '0' NOT NULL, 2 C_W_ID SMALLINT DEFAULT '0' NOT NULL, 3 C_FIRST VARCHAR(32) DEFAULT NULL, 4 C_MIDDLE VARCHAR(2) DEFAULT NULL, 5 C_LAST VARCHAR(32) DEFAULT NULL, 6 C_STREET_1 VARCHAR(32) DEFAULT NULL, 7 C_STREET_2 VARCHAR(32) DEFAULT NULL, 8 C_CITY VARCHAR(32) DEFAULT NULL, 9 C_STATE VARCHAR(2) DEFAULT NULL, 10 C_ZIP VARCHAR(9) DEFAULT NULL, 11 C_PHONE VARCHAR(32) DEFAULT NULL, 12 C_SINCE TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 13 C_CREDIT VARCHAR(2) DEFAULT NULL, 14 C_CREDIT_LIM FLOAT DEFAULT NULL, 15 C_DISCOUNT FLOAT DEFAULT NULL, 16 C_BALANCE FLOAT DEFAULT NULL, 17 C_YTD_PAYMENT FLOAT DEFAULT NULL, 18 C_PAYMENT_CNT INTEGER DEFAULT NULL, 19 C_DELIVERY_CNT INTEGER DEFAULT NULL, 20 C_DATA VARCHAR(500), PRIMARY KEY (C_W_ID,C_D_ID,C_ID), UNIQUE (C_W_ID,C_D_ID,C_LAST,C_FIRST), CONSTRAINT C_FKEY_D FOREIGN KEY (C_D_ID, C_W_ID) REFERENCES DISTRICT (D_ID, D_W_ID) ); CREATE INDEX IDX_CUSTOMER ON CUSTOMER (C_W_ID,C_D_ID,C_LAST); INDEXES: 0, 1, 2 C_ID, C_W_ID, C_D_ID 1, 2, 5 C_W_ID, C_D_ID, C_LAST */ /* CREATE TABLE HISTORY ( 0 H_C_ID INTEGER DEFAULT NULL, 1 H_C_D_ID TINYINT DEFAULT NULL, 2 H_C_W_ID SMALLINT DEFAULT NULL, 3 H_D_ID TINYINT DEFAULT NULL, 4 H_W_ID SMALLINT DEFAULT '0' NOT NULL, 5 H_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 6 H_AMOUNT FLOAT DEFAULT NULL, 7 H_DATA VARCHAR(32) DEFAULT NULL, CONSTRAINT H_FKEY_C FOREIGN KEY (H_C_ID, H_C_D_ID, H_C_W_ID) REFERENCES CUSTOMER (C_ID, C_D_ID, C_W_ID), CONSTRAINT H_FKEY_D FOREIGN KEY (H_D_ID, H_W_ID) REFERENCES DISTRICT (D_ID, D_W_ID) ); */ /* CREATE TABLE STOCK ( 0 S_I_ID INTEGER DEFAULT '0' NOT NULL REFERENCES ITEM (I_ID), 1 S_W_ID SMALLINT DEFAULT '0 ' NOT NULL REFERENCES WAREHOUSE (W_ID), 2 S_QUANTITY INTEGER DEFAULT '0' NOT NULL, 3 S_DIST_01 VARCHAR(32) DEFAULT NULL, 4 S_DIST_02 VARCHAR(32) DEFAULT NULL, 5 S_DIST_03 VARCHAR(32) DEFAULT NULL, 6 S_DIST_04 VARCHAR(32) DEFAULT NULL, 7 S_DIST_05 VARCHAR(32) DEFAULT NULL, 8 S_DIST_06 VARCHAR(32) DEFAULT NULL, 9 S_DIST_07 VARCHAR(32) DEFAULT NULL, 10 S_DIST_08 VARCHAR(32) DEFAULT NULL, 11 S_DIST_09 VARCHAR(32) DEFAULT NULL, 12 S_DIST_10 VARCHAR(32) DEFAULT NULL, 13 S_YTD INTEGER DEFAULT NULL, 14 S_ORDER_CNT INTEGER DEFAULT NULL, 15 S_REMOTE_CNT INTEGER DEFAULT NULL, 16 S_DATA VARCHAR(64) DEFAULT NULL, PRIMARY KEY (S_W_ID,S_I_ID) ); INDEXES: 0, 1 S_I_ID, S_W_ID */ /* CREATE TABLE ORDERS ( 0 O_ID INTEGER DEFAULT '0' NOT NULL, 1 O_C_ID INTEGER DEFAULT NULL, 2 O_D_ID TINYINT DEFAULT '0' NOT NULL, 3 O_W_ID SMALLINT DEFAULT '0' NOT NULL, 4 O_ENTRY_D TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, 5 O_CARRIER_ID INTEGER DEFAULT NULL, 6 O_OL_CNT INTEGER DEFAULT NULL, 7 O_ALL_LOCAL INTEGER DEFAULT NULL, PRIMARY KEY (O_W_ID,O_D_ID,O_ID), UNIQUE (O_W_ID,O_D_ID,O_C_ID,O_ID), CONSTRAINT O_FKEY_C FOREIGN KEY (O_C_ID, O_D_ID, O_W_ID) REFERENCES CUSTOMER (C_ID, C_D_ID, C_W_ID) ); CREATE INDEX IDX_ORDERS ON ORDERS (O_W_ID,O_D_ID,O_C_ID); INDEXES: 0, 2, 3 O_ID, O_D_ID, O_W_ID 1, 2, 3 O_C_ID, O_D_ID, O_W_ID */ /* CREATE TABLE NEW_ORDER ( 0 NO_O_ID INTEGER DEFAULT '0' NOT NULL, 1 NO_D_ID TINYINT DEFAULT '0' NOT NULL, 2 NO_W_ID SMALLINT DEFAULT '0' NOT NULL, CONSTRAINT NO_PK_TREE PRIMARY KEY (NO_D_ID,NO_W_ID,NO_O_ID), CONSTRAINT NO_FKEY_O FOREIGN KEY (NO_O_ID, NO_D_ID, NO_W_ID) REFERENCES ORDERS (O_ID, O_D_ID, O_W_ID) ); INDEXES: 0, 1, 2 NO_O_ID, NO_D_ID, NO_W_ID */ /* CREATE TABLE ORDER_LINE ( 0 OL_O_ID INTEGER DEFAULT '0' NOT NULL, 1 OL_D_ID TINYINT DEFAULT '0' NOT NULL, 2 OL_W_ID SMALLINT DEFAULT '0' NOT NULL, 3 OL_NUMBER INTEGER DEFAULT '0' NOT NULL, 4 OL_I_ID INTEGER DEFAULT NULL, 5 OL_SUPPLY_W_ID SMALLINT DEFAULT NULL, 6 OL_DELIVERY_D TIMESTAMP DEFAULT NULL, 7 OL_QUANTITY INTEGER DEFAULT NULL, 8 OL_AMOUNT FLOAT DEFAULT NULL, 9 OL_DIST_INFO VARCHAR(32) DEFAULT NULL, PRIMARY KEY (OL_W_ID,OL_D_ID,OL_O_ID,OL_NUMBER), CONSTRAINT OL_FKEY_O FOREIGN KEY (OL_O_ID, OL_D_ID, OL_W_ID) REFERENCES ORDERS (O_ID, O_D_ID, O_W_ID), CONSTRAINT OL_FKEY_S FOREIGN KEY (OL_I_ID, OL_SUPPLY_W_ID) REFERENCES STOCK (S_I_ID, S_W_ID) ); CREATE INDEX IDX_ORDER_LINE_TREE ON ORDER_LINE (OL_W_ID,OL_D_ID,OL_O_ID); INDEXES: 0, 1, 2, 3 OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER 0, 1, 2 OL_O_ID, OL_D_ID, OL_W_ID */ ///////////////////////////////////////////////////////// // TRANSACTIONS ///////////////////////////////////////////////////////// std::vector<std::vector<Value>> ExecuteTest(executor::AbstractExecutor* executor) { bool status = false; // Run all the executors status = executor->Init(); if (status == false) { throw Exception("Init failed"); } std::vector<std::vector<Value>> logical_tile_values; // Execute stuff while (executor->Execute() == true) { std::unique_ptr<executor::LogicalTile> result_tile( executor->GetOutput()); if(result_tile == nullptr) break; auto column_count = result_tile->GetColumnCount(); for (oid_t tuple_id : *result_tile) { expression::ContainerTuple<executor::LogicalTile> cur_tuple(result_tile.get(), tuple_id); std::vector<Value> tuple_values; for (oid_t column_itr = 0; column_itr < column_count; column_itr++){ auto value = cur_tuple.GetValue(column_itr); tuple_values.push_back(value); } // Move the tuple list logical_tile_values.push_back(std::move(tuple_values)); } } return std::move(logical_tile_values); } bool RunNewOrder(){ /* "NEW_ORDER": { "getWarehouseTaxRate": "SELECT W_TAX FROM WAREHOUSE WHERE W_ID = ?", # w_id "getDistrict": "SELECT D_TAX, D_NEXT_O_ID FROM DISTRICT WHERE D_ID = ? AND D_W_ID = ?", # d_id, w_id "getCustomer": "SELECT C_DISCOUNT, C_LAST, C_CREDIT FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # w_id, d_id, c_id "incrementNextOrderId": "UPDATE DISTRICT SET D_NEXT_O_ID = ? WHERE D_ID = ? AND D_W_ID = ?", # d_next_o_id, d_id, w_id "createOrder": "INSERT INTO ORDERS (O_ID, O_D_ID, O_W_ID, O_C_ID, O_ENTRY_D, O_CARRIER_ID, O_OL_CNT, O_ALL_LOCAL) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", # d_next_o_id, d_id, w_id, c_id, o_entry_d, o_carrier_id, o_ol_cnt, o_all_local "createNewOrder": "INSERT INTO NEW_ORDER (NO_O_ID, NO_D_ID, NO_W_ID) VALUES (?, ?, ?)", # o_id, d_id, w_id "getItemInfo": "SELECT I_PRICE, I_NAME, I_DATA FROM ITEM WHERE I_ID = ?", # ol_i_id "getStockInfo": "SELECT S_QUANTITY, S_DATA, S_YTD, S_ORDER_CNT, S_REMOTE_CNT, S_DIST_%02d FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", # d_id, ol_i_id, ol_supply_w_id "updateStock": "UPDATE STOCK SET S_QUANTITY = ?, S_YTD = ?, S_ORDER_CNT = ?, S_REMOTE_CNT = ? WHERE S_I_ID = ? AND S_W_ID = ?", # s_quantity, s_order_cnt, s_remote_cnt, ol_i_id, ol_supply_w_id "createOrderLine": "INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID, OL_DELIVERY_D, OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", # o_id, d_id, w_id, ol_number, ol_i_id, ol_supply_w_id, ol_quantity, ol_amount, ol_dist_info } */ LOG_INFO("-------------------------------------"); int warehouse_id = GetRandomInteger(0, state.warehouse_count - 1); int district_id = GetRandomInteger(0, state.districts_per_warehouse - 1); //int customer_id = GetRandomInteger(0, state.customers_per_district); int o_ol_cnt = GetRandomInteger(orders_min_ol_cnt, orders_max_ol_cnt); //auto o_entry_ts = GetTimeStamp(); std::vector<int> i_ids, i_w_ids, i_qtys; //bool o_all_local = true; for (auto ol_itr = 0; ol_itr < o_ol_cnt; ol_itr++) { i_ids.push_back(GetRandomInteger(0, state.item_count)); bool remote = GetRandomBoolean(new_order_remote_txns); i_w_ids.push_back(warehouse_id); if(remote == true) { i_w_ids[ol_itr] = GetRandomIntegerExcluding(0, state.warehouse_count - 1, warehouse_id); //o_all_local = false; } i_qtys.push_back(GetRandomInteger(0, order_line_max_ol_quantity)); } auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<VarlenPool> pool(new VarlenPool(BACKEND_TYPE_MM)); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // getWarehouseTaxRate std::vector<oid_t> warehouse_column_ids = {7}; // W_TAX // Create and set up index scan executor std::vector<oid_t> warehouse_key_column_ids = {0}; // W_ID std::vector<ExpressionType> warehouse_expr_types; std::vector<Value> warehouse_key_values; std::vector<expression::AbstractExpression *> runtime_keys; warehouse_expr_types.push_back( ExpressionType::EXPRESSION_TYPE_COMPARE_EQUAL); warehouse_key_values.push_back(ValueFactory::GetIntegerValue(warehouse_id)); auto warehouse_pkey_index = warehouse_table->GetIndexWithOid( warehouse_table_pkey_index_oid); planner::IndexScanPlan::IndexScanDesc warehouse_index_scan_desc( warehouse_pkey_index, warehouse_key_column_ids, warehouse_expr_types, warehouse_key_values, runtime_keys); // Create plan node. auto predicate = nullptr; planner::IndexScanPlan warehouse_index_scan_node(warehouse_table, predicate, warehouse_column_ids, warehouse_index_scan_desc); executor::IndexScanExecutor warehouse_index_scan_executor(&warehouse_index_scan_node, context.get()); auto gwtr_lists_values = ExecuteTest(&warehouse_index_scan_executor); if(gwtr_lists_values.empty() == true) { LOG_ERROR("getWarehouseTaxRate failed"); txn_manager.AbortTransaction(); return false; } auto w_tax = gwtr_lists_values[0][0]; LOG_TRACE("W_TAX: %s", w_tax.GetInfo().c_str()); // getDistrict std::vector<oid_t> district_column_ids = {8, 10}; // D_TAX, D_NEXT_O_ID // Create and set up index scan executor std::vector<oid_t> district_key_column_ids = {0, 1}; // D_ID, D_W_ID std::vector<ExpressionType> district_expr_types; std::vector<Value> district_key_values; district_expr_types.push_back( ExpressionType::EXPRESSION_TYPE_COMPARE_EQUAL); district_expr_types.push_back( ExpressionType::EXPRESSION_TYPE_COMPARE_EQUAL); district_key_values.push_back(ValueFactory::GetIntegerValue(district_id)); district_key_values.push_back(ValueFactory::GetIntegerValue(warehouse_id)); auto district_pkey_index = district_table->GetIndexWithOid( district_table_pkey_index_oid); planner::IndexScanPlan::IndexScanDesc district_index_scan_desc( district_pkey_index, district_key_column_ids, district_expr_types, district_key_values, runtime_keys); // Create plan node. planner::IndexScanPlan district_index_scan_node(district_table, predicate, district_column_ids, district_index_scan_desc); executor::IndexScanExecutor district_index_scan_executor(&district_index_scan_node, context.get()); auto gd_lists_values = ExecuteTest(&district_index_scan_executor); if(gd_lists_values.empty() == true) { LOG_ERROR("getDistrict failed"); txn_manager.AbortTransaction(); return false; } auto result = txn->GetResult(); auto d_tax = gd_lists_values[0][0]; LOG_TRACE("D_TAX: %s", d_tax.GetInfo().c_str()); auto d_next_o_id = gd_lists_values[0][1]; LOG_TRACE("D_NEXT_O_ID: %s", d_next_o_id.GetInfo().c_str()); // transaction passed execution. if (result == Result::RESULT_SUCCESS) { result = txn_manager.CommitTransaction(); auto d_tax = gd_lists_values[0][0]; // LOG_TRACE("D_TAX: %d", d_tax); auto d_next_o_id = gd_lists_values[0][1]; // LOG_TRACE("D_NEXT_O_ID: %d", d_next_o_id); return true; } // transaction aborted during execution. else { assert(result == Result::RESULT_ABORTED || result == Result::RESULT_FAILURE); result = txn_manager.AbortTransaction(); return false; } } bool RunPayment(){ /* "PAYMENT": { "getWarehouse": "SELECT W_NAME, W_STREET_1, W_STREET_2, W_CITY, W_STATE, W_ZIP FROM WAREHOUSE WHERE W_ID = ?", # w_id "updateWarehouseBalance": "UPDATE WAREHOUSE SET W_YTD = W_YTD + ? WHERE W_ID = ?", # h_amount, w_id "getDistrict": "SELECT D_NAME, D_STREET_1, D_STREET_2, D_CITY, D_STATE, D_ZIP FROM DISTRICT WHERE D_W_ID = ? AND D_ID = ?", # w_id, d_id "updateDistrictBalance": "UPDATE DISTRICT SET D_YTD = D_YTD + ? WHERE D_W_ID = ? AND D_ID = ?", # h_amount, d_w_id, d_id "getCustomerByCustomerId": "SELECT C_ID, C_FIRST, C_MIDDLE, C_LAST, C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, C_PHONE, C_SINCE, C_CREDIT, C_CREDIT_LIM, C_DISCOUNT, C_BALANCE, C_YTD_PAYMENT, C_PAYMENT_CNT, C_DATA FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # w_id, d_id, c_id "getCustomersByLastName": "SELECT C_ID, C_FIRST, C_MIDDLE, C_LAST, C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, C_PHONE, C_SINCE, C_CREDIT, C_CREDIT_LIM, C_DISCOUNT, C_BALANCE, C_YTD_PAYMENT, C_PAYMENT_CNT, C_DATA FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_LAST = ? ORDER BY C_FIRST", # w_id, d_id, c_last "updateBCCustomer": "UPDATE CUSTOMER SET C_BALANCE = ?, C_YTD_PAYMENT = ?, C_PAYMENT_CNT = ?, C_DATA = ? WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # c_balance, c_ytd_payment, c_payment_cnt, c_data, c_w_id, c_d_id, c_id "updateGCCustomer": "UPDATE CUSTOMER SET C_BALANCE = ?, C_YTD_PAYMENT = ?, C_PAYMENT_CNT = ? WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # c_balance, c_ytd_payment, c_payment_cnt, c_w_id, c_d_id, c_id "insertHistory": "INSERT INTO HISTORY VALUES (?, ?, ?, ?, ?, ?, ?, ?)", } */ LOG_INFO("-------------------------------------"); //int warehouse_id = GetRandomInteger(0, state.warehouse_count - 1); //int district_id = GetRandomInteger(0, state.districts_per_warehouse - 1); return true; } bool RunOrderStatus(){ /* "ORDER_STATUS": { "getCustomerByCustomerId": "SELECT C_ID, C_FIRST, C_MIDDLE, C_LAST, C_BALANCE FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # w_id, d_id, c_id "getCustomersByLastName": "SELECT C_ID, C_FIRST, C_MIDDLE, C_LAST, C_BALANCE FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_LAST = ? ORDER BY C_FIRST", # w_id, d_id, c_last "getLastOrder": "SELECT O_ID, O_CARRIER_ID, O_ENTRY_D FROM ORDERS WHERE O_W_ID = ? AND O_D_ID = ? AND O_C_ID = ? ORDER BY O_ID DESC LIMIT 1", # w_id, d_id, c_id "getOrderLines": "SELECT OL_SUPPLY_W_ID, OL_I_ID, OL_QUANTITY, OL_AMOUNT, OL_DELIVERY_D FROM ORDER_LINE WHERE OL_W_ID = ? AND OL_D_ID = ? AND OL_O_ID = ?", # w_id, d_id, o_id } */ return true; } bool RunDelivery(){ /* "DELIVERY": { "getNewOrder": "SELECT NO_O_ID FROM NEW_ORDER WHERE NO_D_ID = ? AND NO_W_ID = ? AND NO_O_ID > -1 LIMIT 1", # "deleteNewOrder": "DELETE FROM NEW_ORDER WHERE NO_D_ID = ? AND NO_W_ID = ? AND NO_O_ID = ?", # d_id, w_id, no_o_id "getCId": "SELECT O_C_ID FROM ORDERS WHERE O_ID = ? AND O_D_ID = ? AND O_W_ID = ?", # no_o_id, d_id, w_id "updateOrders": "UPDATE ORDERS SET O_CARRIER_ID = ? WHERE O_ID = ? AND O_D_ID = ? AND O_W_ID = ?", # o_carrier_id, no_o_id, d_id, w_id "updateOrderLine": "UPDATE ORDER_LINE SET OL_DELIVERY_D = ? WHERE OL_O_ID = ? AND OL_D_ID = ? AND OL_W_ID = ?", # o_entry_d, no_o_id, d_id, w_id "sumOLAmount": "SELECT SUM(OL_AMOUNT) FROM ORDER_LINE WHERE OL_O_ID = ? AND OL_D_ID = ? AND OL_W_ID = ?", # no_o_id, d_id, w_id "updateCustomer": "UPDATE CUSTOMER SET C_BALANCE = C_BALANCE + ? WHERE C_ID = ? AND C_D_ID = ? AND C_W_ID = ?", # ol_total, c_id, d_id, w_id } */ return true; } bool RunStockLevel() { /* "STOCK_LEVEL": { "getOId": "SELECT D_NEXT_O_ID FROM DISTRICT WHERE D_W_ID = ? AND D_ID = ?", "getStockCount": "SELECT COUNT(DISTINCT(OL_I_ID)) FROM ORDER_LINE, STOCK WHERE OL_W_ID = ? AND OL_D_ID = ? AND OL_O_ID < ? AND OL_O_ID >= ? AND S_W_ID = ? AND S_I_ID = OL_I_ID AND S_QUANTITY < ? } */ return true; } } // namespace tpcc } // namespace benchmark } // namespace peloton
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <forward_list> // ~forward_list() // implied noexcept; // UNSUPPORTED: c++98, c++03 #include <forward_list> #include <cassert> #include "test_macros.h" #include "MoveOnly.h" #include "test_allocator.h" template <class T> struct some_alloc { typedef T value_type; some_alloc(const some_alloc&); ~some_alloc() noexcept(false); }; int main() { { typedef std::forward_list<MoveOnly> C; static_assert(std::is_nothrow_destructible<C>::value, ""); } { typedef std::forward_list<MoveOnly, test_allocator<MoveOnly>> C; static_assert(std::is_nothrow_destructible<C>::value, ""); } { typedef std::forward_list<MoveOnly, other_allocator<MoveOnly>> C; static_assert(std::is_nothrow_destructible<C>::value, ""); } { typedef std::forward_list<MoveOnly, some_alloc<MoveOnly>> C; LIBCPP_STATIC_ASSERT(!std::is_nothrow_destructible<C>::value, ""); } }
// RUN: %check_clang_tidy %s android-cloexec-dup %t extern "C" int dup(int oldfd); void f() { dup(1); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: prefer fcntl() to dup() because fcntl() allows F_DUPFD_CLOEXEC [android-cloexec-dup] // CHECK-FIXES: fcntl(1, F_DUPFD_CLOEXEC); int oldfd = 0; dup(oldfd); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: prefer // CHECK-FIXES: fcntl(oldfd, F_DUPFD_CLOEXEC); } namespace i { int dup(int oldfd); void g() { dup(0); int oldfd = 1; dup(oldfd); } } // namespace i class C { public: int dup(int oldfd); void h() { dup(0); int oldfd = 1; dup(oldfd); } };
/** * @author SANKALP SAXENA */ #include <iostream> #include <cstdio> using namespace std; /* Add `int max_of_four(int a, int b, int c, int d)` here. */ int max_of_four(int a, int b, int c, int d) { int max; if((a > b) && (a > c) && (a > d)) max = a; else if((b > a) && (b > c) && (b > d)) max = b; else if((c > b) && (c > a) && (c > d)) max = c; else max = d; return max; } int main() { int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); int ans = max_of_four(a, b, c, d); printf("%d", ans); return 0; }
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "dll_log.hpp" #include "d3d12_device.hpp" #include "d3d12_command_list.hpp" #include "d3d12_command_queue.hpp" #include "d3d12_command_queue_downlevel.hpp" #include <malloc.h> D3D12CommandQueue::D3D12CommandQueue(D3D12Device *device, ID3D12CommandQueue *original) : command_queue_impl(device, original), _device(device) { assert(_orig != nullptr && _device != nullptr); // Explicitly add a reference to the device, to ensure it stays valid for the lifetime of this queue object _device->AddRef(); } bool D3D12CommandQueue::check_and_upgrade_interface(REFIID riid) { if (riid == __uuidof(this) || riid == __uuidof(IUnknown) || // This is the IID_IUnknown identity object riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) || riid == __uuidof(ID3D12Pageable)) return true; static const IID iid_lookup[] = { __uuidof(ID3D12CommandQueue), }; for (unsigned int version = 0; version < ARRAYSIZE(iid_lookup); ++version) { if (riid != iid_lookup[version]) continue; if (version > _interface_version) { IUnknown *new_interface = nullptr; if (FAILED(_orig->QueryInterface(riid, reinterpret_cast<void **>(&new_interface)))) return false; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Upgraded ID3D12CommandQueue" << _interface_version << " object " << this << " to ID3D12CommandQueue" << version << '.'; #endif _orig->Release(); _orig = static_cast<ID3D12CommandQueue *>(new_interface); _interface_version = version; } return true; } return false; } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::QueryInterface(REFIID riid, void **ppvObj) { if (ppvObj == nullptr) return E_POINTER; if (check_and_upgrade_interface(riid)) { AddRef(); *ppvObj = this; return S_OK; } // Special case for d3d12on7 if (riid == __uuidof(ID3D12CommandQueueDownlevel)) { if (ID3D12CommandQueueDownlevel *downlevel = nullptr; // Not a 'com_ptr' since D3D12CommandQueueDownlevel will take ownership _downlevel == nullptr && SUCCEEDED(_orig->QueryInterface(&downlevel))) _downlevel = new D3D12CommandQueueDownlevel(this, downlevel); if (_downlevel != nullptr) return _downlevel->QueryInterface(riid, ppvObj); } return _orig->QueryInterface(riid, ppvObj); } ULONG STDMETHODCALLTYPE D3D12CommandQueue::AddRef() { _orig->AddRef(); return InterlockedIncrement(&_ref); } ULONG STDMETHODCALLTYPE D3D12CommandQueue::Release() { const ULONG ref = InterlockedDecrement(&_ref); if (ref != 0) return _orig->Release(), ref; if (_downlevel != nullptr) { // Release the reference that was added when the downlevel interface was first queried in 'QueryInterface' above _downlevel->_orig->Release(); delete _downlevel; } const auto orig = _orig; const auto device = _device; const auto interface_version = _interface_version; #if RESHADE_VERBOSE_LOG LOG(DEBUG) << "Destroying " << "ID3D12CommandQueue" << interface_version << " object " << this << " (" << orig << ")."; #endif delete this; const ULONG ref_orig = orig->Release(); if (ref_orig != 0) // Verify internal reference count LOG(WARN) << "Reference count for " << "ID3D12CommandQueue" << interface_version << " object " << this << " (" << orig << ") is inconsistent (" << ref_orig << ")."; // Release the explicit reference to the device that was added in the D3D12CommandQueue constructor above now that the queue implementation was destroyed and is no longer referencing it device->Release(); return 0; } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::GetPrivateData(REFGUID guid, UINT *pDataSize, void *pData) { return _orig->GetPrivateData(guid, pDataSize, pData); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::SetPrivateData(REFGUID guid, UINT DataSize, const void *pData) { return _orig->SetPrivateData(guid, DataSize, pData); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::SetPrivateDataInterface(REFGUID guid, const IUnknown *pData) { return _orig->SetPrivateDataInterface(guid, pData); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::SetName(LPCWSTR Name) { return _orig->SetName(Name); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::GetDevice(REFIID riid, void **ppvDevice) { return _device->QueryInterface(riid, ppvDevice); } void STDMETHODCALLTYPE D3D12CommandQueue::UpdateTileMappings(ID3D12Resource *pResource, UINT NumResourceRegions, const D3D12_TILED_RESOURCE_COORDINATE *pResourceRegionStartCoordinates, const D3D12_TILE_REGION_SIZE *pResourceRegionSizes, ID3D12Heap *pHeap, UINT NumRanges, const D3D12_TILE_RANGE_FLAGS *pRangeFlags, const UINT *pHeapRangeStartOffsets, const UINT *pRangeTileCounts, D3D12_TILE_MAPPING_FLAGS Flags) { _orig->UpdateTileMappings(pResource, NumResourceRegions, pResourceRegionStartCoordinates, pResourceRegionSizes, pHeap, NumRanges, pRangeFlags, pHeapRangeStartOffsets, pRangeTileCounts, Flags); } void STDMETHODCALLTYPE D3D12CommandQueue::CopyTileMappings(ID3D12Resource *pDstResource, const D3D12_TILED_RESOURCE_COORDINATE *pDstRegionStartCoordinate, ID3D12Resource *pSrcResource, const D3D12_TILED_RESOURCE_COORDINATE *pSrcRegionStartCoordinate, const D3D12_TILE_REGION_SIZE *pRegionSize, D3D12_TILE_MAPPING_FLAGS Flags) { _orig->CopyTileMappings(pDstResource, pDstRegionStartCoordinate, pSrcResource, pSrcRegionStartCoordinate, pRegionSize, Flags); } void STDMETHODCALLTYPE D3D12CommandQueue::ExecuteCommandLists(UINT NumCommandLists, ID3D12CommandList *const *ppCommandLists) { const auto command_lists = static_cast<ID3D12CommandList **>(_malloca(NumCommandLists * sizeof(ID3D12CommandList *))); for (UINT i = 0; i < NumCommandLists; i++) { assert(ppCommandLists[i] != nullptr); if (com_ptr<D3D12GraphicsCommandList> command_list_proxy; SUCCEEDED(ppCommandLists[i]->QueryInterface(&command_list_proxy))) { #if RESHADE_ADDON reshade::invoke_addon_event<reshade::addon_event::execute_command_list>(this, command_list_proxy.get()); #endif // Get original command list pointer from proxy object command_lists[i] = command_list_proxy->_orig; } else { // This can be a compute command list too, which have no proxy object command_lists[i] = ppCommandLists[i]; } } flush_immediate_command_list(); _orig->ExecuteCommandLists(NumCommandLists, command_lists); _freea(command_lists); } void STDMETHODCALLTYPE D3D12CommandQueue::SetMarker(UINT Metadata, const void *pData, UINT Size) { _orig->SetMarker(Metadata, pData, Size); } void STDMETHODCALLTYPE D3D12CommandQueue::BeginEvent(UINT Metadata, const void *pData, UINT Size) { _orig->BeginEvent(Metadata, pData, Size); } void STDMETHODCALLTYPE D3D12CommandQueue::EndEvent() { _orig->EndEvent(); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::Signal(ID3D12Fence *pFence, UINT64 Value) { return _orig->Signal(pFence, Value); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::Wait(ID3D12Fence *pFence, UINT64 Value) { return _orig->Wait(pFence, Value); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::GetTimestampFrequency(UINT64 *pFrequency) { return _orig->GetTimestampFrequency(pFrequency); } HRESULT STDMETHODCALLTYPE D3D12CommandQueue::GetClockCalibration(UINT64 *pGpuTimestamp, UINT64 *pCpuTimestamp) { return _orig->GetClockCalibration(pGpuTimestamp, pCpuTimestamp); } D3D12_COMMAND_QUEUE_DESC STDMETHODCALLTYPE D3D12CommandQueue::GetDesc() { return _orig->GetDesc(); }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/json/json_writer.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" #include "base/test/mock_log.h" #include "base/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/policy/core/common/fake_async_policy_loader.h" #include "policy/policy_constants.h" #include "remoting/host/dns_blackhole_checker.h" #include "remoting/host/policy_watcher.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace remoting { namespace key = ::policy::key; MATCHER_P(IsPolicies, dict, "") { bool equal = arg->Equals(dict); if (!equal) { std::string actual_value; base::JSONWriter::WriteWithOptions( *arg, base::JSONWriter::OPTIONS_PRETTY_PRINT, &actual_value); std::string expected_value; base::JSONWriter::WriteWithOptions( *dict, base::JSONWriter::OPTIONS_PRETTY_PRINT, &expected_value); *result_listener << "Policies are not equal. "; *result_listener << "Expected policy: " << expected_value << ". "; *result_listener << "Actual policy: " << actual_value << "."; } return equal; } class MockPolicyCallback { public: MockPolicyCallback(){}; // TODO(lukasza): gmock cannot mock a method taking scoped_ptr<T>... MOCK_METHOD1(OnPolicyUpdatePtr, void(const base::DictionaryValue* policies)); void OnPolicyUpdate(scoped_ptr<base::DictionaryValue> policies) { OnPolicyUpdatePtr(policies.get()); } MOCK_METHOD0(OnPolicyError, void()); private: DISALLOW_COPY_AND_ASSIGN(MockPolicyCallback); }; class PolicyWatcherTest : public testing::Test { public: PolicyWatcherTest() : message_loop_(base::MessageLoop::TYPE_IO) {} void SetUp() override { // We expect no callbacks unless explicitly specified by individual tests. EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(testing::_)).Times(0); EXPECT_CALL(mock_policy_callback_, OnPolicyError()).Times(0); // Retaining a raw pointer to keep control over policy contents. policy_loader_ = new policy::FakeAsyncPolicyLoader(base::ThreadTaskRunnerHandle::Get()); policy_watcher_ = PolicyWatcher::CreateFromPolicyLoader(make_scoped_ptr(policy_loader_)); nat_true_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, true); nat_false_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, false); nat_one_.SetInteger(key::kRemoteAccessHostFirewallTraversal, 1); nat_one_domain_full_.SetInteger(key::kRemoteAccessHostFirewallTraversal, 1); nat_one_domain_full_.SetString(key::kRemoteAccessHostDomain, kHostDomain); domain_empty_.SetString(key::kRemoteAccessHostDomain, std::string()); domain_full_.SetString(key::kRemoteAccessHostDomain, kHostDomain); SetDefaults(nat_true_others_default_); nat_true_others_default_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, true); SetDefaults(nat_false_others_default_); nat_false_others_default_.SetBoolean( key::kRemoteAccessHostFirewallTraversal, false); SetDefaults(domain_empty_others_default_); domain_empty_others_default_.SetString(key::kRemoteAccessHostDomain, std::string()); SetDefaults(domain_full_others_default_); domain_full_others_default_.SetString(key::kRemoteAccessHostDomain, kHostDomain); nat_true_domain_empty_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, true); nat_true_domain_empty_.SetString(key::kRemoteAccessHostDomain, std::string()); nat_true_domain_full_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, true); nat_true_domain_full_.SetString(key::kRemoteAccessHostDomain, kHostDomain); nat_false_domain_empty_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, false); nat_false_domain_empty_.SetString(key::kRemoteAccessHostDomain, std::string()); nat_false_domain_full_.SetBoolean(key::kRemoteAccessHostFirewallTraversal, false); nat_false_domain_full_.SetString(key::kRemoteAccessHostDomain, kHostDomain); SetDefaults(nat_true_domain_empty_others_default_); nat_true_domain_empty_others_default_.SetBoolean( key::kRemoteAccessHostFirewallTraversal, true); nat_true_domain_empty_others_default_.SetString( key::kRemoteAccessHostDomain, std::string()); unknown_policies_.SetString("UnknownPolicyOne", std::string()); unknown_policies_.SetString("UnknownPolicyTwo", std::string()); unknown_policies_.SetBoolean("RemoteAccessHostUnknownPolicyThree", true); pairing_true_.SetBoolean(key::kRemoteAccessHostAllowClientPairing, true); pairing_false_.SetBoolean(key::kRemoteAccessHostAllowClientPairing, false); gnubby_auth_true_.SetBoolean(key::kRemoteAccessHostAllowGnubbyAuth, true); gnubby_auth_false_.SetBoolean(key::kRemoteAccessHostAllowGnubbyAuth, false); relay_true_.SetBoolean(key::kRemoteAccessHostAllowRelayedConnection, true); relay_false_.SetBoolean(key::kRemoteAccessHostAllowRelayedConnection, false); port_range_full_.SetString(key::kRemoteAccessHostUdpPortRange, kPortRange); port_range_empty_.SetString(key::kRemoteAccessHostUdpPortRange, std::string()); port_range_malformed_.SetString(key::kRemoteAccessHostUdpPortRange, "malformed"); port_range_malformed_domain_full_.MergeDictionary(&port_range_malformed_); port_range_malformed_domain_full_.SetString(key::kRemoteAccessHostDomain, kHostDomain); curtain_true_.SetBoolean(key::kRemoteAccessHostRequireCurtain, true); curtain_false_.SetBoolean(key::kRemoteAccessHostRequireCurtain, false); username_true_.SetBoolean(key::kRemoteAccessHostMatchUsername, true); username_false_.SetBoolean(key::kRemoteAccessHostMatchUsername, false); talk_gadget_blah_.SetString(key::kRemoteAccessHostTalkGadgetPrefix, "blah"); third_party_auth_partial_.SetString(key::kRemoteAccessHostTokenUrl, "https://token.com"); third_party_auth_partial_.SetString( key::kRemoteAccessHostTokenValidationUrl, "https://validation.com"); third_party_auth_full_.MergeDictionary(&third_party_auth_partial_); third_party_auth_full_.SetString( key::kRemoteAccessHostTokenValidationCertificateIssuer, "certificate subject"); third_party_auth_cert_empty_.MergeDictionary(&third_party_auth_partial_); third_party_auth_cert_empty_.SetString( key::kRemoteAccessHostTokenValidationCertificateIssuer, ""); } void TearDown() override { policy_watcher_.reset(); policy_loader_ = nullptr; base::RunLoop().RunUntilIdle(); } protected: void StartWatching() { policy_watcher_->StartWatching( base::Bind(&MockPolicyCallback::OnPolicyUpdate, base::Unretained(&mock_policy_callback_)), base::Bind(&MockPolicyCallback::OnPolicyError, base::Unretained(&mock_policy_callback_))); base::RunLoop().RunUntilIdle(); } void SetPolicies(const base::DictionaryValue& dict) { // Copy |dict| into |policy_bundle|. policy::PolicyNamespace policy_namespace = policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()); policy::PolicyBundle policy_bundle; policy::PolicyMap& policy_map = policy_bundle.Get(policy_namespace); policy_map.LoadFrom(&dict, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD); // Simulate a policy file/registry/preference update. policy_loader_->SetPolicies(policy_bundle); policy_loader_->PostReloadOnBackgroundThread(true /* force reload asap */); base::RunLoop().RunUntilIdle(); } const policy::Schema* GetPolicySchema() { return policy_watcher_->GetPolicySchema(); } const base::DictionaryValue& GetDefaultValues() { return *(policy_watcher_->default_values_); } MOCK_METHOD0(PostPolicyWatcherShutdown, void()); static const char* kHostDomain; static const char* kPortRange; base::MessageLoop message_loop_; MockPolicyCallback mock_policy_callback_; // |policy_loader_| is owned by |policy_watcher_|. PolicyWatcherTest retains // a raw pointer to |policy_loader_| in order to control the simulated / faked // policy contents. policy::FakeAsyncPolicyLoader* policy_loader_; scoped_ptr<PolicyWatcher> policy_watcher_; base::DictionaryValue empty_; base::DictionaryValue nat_true_; base::DictionaryValue nat_false_; base::DictionaryValue nat_one_; base::DictionaryValue nat_one_domain_full_; base::DictionaryValue domain_empty_; base::DictionaryValue domain_full_; base::DictionaryValue nat_true_others_default_; base::DictionaryValue nat_false_others_default_; base::DictionaryValue domain_empty_others_default_; base::DictionaryValue domain_full_others_default_; base::DictionaryValue nat_true_domain_empty_; base::DictionaryValue nat_true_domain_full_; base::DictionaryValue nat_false_domain_empty_; base::DictionaryValue nat_false_domain_full_; base::DictionaryValue nat_true_domain_empty_others_default_; base::DictionaryValue unknown_policies_; base::DictionaryValue pairing_true_; base::DictionaryValue pairing_false_; base::DictionaryValue gnubby_auth_true_; base::DictionaryValue gnubby_auth_false_; base::DictionaryValue relay_true_; base::DictionaryValue relay_false_; base::DictionaryValue port_range_full_; base::DictionaryValue port_range_empty_; base::DictionaryValue port_range_malformed_; base::DictionaryValue port_range_malformed_domain_full_; base::DictionaryValue curtain_true_; base::DictionaryValue curtain_false_; base::DictionaryValue username_true_; base::DictionaryValue username_false_; base::DictionaryValue talk_gadget_blah_; base::DictionaryValue third_party_auth_full_; base::DictionaryValue third_party_auth_partial_; base::DictionaryValue third_party_auth_cert_empty_; private: void SetDefaults(base::DictionaryValue& dict) { dict.SetBoolean(key::kRemoteAccessHostFirewallTraversal, true); dict.SetBoolean(key::kRemoteAccessHostAllowRelayedConnection, true); dict.SetString(key::kRemoteAccessHostUdpPortRange, ""); dict.SetString(key::kRemoteAccessHostDomain, std::string()); dict.SetBoolean(key::kRemoteAccessHostMatchUsername, false); dict.SetString(key::kRemoteAccessHostTalkGadgetPrefix, kDefaultHostTalkGadgetPrefix); dict.SetBoolean(key::kRemoteAccessHostRequireCurtain, false); dict.SetString(key::kRemoteAccessHostTokenUrl, ""); dict.SetString(key::kRemoteAccessHostTokenValidationUrl, ""); dict.SetString(key::kRemoteAccessHostTokenValidationCertificateIssuer, ""); dict.SetBoolean(key::kRemoteAccessHostAllowClientPairing, true); dict.SetBoolean(key::kRemoteAccessHostAllowGnubbyAuth, true); ASSERT_THAT(&dict, IsPolicies(&GetDefaultValues())) << "Sanity check that defaults expected by the test code " << "match what is stored in PolicyWatcher::default_values_"; } }; const char* PolicyWatcherTest::kHostDomain = "google.com"; const char* PolicyWatcherTest::kPortRange = "12400-12409"; TEST_F(PolicyWatcherTest, None) { EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); SetPolicies(empty_); StartWatching(); } TEST_F(PolicyWatcherTest, NatTrue) { EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); SetPolicies(nat_true_); StartWatching(); } TEST_F(PolicyWatcherTest, NatFalse) { EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_false_others_default_))); SetPolicies(nat_false_); StartWatching(); } TEST_F(PolicyWatcherTest, NatWrongType) { EXPECT_CALL(mock_policy_callback_, OnPolicyError()); SetPolicies(nat_one_); StartWatching(); } // This test verifies that a mistyped policy value is still detected // even though it doesn't change during the second SetPolicies call. TEST_F(PolicyWatcherTest, NatWrongTypeThenIrrelevantChange) { EXPECT_CALL(mock_policy_callback_, OnPolicyError()).Times(2); SetPolicies(nat_one_); StartWatching(); SetPolicies(nat_one_domain_full_); } // This test verifies that a malformed policy value is still detected // even though it doesn't change during the second SetPolicies call. TEST_F(PolicyWatcherTest, PortRangeMalformedThenIrrelevantChange) { EXPECT_CALL(mock_policy_callback_, OnPolicyError()).Times(2); SetPolicies(port_range_malformed_); StartWatching(); SetPolicies(port_range_malformed_domain_full_); } TEST_F(PolicyWatcherTest, DomainEmpty) { EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&domain_empty_others_default_))); SetPolicies(domain_empty_); StartWatching(); } TEST_F(PolicyWatcherTest, DomainFull) { EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&domain_full_others_default_))); SetPolicies(domain_full_); StartWatching(); } TEST_F(PolicyWatcherTest, NatNoneThenTrue) { EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); SetPolicies(empty_); StartWatching(); SetPolicies(nat_true_); } TEST_F(PolicyWatcherTest, NatNoneThenTrueThenTrue) { EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); SetPolicies(empty_); StartWatching(); SetPolicies(nat_true_); SetPolicies(nat_true_); } TEST_F(PolicyWatcherTest, NatNoneThenTrueThenTrueThenFalse) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_false_))); SetPolicies(empty_); StartWatching(); SetPolicies(nat_true_); SetPolicies(nat_true_); SetPolicies(nat_false_); } TEST_F(PolicyWatcherTest, NatNoneThenFalse) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_false_))); SetPolicies(empty_); StartWatching(); SetPolicies(nat_false_); } TEST_F(PolicyWatcherTest, NatNoneThenFalseThenTrue) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_false_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_))); SetPolicies(empty_); StartWatching(); SetPolicies(nat_false_); SetPolicies(nat_true_); } TEST_F(PolicyWatcherTest, ChangeOneRepeatedlyThenTwo) { testing::InSequence sequence; EXPECT_CALL( mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_domain_empty_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&domain_full_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_false_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&domain_empty_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_domain_full_))); SetPolicies(nat_true_domain_empty_); StartWatching(); SetPolicies(nat_true_domain_full_); SetPolicies(nat_false_domain_full_); SetPolicies(nat_false_domain_empty_); SetPolicies(nat_true_domain_full_); } TEST_F(PolicyWatcherTest, FilterUnknownPolicies) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); SetPolicies(empty_); StartWatching(); SetPolicies(unknown_policies_); SetPolicies(empty_); } class MisspelledPolicyTest : public PolicyWatcherTest, public ::testing::WithParamInterface<const char*> { }; // Verify that a misspelled policy causes a warning written to the log. TEST_P(MisspelledPolicyTest, WarningLogged) { const char* misspelled_policy_name = GetParam(); base::test::MockLog mock_log; ON_CALL(mock_log, Log(testing::_, testing::_, testing::_, testing::_, testing::_)).WillByDefault(testing::Return(true)); EXPECT_CALL(mock_log, Log(logging::LOG_WARNING, testing::_, testing::_, testing::_, testing::HasSubstr(misspelled_policy_name))).Times(1); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); base::DictionaryValue misspelled_policies; misspelled_policies.SetString(misspelled_policy_name, "some test value"); mock_log.StartCapturingLogs(); SetPolicies(misspelled_policies); StartWatching(); mock_log.StopCapturingLogs(); } INSTANTIATE_TEST_CASE_P( PolicyWatcherTest, MisspelledPolicyTest, ::testing::Values("RemoteAccessHostDomainX", "XRemoteAccessHostDomain", "RemoteAccessHostdomain", "RemoteAccessHostPolicyForFutureVersion")); TEST_F(PolicyWatcherTest, PairingFalseThenTrue) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&pairing_false_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&pairing_true_))); SetPolicies(empty_); StartWatching(); SetPolicies(pairing_false_); SetPolicies(pairing_true_); } TEST_F(PolicyWatcherTest, GnubbyAuth) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&gnubby_auth_false_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&gnubby_auth_true_))); SetPolicies(empty_); StartWatching(); SetPolicies(gnubby_auth_false_); SetPolicies(gnubby_auth_true_); } TEST_F(PolicyWatcherTest, Relay) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&relay_false_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&relay_true_))); SetPolicies(empty_); StartWatching(); SetPolicies(relay_false_); SetPolicies(relay_true_); } TEST_F(PolicyWatcherTest, Curtain) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&curtain_true_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&curtain_false_))); SetPolicies(empty_); StartWatching(); SetPolicies(curtain_true_); SetPolicies(curtain_false_); } TEST_F(PolicyWatcherTest, MatchUsername) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); #if !defined(OS_WIN) EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&username_true_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&username_false_))); #else // On Windows the MatchUsername policy is ignored and therefore the 2 // SetPolicies calls won't result in any calls to OnPolicyUpdate. #endif SetPolicies(empty_); StartWatching(); SetPolicies(username_true_); SetPolicies(username_false_); } TEST_F(PolicyWatcherTest, TalkGadgetPrefix) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&talk_gadget_blah_))); SetPolicies(empty_); StartWatching(); SetPolicies(talk_gadget_blah_); } TEST_F(PolicyWatcherTest, ThirdPartyAuthFull) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&third_party_auth_full_))); SetPolicies(empty_); StartWatching(); SetPolicies(third_party_auth_full_); } // This test verifies what happens when only 1 out of 3 third-party auth // policies changes. Without the other 2 policy values such policy values // combination is invalid (i.e. cannot have TokenUrl without // TokenValidationUrl) and can trigger OnPolicyError unless PolicyWatcher // implementation is careful around this scenario. TEST_F(PolicyWatcherTest, ThirdPartyAuthPartialToFull) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&third_party_auth_cert_empty_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&third_party_auth_full_))); SetPolicies(empty_); StartWatching(); SetPolicies(third_party_auth_partial_); SetPolicies(third_party_auth_full_); } TEST_F(PolicyWatcherTest, UdpPortRange) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&nat_true_others_default_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&port_range_full_))); EXPECT_CALL(mock_policy_callback_, OnPolicyUpdatePtr(IsPolicies(&port_range_empty_))); SetPolicies(empty_); StartWatching(); SetPolicies(port_range_full_); SetPolicies(port_range_empty_); } TEST_F(PolicyWatcherTest, PolicySchemaAndPolicyWatcherShouldBeInSync) { // This test verifies that // 1) policy schema (generated out of policy_templates.json) // and // 2) PolicyWatcher's code (i.e. contents of the |default_values_| field) // are kept in-sync. std::map<std::string, base::Value::Type> expected_schema; for (base::DictionaryValue::Iterator i(GetDefaultValues()); !i.IsAtEnd(); i.Advance()) { expected_schema[i.key()] = i.value().GetType(); } #if defined(OS_WIN) // RemoteAccessHostMatchUsername is marked in policy_templates.json as not // supported on Windows and therefore is (by design) excluded from the schema. expected_schema.erase(key::kRemoteAccessHostMatchUsername); #endif std::map<std::string, base::Value::Type> actual_schema; const policy::Schema* schema = GetPolicySchema(); ASSERT_TRUE(schema->valid()); for (auto it = schema->GetPropertiesIterator(); !it.IsAtEnd(); it.Advance()) { std::string key = it.key(); if (key.find("RemoteAccessHost") == std::string::npos) { // For now PolicyWatcher::GetPolicySchema() mixes Chrome and Chromoting // policies, so we have to skip them here. continue; } actual_schema[key] = it.schema().type(); } EXPECT_THAT(actual_schema, testing::ContainerEq(expected_schema)); } TEST_F(PolicyWatcherTest, SchemaTypeCheck) { const policy::Schema* schema = GetPolicySchema(); ASSERT_TRUE(schema->valid()); // Check one, random "string" policy to see if the type propagated correctly // from policy_templates.json file. const policy::Schema string_schema = schema->GetKnownProperty("RemoteAccessHostDomain"); EXPECT_TRUE(string_schema.valid()); EXPECT_EQ(string_schema.type(), base::Value::Type::TYPE_STRING); // And check one, random "boolean" policy to see if the type propagated // correctly from policy_templates.json file. const policy::Schema boolean_schema = schema->GetKnownProperty("RemoteAccessHostRequireCurtain"); EXPECT_TRUE(boolean_schema.valid()); EXPECT_EQ(boolean_schema.type(), base::Value::Type::TYPE_BOOLEAN); } // Unit tests cannot instantiate PolicyWatcher on ChromeOS // (as this requires running inside a browser process). #ifndef OS_CHROMEOS namespace { void OnPolicyUpdatedDumpPolicy(scoped_ptr<base::DictionaryValue> policies) { VLOG(1) << "OnPolicyUpdated callback received the following policies:"; for (base::DictionaryValue::Iterator iter(*policies); !iter.IsAtEnd(); iter.Advance()) { switch (iter.value().GetType()) { case base::Value::Type::TYPE_STRING: { std::string value; CHECK(iter.value().GetAsString(&value)); VLOG(1) << iter.key() << " = " << "string: " << '"' << value << '"'; break; } case base::Value::Type::TYPE_BOOLEAN: { bool value; CHECK(iter.value().GetAsBoolean(&value)); VLOG(1) << iter.key() << " = " << "boolean: " << (value ? "True" : "False"); break; } default: { VLOG(1) << iter.key() << " = " << "unrecognized type"; break; } } } } } // anonymous namespace // To dump policy contents, run unit tests with the following flags: // out/Debug/remoting_unittests --gtest_filter=*TestRealChromotingPolicy* -v=1 #if defined(ADDRESS_SANITIZER) // http://crbug.com/517918 #define MAYBE_TestRealChromotingPolicy DISABLED_TestRealChromotingPolicy #else #define MAYBE_TestRealChromotingPolicy TestRealChromotingPolicy #endif TEST_F(PolicyWatcherTest, MAYBE_TestRealChromotingPolicy) { scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::MessageLoop::current()->task_runner(); scoped_ptr<PolicyWatcher> policy_watcher( PolicyWatcher::Create(nullptr, task_runner)); { base::RunLoop run_loop; policy_watcher->StartWatching(base::Bind(OnPolicyUpdatedDumpPolicy), base::Bind(base::DoNothing)); run_loop.RunUntilIdle(); } // Today, the only verification offered by this test is: // - Manual verification of policy values dumped by OnPolicyUpdatedDumpPolicy // - Automated verification that nothing crashed } #endif } // namespace remoting
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef SFML_GLRESOURCE_HPP #define SFML_GLRESOURCE_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Window/Export.hpp> #include <SFML/System/NonCopyable.hpp> namespace sf { class Context; typedef void(*ContextDestroyCallback)(void*); //////////////////////////////////////////////////////////// /// \brief Base class for classes that require an OpenGL context /// //////////////////////////////////////////////////////////// class SFML_WINDOW_API GlResource { protected: //////////////////////////////////////////////////////////// /// \brief Default constructor /// //////////////////////////////////////////////////////////// GlResource(); //////////////////////////////////////////////////////////// /// \brief Destructor /// //////////////////////////////////////////////////////////// ~GlResource(); //////////////////////////////////////////////////////////// /// \brief Register a function to be called when a context is destroyed /// /// This is used for internal purposes in order to properly /// clean up OpenGL resources that cannot be shared between /// contexts. /// /// \param callback Function to be called when a context is destroyed /// \param arg Argument to pass when calling the function /// //////////////////////////////////////////////////////////// static void registerContextDestroyCallback(ContextDestroyCallback callback, void* arg); //////////////////////////////////////////////////////////// /// \brief RAII helper class to temporarily lock an available context for use /// //////////////////////////////////////////////////////////// class SFML_WINDOW_API TransientContextLock : NonCopyable { public: //////////////////////////////////////////////////////////// /// \brief Default constructor /// //////////////////////////////////////////////////////////// TransientContextLock(); //////////////////////////////////////////////////////////// /// \brief Destructor /// //////////////////////////////////////////////////////////// ~TransientContextLock(); }; }; } // namespace sf #endif // SFML_GLRESOURCE_HPP //////////////////////////////////////////////////////////// /// \class sf::GlResource /// \ingroup window /// /// This class is for internal use only, it must be the base /// of every class that requires a valid OpenGL context in /// order to work. /// ////////////////////////////////////////////////////////////
/* Copyright 2021-2022 NVIDIA Corporation * * 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 "cunumeric/binary/binary_red.h" #include "cunumeric/binary/binary_red_template.inl" namespace cunumeric { using namespace Legion; using namespace legate; template <BinaryOpCode OP_CODE, LegateTypeCode CODE, int DIM> struct BinaryRedImplBody<VariantKind::OMP, OP_CODE, CODE, DIM> { using OP = BinaryOp<OP_CODE, CODE>; using ARG = legate_type_of<CODE>; template <typename AccessorRD> void operator()(OP func, AccessorRD out, AccessorRO<ARG, DIM> in1, AccessorRO<ARG, DIM> in2, const Pitches<DIM - 1>& pitches, const Rect<DIM>& rect, bool dense) const { size_t volume = rect.volume(); bool result = true; if (dense) { auto in1ptr = in1.ptr(rect); auto in2ptr = in2.ptr(rect); #pragma omp parallel for schedule(static) for (size_t idx = 0; idx < volume; ++idx) if (!func(in1ptr[idx], in2ptr[idx])) result = false; } else { #pragma omp parallel for schedule(static) for (size_t idx = 0; idx < volume; ++idx) { auto point = pitches.unflatten(idx, rect.lo); if (!func(in1[point], in2[point])) result = false; } } out.reduce(0, result); } }; /*static*/ void BinaryRedTask::omp_variant(TaskContext& context) { binary_red_template<VariantKind::OMP>(context); } } // namespace cunumeric
// Copyright (c) 2009-2014 The Straks Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/straks-config.h" #endif #include <cstddef> #if defined(HAVE_SYS_SELECT_H) #include <sys/select.h> #endif // Prior to GLIBC_2.14, memcpy was aliased to memmove. extern "C" void* memmove(void* a, const void* b, size_t c); extern "C" void* memcpy(void* a, const void* b, size_t c) { return memmove(a, b, c); } extern "C" void __chk_fail(void) __attribute__((__noreturn__)); extern "C" FDELT_TYPE __fdelt_warn(FDELT_TYPE a) { if (a >= FD_SETSIZE) __chk_fail(); return a / __NFDBITS; } extern "C" FDELT_TYPE __fdelt_chk(FDELT_TYPE) __attribute__((weak, alias("__fdelt_warn")));
/** * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #include <graphlab/rpc/dc_dist_object.hpp> #ifndef GRAPHLAB_DC_SERVICES_HPP #define GRAPHLAB_DC_SERVICES_HPP #include <graphlab/parallel/pthread_tools.hpp> #include <graphlab/macros_def.hpp> namespace graphlab { /** \ingroup rpc Creates a new context for MPI-like global global operations. Where all machines create an instance of dc_services at the same time, operations performed by the new dc_services instance will not interfere and will run in parallel with other contexts. i.e. If I have two distributed dc_services instances, one instance can perform a barrier while another instance performs a broadcast() at the same time. \note Only simple algorithms for the MPI collective operations (barrier, broadcast, etc) are implemented. Significant work is necessary to improve the performance of the collectives. */ class dc_services { private: dc_dist_object<dc_services> rmi; public: dc_services(distributed_control &dc):rmi(dc, this) { } /// Returns the underlying dc_dist_object dc_dist_object<dc_services>& rmi_instance() { return rmi; } /// Returns the underlying dc_dist_object const dc_dist_object<dc_services>& rmi_instance() const { return rmi; } /** This comm barrier is not a true "barrier" but is essentially a sequentialization point. It guarantees that all calls from this machine to the target machine performed before the comm_barrier() call are completed before any call sent after the comm barrier() call. \note This affects the global context */ inline void comm_barrier(procid_t targetmachine) { rmi.comm_barrier(targetmachine); } /** This is a convenience function which broadcasts a comm_barrier() \note having all machines call the comm barrier does not guarantee that all calls have been processed. Basically 'p' local barriers do not result in a global barrier. \note This affects the global context */ inline void comm_barrier() { rmi.comm_barrier(); } /** This is a blocking send_to. It send an object T to the target machine, but waits for the target machine to call recv_from before returning. Functionally similar to MPI's matched sending/receiving */ template <typename U> inline void send_to(procid_t target, U& t, bool control = false) { rmi.send_to(target, t, control); } /** A blocking recv_from. Must be matched with a send_to call from the target before both source and target resumes. */ template <typename U> inline void recv_from(procid_t source, U& t, bool control = false) { rmi.recv_from(source, t, control); } /** This function allows one machine to broadcasts a variable to all machines. The originator calls broadcast with data provided in in 'data' and originator set to true. All other callers call with originator set to false. The originator will then return 'data'. All other machines will receive the originator's transmission in the "data" parameter. This call is guaranteed to have barrier-like behavior. That is to say, this call will block until all machines enter the broadcast function. \note Behavior is undefined if more than one machine calls broadcast with originator set to true. \note Behavior is undefined if multiple threads on the same machine call broadcast simultaneously. If multiple-thread broadcast is necessary, each thread should use its own instance of the services class. */ template <typename U> inline void broadcast(U& data, bool originator, bool control = false) { rmi.broadcast(data, originator, control); } /** * data must be of length data[numprocs]. * My data is stored in data[dc.procid()]. * when function returns, machine sendto will have the complete vector * where data[i] is the data contributed by machine i. * All machines must have the same parameter for "sendto" */ template <typename U> inline void gather(std::vector<U>& data, procid_t sendto, bool control = false) { rmi.gather(data, sendto, control); } /** * Each machine creates a vector 'data' with size equivalent to the number of machines. * Each machine then fills the entry data[procid()] with information that it * wishes to communicate. * After calling all_gather(), all machines will return with identical * vectors 'data', where data[i] contains the information machine i stored. */ template <typename U> inline void all_gather(std::vector<U>& data, bool control = false) { rmi.all_gather(data, control); } /** * This function is takes a vector of local elements T which must * be comparable and constructs a vector of length numprocs where * each element is a subset of the local contribution from that * machine and the union of all elements in the union of all local * contributions and all entries are unique: * * Usage: Each process reads the files that are stored locally and * wants to know which subset of local files to read even when * multiple processes see the same files. */ template <typename U> inline void gather_partition(const std::vector<U>& local_contribution, std::vector< std::vector<U> >& ret_partition, bool control = false) { rmi.gather_partition(local_contribution, ret_partition, control); } /** A regular barrier equivalent to MPI_Barrier. A thread machine entering this barrier will wait until one thread on each machines enter this barrier. \see full_barrier */ inline void barrier() { rmi.barrier(); } /** This barrier ensures globally across all machines that all calls issued prior to this barrier are completed before returning. This function could return prematurely if other threads are still issuing function calls since we cannot differentiate between calls issued before the barrier and calls issued while the barrier is being evaluated. Therefore, when used in a multithreaded scenario, the user must ensure that all other threads which may perform operations using this object are stopped before the full barrier is initated. \see barrier */ inline void full_barrier() { rmi.full_barrier(); } }; } // end of namespace graphlab #include <graphlab/macros_undef.hpp> #endif
// speech-project.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <fstream> #include <math.h> #include <iomanip> #include <vector> #include <algorithm> #include <sstream> #include <windows.h> #define CONVERGE_ITERATIONS 200 #define M 32 //Number of obsevation symbols per state #define N 5 //Number of states #define P 12 #define LIMIT 5000 #define CB_SIZE 32 #define PI 3.142857142857 #define FRAME_SIZE 320 #define FRAMES 100 const int WIN_SIZE = (FRAME_SIZE * FRAMES); int T; //Time sequence length const int MAX_T = 150; // max time sequence length using namespace std; //Global variables long double dcShift, nFactor, mx, silenceEnergy; long double const threshold = 1e-30; //Min threshold to be assigned to zero values in matrix B. long int sSize = 0, sampSize = 0, enSize = 0; long double max_pobs_model = 0; int test_ans = 0, fake = 0; //Globally defined arrays int O[MAX_T+1]; //Observation sequence int Q[MAX_T+1]; //state sequence. long double pstar = 0, prev_p_star = -1; int Psi[MAX_T+1][N+1]; long double Alpha[MAX_T+1][N+1]; long double Beta[MAX_T+1][N+1]; long double Gamma[MAX_T+1][N+1]; long double Delta[MAX_T+1][N+1]; long double Xi[MAX_T+1][N+1][N+1]; //codebook long double codeBook[CB_SIZE][P]; //arrays for samples long int sample[1000000]; long double steadySamp[WIN_SIZE]; long double energy[100000]; long double Ai[P+1], Ri[P+1], Ci[P+1]; //tokhura weights double tokhuraWeights[]={1.0, 3.0, 7.0, 13.0, 19.0, 22.0, 25.0, 33.0, 42.0, 50.0, 56.0, 61.0}; //Model parameters A, B and Pi long double A[N+1][N+1] = {0}; long double B[N+1][M+1] = {0}; long double Pi[N+1] = {0}; long double Abar[N+1][N+1] = {0}; long double Bbar[N+1][M+1] = {0}; long double Pibar[N+1] = {0}; long double a_average[N+1][N+1] = {0}; long double b_average[N+1][M+1] = {0}; long double pi_average[N+1] = {0}; //files char* A_file = "a_i_j.txt"; char* B_file = "b_i_j.txt"; char* PI_file = "pi.txt"; int cnt = 1, train = 0; long double P_O_given_Model = 0; ofstream uni, dump; FILE *common_dump; int environment_known = 0, is_live_testing = 0; char keywords[][100] = {"calendar", "close", "down", "exit", "faculties", "github", "history", "jobs", "open", "outlook", "payments", "portal", "quora", "search", "up", "video"}; //////////////////////////////////////////////////////////Browser related code/////////////////////////////////////////////////////////////////// bool browser_open = false; #define SCROLL_DOWN_VAL -700 #define SCROLL_UP_VAL 700 #define CONFIRM_BOX_YES 6 #define CONFIRM_BOX_NO 7 #define CONFIRM_BOX_CANCEL 2 static const WORD TAB_SCANCODE = 0x0f; static const WORD LEFT_ALT_SCANCODE = 0x38; static const WORD LCTRL_SCANCODE = 0x1d; static const WORD H_SCANCODE = 0x23; static const WORD B_SCANCODE = 0x30; static const WORD J_SCANCODE = 0x24; static const WORD K_SCANCODE = 0x25; static const WORD O_SCANCODE = 0x18; static const WORD P_SCANCODE = 0x19; static const WORD NUMPAD_5 = 0x4c; static const WORD LSHIFT_SCANCODE = 0x2a; static const DWORD keypress_delay_ms = 500; static const WORD W_SCANCODE = 0x11; bool next_prob_word[16]; string browserName = "Firefox"; char window_title[256]; HWND hwnd; void sendkey(WORD scan_code, bool tf_down_up, bool extended = false) { INPUT input = { 0 }; input.type = INPUT_KEYBOARD; input.ki.wScan = scan_code; input.ki.dwFlags = KEYEVENTF_SCANCODE; if (!tf_down_up) input.ki.dwFlags |= KEYEVENTF_KEYUP; if (extended) input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; SendInput(1, &input, sizeof(input)); } void keydown(WORD scan_code, bool extended = false) { sendkey(scan_code, true, extended); } void keyup(WORD scan_code, bool extended = false) { sendkey(scan_code, false, extended); } void alt_tab(int tab_count = 1) { keydown(LEFT_ALT_SCANCODE); Sleep(keypress_delay_ms); for (int i = 0; i<tab_count; ++i) { keydown(TAB_SCANCODE); Sleep(keypress_delay_ms); keyup(TAB_SCANCODE); Sleep(keypress_delay_ms); } keyup(LEFT_ALT_SCANCODE); } void toggle_to_browser(){ Sleep(500); alt_tab(2); } void ctrl_h(){ keydown(LCTRL_SCANCODE); Sleep(keypress_delay_ms); keydown(H_SCANCODE); Sleep(keypress_delay_ms); keyup(H_SCANCODE); Sleep(keypress_delay_ms); keyup(LCTRL_SCANCODE); Sleep(keypress_delay_ms); } void open_history(){ ctrl_h(); } void ctrl_j(){ keydown(LCTRL_SCANCODE); Sleep(keypress_delay_ms); keydown(J_SCANCODE); Sleep(keypress_delay_ms); keyup(J_SCANCODE); Sleep(keypress_delay_ms); keyup(LCTRL_SCANCODE); Sleep(keypress_delay_ms); } void ctrl_w(){ keydown(LCTRL_SCANCODE); Sleep(keypress_delay_ms); keydown(W_SCANCODE); Sleep(keypress_delay_ms); keyup(W_SCANCODE); Sleep(keypress_delay_ms); keyup(LCTRL_SCANCODE); Sleep(keypress_delay_ms); } void ctrl_k(){ keydown(LCTRL_SCANCODE); Sleep(keypress_delay_ms); keydown(K_SCANCODE); Sleep(keypress_delay_ms); keyup(K_SCANCODE); Sleep(keypress_delay_ms); keyup(LCTRL_SCANCODE); Sleep(keypress_delay_ms); } void alt_p(){ keydown(LEFT_ALT_SCANCODE); Sleep(keypress_delay_ms); keydown(P_SCANCODE); Sleep(keypress_delay_ms); keyup(P_SCANCODE); Sleep(keypress_delay_ms); keyup(LEFT_ALT_SCANCODE); Sleep(keypress_delay_ms); } void show_menu(){ printf("OPEN - to open the browser\nHISTORY - to see the history\nClose - to close the current tab\n"); printf("UP - to scroll up\nDOWN - to scroll down\nCALENDAR - to see institute calendar\nQUORA - to see the quora page\n"); printf("GITHUB - to see the GitHub\nJOBS - to see the jobs page\nPORTAL - to see the placement portal of IITG\n"); printf("SEARCH - to search on google\nPayments - to open the fees payment page of IITG\nVIDEO - to search the video on youtube\n"); printf("FACULTIES - to see the faculty page\nOUTLOOK - to open the outlook\nEXIT - to exit the browser\n"); printf("Speak what you want to do - \n"); } void close_browser(){ char command[50]; sprintf(command, "taskkill /f /im %s.exe", browserName); system("taskkill /f /im firefox.exe"); } void close_tab(){ ctrl_w(); } void open_faculty_page(){ system("start https://iitg.ac.in/iitg_faculty_all"); } void open_outlook(){ system("start https://outlook.office.com/mail/"); } void search_video(){ char video_search[] = "https://www.youtube.com/results?search_query="; char input[100], final[200]; char temp; printf("Enter the video name - "); scanf("%c", &temp); //fgets(input, 100, stdin); cin.getline(input, 100); int i=0; while(input[i] != '\0'){ if(input[i] == ' ') input[i] = '+'; i++; } sprintf(final, "%s", video_search); strcat(final, input); char command[1000]; sprintf(command, "start %s", final); system(command); } void open_payments(){ system("start https://online.iitg.ac.in/epay/"); } void search_google(){ //query replace space with + char search_query[] = "https://www.google.com/search?q="; char qinput[100], final[200]; char temp; printf("Enter the search query - "); scanf("%c", &temp); cin.getline(qinput, 100); int i = 0; while(qinput[i] != '\0'){ if(qinput[i] == ' ') qinput[i] = '+'; i++; } sprintf(final, "%s", search_query); strcat(final, qinput); char command[100]; sprintf(command, "start %s", final); system(command); } void open_quora(){ system("start https://www.quora.com/"); } void open_portal(){ system("start https://swc.iitg.ac.in/placement-portal/"); } void open_jobs(){ system("start https://www.naukri.com/"); } void open_github(){ system("start https://github.com"); } void go_to_browser(){ Sleep(keypress_delay_ms); alt_tab(2); } void open_calendar(){ system("start https://iitg.ac.in/acad/academic_calender.php"); } void scrolling_down(){ Sleep(500); mouse_event(MOUSEEVENTF_WHEEL, 0, 0, SCROLL_DOWN_VAL, 0); } void scrolling_up(){ Sleep(500); mouse_event(MOUSEEVENTF_WHEEL, 0, 0, SCROLL_UP_VAL, 0); } void open_browser(){ system("start www.google.com"); } int is_substring(string a, string b){ int m = a.length(); int n = b.length(); for (int i = 0; i <= n - m; i++) { int j; for (j = 0; j < m; j++) if (b[i + j] != a[j]) break; if (j == m) return i; } return -1; } //perform the operation according to detected operation void perform(int index){ //index = 13; int x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11; int i; if (system(NULL)) puts("Proceed"); else exit(1); //deciding what to do switch (index){ case 0: { open_calendar(); for(int i = 0; i<16; i++){ if(i == 14 || i==0){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } case 1: { x2 = 5; while (x2>0){ alt_tab(2); Sleep(1000); hwnd = GetForegroundWindow(); // get handle of currently active window GetWindowTextA(hwnd, window_title, sizeof(window_title)); printf("\n%s", window_title); if (is_substring(browserName, window_title) != -1){ break; } x2--; } close_tab(); break; } //scroll dowwn case 2: { x3 = 5; while (x3>0){ alt_tab(2); Sleep(1000); hwnd = GetForegroundWindow(); // get handle of currently active window GetWindowTextA(hwnd, window_title, sizeof(window_title)); printf("\n%s", window_title); if (is_substring(browserName, window_title) != -1){ break; } x3--; } scrolling_down(); alt_tab(1); for(int i = 0; i<16; i++){ if(i == 8){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } //exit browser case 3: { // if (close_flag == 1) // { x1 = MessageBox(nullptr, TEXT("Do you want to close browser?"), TEXT("Message"), MB_YESNOCANCEL); if (x1 == CONFIRM_BOX_YES) { system("taskkill /IM firefox.exe /F"); // close_flag = 0; // read_flag = 0; // stop_flag = 0; for(int i = 0; i<16; i++){ if(i == 3) next_prob_word[i] = 0; else next_prob_word[i] = 1; } } // } break; } case 4: { open_faculty_page(); for(int i = 0; i<16; i++){ if(i == 8 || i==4){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } case 5: { open_github(); for(int i = 0; i<16; i++){ if(i == 8 || i==5){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } //history case 6: { x7 = 5; while (x7 >0){ alt_tab(2); Sleep(1000); hwnd = GetForegroundWindow(); // get handle of currently active window GetWindowTextA(hwnd, window_title, sizeof(window_title)); printf("\n%s", window_title); if (is_substring(browserName, window_title) != -1){ break; } x7--; } open_history(); alt_tab(1); break; } case 7: { open_jobs(); for(int i = 0; i<16; i++){ if(i == 8 || i == 7){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } //open browser case 8: { system("start https://www.google.com/"); for (i = 0; i < 11; i++){ if ((i == 8)) next_prob_word[i] = 0; else next_prob_word[i] = 1; } break; } case 9: { open_outlook(); for(int i=0; i<16; i++){ if( i == 9 || i == 8){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } case 10: { open_payments(); for(int i=0; i<16; i++){ if( i==8 || i == 10 ){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } case 11: { open_portal(); for(int i = 0; i<16; i++){ if(i == 8 || i == 11){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } case 12: { open_quora(); for(int i = 0; i<16; i++){ if(i == 8 || i == 12){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } case 13: { search_google(); for(int i = 0; i<16; i++){ if(i == 8 || i == 13){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } //scroll up case 14: { x2 = 5; while (x2>0){ alt_tab(2); Sleep(1000); hwnd = GetForegroundWindow(); // get handle of currently active window GetWindowTextA(hwnd, window_title, sizeof(window_title)); //printf("\n%s", window_title); if (is_substring(browserName, window_title) != -1){ break; } x2--; } scrolling_up(); alt_tab(1); for(int i = 0; i<16; i++){ if(i == 8){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } case 15: { search_video(); for(int i = 0; i<16; i++){ if(i == 8 || i == 15){ next_prob_word[i] = 0; } else { next_prob_word[i] = 1; } } break; } default : system("taskkill /IM Firefox.exe /F"); break; } } ////////////////////////////////////////Functions related to speech processing//////////////////////////////////////////////////////// //Calculation of alpha variable to find the solution of problem number 1. void forward_procedure(){ int i , j , t; long double sum ; int index = O[1]; P_O_given_Model = 0; for(i=1;i<=N;i++){ Alpha[1][i] = Pi[i]*B[i][index]; } for (t = 1; t < T; t++){ for (j = 1; j <= N; j++){ sum = 0; for (i = 1; i <= N; i++){ sum += Alpha[t][i] * A[i][j]; } Alpha[t + 1][j] = sum * B[j][O[t + 1]]; } } for(i=1;i<=N;i++){ P_O_given_Model = P_O_given_Model + Alpha[T][i]; } } //Calculation of alpha variable to find the solution of problem number 1. void forward_procedure(int iteration, FILE *fp = NULL){ int i , j , t; long double sum ; int index = O[1]; P_O_given_Model = 0; for(i=1;i<=N;i++){ Alpha[1][i] = Pi[i]*B[i][index]; } for (t = 1; t < T; t++){ for (j = 1; j <= N; j++){ sum = 0; for (i = 1; i <= N; i++){ sum += Alpha[t][i] * A[i][j]; } Alpha[t + 1][j] = sum * B[j][O[t + 1]]; } } for(i=1;i<=N;i++){ P_O_given_Model = P_O_given_Model + Alpha[T][i]; } //finding where the model is matching if(P_O_given_Model > max_pobs_model){ max_pobs_model = P_O_given_Model; test_ans = iteration; } cout << "Word : "<<keywords[iteration]<<"\tP(obs/model) : " << P_O_given_Model <<endl; if(fp != NULL){ fprintf(fp, "---> Word %s ----- P(Obs/Model) : %g\n", keywords[iteration], P_O_given_Model); //cout << "Digit:"<<iteration<<"\tP(obs/model) : " << P_O_given_Model <<endl; } } //function for testing with iteration as argument void solution_to_prob1(int iteration, FILE *fp = NULL){ if(fp == NULL) forward_procedure(iteration); else forward_procedure(iteration, fp); } //Calculation of Beta variable. void backward_procedure(){ int i , j , t; long double sum; int index = 0; for(i=1;i<=N;i++){ Beta[T][i] = 1.0; } for(t=T-1;t>=1;t--){ index = O[t+1]; for(i=1;i<=N;i++){ sum = 0; for(j=1;j<=N;j++){ sum = sum + B[j][index]*A[i][j]*Beta[t+1][j]; } Beta[t][i]=sum; } } } //calculating alpha and beta values void calculate_gamma(){ for(int t=1;t<=T;t++){ for(int j=1;j<=N;j++){ long double summation=0; for(int k=1;k<=N;k++){ summation += Alpha[t][k] * Beta[t][k]; } Gamma[t][j]=(Alpha[t][j] * Beta[t][j])/summation; } } } //loading the model parameters with new calculated values void load_calculated_model(){ int i, j; for(i=1;i<=N;i++){ Pi[i]=Pibar[i]; } for(i=1;i<=N;i++){ for(j=1;j<=N;j++){ A[i][j]= Abar[i][j]; } } for(i=1;i<=N;i++){ for(j=1;j<=M;j++){ B[i][j] = Bbar[i][j]; } } } void reevaluate_model_parameters(){ int i, j, k, t; long double sum1=0 , sum2 =0; //Re-evaluating Pi for(i=1;i<=N;i++){ Pibar[i] = Gamma[1][i]; } for(i = 1; i<=N; i++){ for(j = 1; j <= N; j++){ long double t1 = 0, t2 = 0; for(t = 1; t <= T-1; t++){ t1 += Xi[t][i][j]; t2 += Gamma[t][i]; //cout<<"Xi["<<t<<"]["<<i<<"]["<<j<<"]: "<<Xi[t][i][j]<<", Gamma["<<t<<"]["<<j<<"]: "<<Gamma[t][j]<<endl; } //cout<<"t1 "<<t1<<" t2: "<<t2<<endl; //cout<<"t1/t2: "<<t1/t2<<endl; //system("pause"); Abar[i][j] = t1/t2; } } //Re-evaluating B for(j=1;j<=N;j++){ int count=0; long double max=0; int ind_j=0, ind_k=0; for(k=1;k<=M;k++){ sum1 =0 , sum2 =0; for(t=1;t<T;t++){ sum1 = sum1 + Gamma[t][j]; if(O[t]==k){ sum2 = sum2 + Gamma[t][j]; } } Bbar[j][k] = sum2/sum1; //finding max if(Bbar[j][k]>max){ max=Bbar[j][k]; ind_j = j; ind_k = k; } //updating new bij with threshold value if it is zero if(Bbar[j][k] == 0){ Bbar[j][k]=threshold; count++; } } Bbar[ind_j][ind_k] = max - count*threshold; } //loading the new model load_calculated_model(); } //Adjusting Model Parameters void calculate_xi(){ int i , j , t , index; long double summation[FRAMES + 1]; for(t=1;t<=T;t++){ // index = ; summation[t] = 0; for(i=1;i<=N;i++){ for(j=1;j<=N;j++){ summation[t] += Alpha[t][i]*A[i][j]*B[j][O[t+1]]*Beta[t+1][j]; } } for(i=1;i<=N;i++){ long double x; for(j=1;j<=N;j++){ x = Alpha[t][i]*A[i][j]*B[j][O[t+1]]*Beta[t+1][j]; Xi[t][i][j]= x/summation[t]; } } } } //viterbi algorithm void viterbi(){ //initialization for(int i=1; i<=N; i++){ Delta[1][i] = Pi[i] * B[i][O[1]]; Psi[1][i] = 0; } //induction for(int j=1; j<=N; j++){ for(int t=2; t<=T; t++){ long double max = 0, ti = 0; int ind = 0; for(int i=1; i<=N; i++){ ti = Delta[t-1][i] * A[i][j]; if(ti > max){ max = ti; ind = i; } } Delta[t][j] = max * B[j][O[t]]; Psi[t][j] = ind; } } //termination long double max = 0; for(int i=1; i<=N; i++){ if(Delta[T][i] > max) { max = Delta[T][i]; Q[T] = i; } pstar = max; } //backtracking for(int t = T-1; t>0; t--){ Q[t] = Psi[t+1][Q[t+1]]; } } //writing updated A matrix to file void write_final_A_matrix(FILE *fp){ int i, j; fprintf(fp, "---------------A Matrix----------------\n"); for (i = 1; i <= N; i++){ for (j = 1; j <= N; j++){ fprintf(fp,"%Le ",A[i][j]); } fprintf(fp,"\n"); } } //writing updated B matrix to file void write_final_B_matrix(FILE *fp){ int i, j; fprintf(fp, "---------------B Matrix----------------\n"); for (i = 1; i <= N; i++){ for (j = 1; j <= M; j++){ fprintf(fp, "%Le ", B[i][j]); } fprintf(fp, "\n"); } } //writing updated pi values to file void write_final_pi_matrix(FILE *fp){ fprintf(fp, "---------------Pi values----------------\n"); int i, j; for (i = 1; i <= N; i++){ fprintf(fp, "%Le ", Pi[i]); } } //dump the model void dump_converged_model(FILE *fp){ write_final_A_matrix(fp); write_final_B_matrix(fp); write_final_pi_matrix(fp); } //read A bool readA(char *filename){ fstream fin; fin.open(filename); //file does not exist if(!fin){ cout<<"Couldn't open file: "<<filename<<"\n"; return false; } long double word; int row = 1, col = 1; //until input is available while(fin >> word){ col = 1; A[row][col++] = word; for(int i=2; i<=N; i++){ fin>>word; A[row][col++] = word; } row++; } fin.close(); return true; } //read B bool readB(string filename){ fstream fin; fin.open(filename); //file does not exist if(!fin){ cout<<"Couldn't open file: "<<filename<<"\n"; return false; } long double words; int row = 1, col = 1; while(fin>>words){ col = 1; B[row][col++] = words; for(int i=1; i<M; i++){ fin>>words; B[row][col++] = words; } row++; } //cout<<"row: "<<row<<endl; fin.close(); return true; } //read Pi bool readPi(string filename){ fstream fin; fin.open(filename); //file does not exist if(!fin){ cout<<"Couldn't open file: "<<filename<<"\n"; return false; } long double word; int col = 1; //until input is available while(fin >> word){ col = 1; Pi[col++] = word; //save whole row for(int i=1;i<N;i++){ fin>>word; Pi[col++] = word; } } fin.close(); return true; } // make the model values, average model values and bar model values - 0 void erase_all_model(){ for(int i=1; i<=N; i++){ for(int j=1; j<=N; j++){ A[i][j] = 0; a_average[i][j] = 0; Abar[i][j] = 0; } } for(int i=1; i<=N; i++){ for(int j=1; j<=M; j++){ B[i][j] = 0; b_average[i][j] = 0; Bbar[i][j] = 0; } } for(int i=1; i<=N; i++){ Pi[i] = 0; Pibar[i] = 0; pi_average[i] = 0; } } //erasing the current model void erase_model(){ for(int i=1; i<=N; i++){ for(int j=1; j<=N; j++){ A[i][j] = 0; } } for(int i=1; i<=N; i++){ for(int j=1; j<=M; j++){ B[i][j] = 0; } } for(int i=1; i<=N; i++){ Pi[i] = 0; } } // erasing average model void erase_avg_model(){ for(int i=1; i<=N; i++){ for(int j=1; j<=N; j++){ a_average[i][j] = 0; } } for(int i=1; i<=N; i++){ for(int j=1; j<=M; j++){ b_average[i][j] = 0; } } for(int i=1; i<=N; i++){ pi_average[i] = 0; } } //reading average model void read_average_model(int digit){ char filename[100]; sprintf(filename, "output/avgmodels/word_%s_A.txt", keywords[digit]); readA(filename); sprintf(filename, "output/avgmodels/word_%s_B.txt", keywords[digit]); readB(filename); sprintf(filename, "output/avgmodels/word_%s_PI.txt", keywords[digit]); readPi(filename); } //reading average model void read_average_model_for_testing(int digit){ char filename[100]; sprintf(filename, "output/final_avgmodels/word_%s_A.txt", keywords[digit]); readA(filename); sprintf(filename, "output/final_avgmodels/word_%s_B.txt", keywords[digit]); readB(filename); sprintf(filename, "output/final_avgmodels/word_%s_PI.txt", keywords[digit]); readPi(filename); } //initialize model according to parameters void initialize_model(int digit, int seq, char *filename = "--"){ char a_file[100], b_file[100], pi_file[100], obs_file[100]; if(filename == "--"){ readA(A_file); readB(B_file); readPi(PI_file); }else if(filename == "avg") { read_average_model(digit); } // else if(filename == "init"){ // sprintf(a_file, "validation/Digit %d/A_%d.txt", digit, digit); // sprintf(b_file, "validation/Digit %d/B_%d.txt", digit, digit); // sprintf(pi_file, "validation/Digit %d/pi_%d.txt", digit, digit); // readA(a_file); // readB(b_file); // readPi(pi_file); // z } //adding current model values to avg model void add_to_avg_model(){ int i, j; for (i = 1; i <= N; i++){ for (j = 1; j <= N; j++){ a_average[i][j] += A[i][j]; } } for (i = 1; i <= N; i++){ pi_average[i] += Pi[i]; } for (int i = 1; i <= N; i++){ for (int j = 1; j <= M; j++){ b_average[i][j] += B[i][j]; } } } //writing updated a values void write_final_A_values(char filename[]){ FILE *fp = fopen(filename, "w"); int i, j; for (i = 1; i <= N; i++){ for (j = 1; j <= N; j++){ // out << a_i_j[i][j] << " "; fprintf(fp, "%Le ", A[i][j]); } fprintf(fp, "\n"); } fclose(fp); } //writing updated b values void write_final_B_values(char filename[]){ ofstream out(filename); for(int i=1; i<=N; i++){ for(int j=1; j<=M; j++){ out<<B[i][j]<<" "; } out<<endl; } out.close(); } //writing updated pi values void write_final_pi_values(char filename[]){ FILE *fp = fopen(filename, "w"); int i, j; for (i = 1; i <= N; i++){ // out << pi[i] << " "; fprintf(fp, "%Le ", Pi[i]); } fclose(fp); } // dump the final model in output/digit d/ folder wise void dump_final_model(int seq, int digit){ char index[10]; char a_file_final[100], b_file_final[100], pi_file_final[100]; sprintf(pi_file_final, "output/%s/model_PI_%d.txt", keywords[digit], seq); write_final_pi_values(pi_file_final); sprintf(a_file_final, "output/%s/model_A_%d.txt", keywords[digit], seq); write_final_A_values(a_file_final); sprintf(b_file_final, "output/%s/model_B_%d.txt", keywords[digit], seq); write_final_B_values(b_file_final); cout<<"word "<<keywords[digit]<<", sequence : "<<seq<<" model dumped successfully\n"; } // taking average of the avg model void average_of_avg_model(int total_iterations){ int i, j; for (i = 1; i <= N; i++){ pi_average[i] /= total_iterations; } for (i = 1; i <= N; i++){ for (j = 1; j <= N; j++){ a_average[i][j] /= total_iterations; } } for (i = 1; i <= N; i++){ for (j = 1; j <= M; j++){ b_average[i][j] /= total_iterations; } } } // dumping average model to file void dump_avg_model(int digit){ char a_file_avg[100], b_file_avg[100], pi_file_avg[100], ind[3]; sprintf(a_file_avg, "output/avgmodels/word_%s_A.txt", keywords[digit]); FILE *fp = fopen(a_file_avg, "w"); for(int i=1; i<=N; i++){ for(int j=1; j<=N; j++){ fprintf(fp, "%Le ", a_average[i][j]); } fprintf(fp, "\n"); } fclose(fp); sprintf(b_file_avg, "output/avgmodels/word_%s_B.txt", keywords[digit]); ofstream fout(b_file_avg); for(int i=1; i<=N; i++){ for(int j=1; j<=M; j++){ //fprintf(fp, "%Le ", b_average[i][j]); fout<<b_average[i][j]<<" "; } fout<<endl; //fprintf(fp, "\n"); } fout.close(); sprintf(pi_file_avg, "output/avgmodels/word_%s_PI.txt", keywords[digit]); fp = fopen(pi_file_avg, "w"); for(int i=1; i<=N; i++){ fprintf(fp, "%Le ", pi_average[i]); } fclose(fp); } //finding dc shift void get_DC_shift(){ long int sample_count = 0; int cnt = 0; FILE *fp; char line[80]; double cValue; double cEnergy = 0; //reading dc_shift.txt file if(is_live_testing == 0) fp = fopen("silence.txt", "r"); else fp = fopen("silence_file.txt", "r"); if(fp == NULL){ printf("Silence File not found\n"); exit(1); } dcShift = 0; silenceEnergy = 0; //resetting the silence Energy to 0 while(!feof(fp)){ fgets(line, 80, fp); cValue = atof(line); dcShift += cValue; if(cnt == 100){ if(silenceEnergy < cEnergy){ silenceEnergy = cEnergy; } cEnergy = 0; cnt = 0; } cnt++; cEnergy += cValue * cValue; sample_count++; } dcShift /= sample_count; fclose(fp); } // dumping average model to file generated in live training void dump_avg_model_live(int digit){ char a_file_avg[100], b_file_avg[100], pi_file_avg[100], ind[3]; sprintf(a_file_avg, "output/live_avgmodels/word_%s_A.txt", keywords[digit]); FILE *fp = fopen(a_file_avg, "w"); for(int i=1; i<=N; i++){ for(int j=1; j<=N; j++){ fprintf(fp, "%Le ", a_average[i][j]); } fprintf(fp, "\n"); } fclose(fp); sprintf(b_file_avg, "output/live_avgmodels/word_%s_B.txt", keywords[digit]); ofstream fout(b_file_avg); for(int i=1; i<=N; i++){ for(int j=1; j<=M; j++){ //fprintf(fp, "%Le ", b_average[i][j]); fout<<b_average[i][j]<<" "; } fout<<endl; //fprintf(fp, "\n"); } fout.close(); sprintf(pi_file_avg, "output/live_avgmodels/word_%s_PI.txt", keywords[digit]); fp = fopen(pi_file_avg, "w"); for(int i=1; i<=N; i++){ fprintf(fp, "%Le ", pi_average[i]); } fclose(fp); } //function to setup the global variable like, max and nFactor //max and nFactor depends on the vowel recording file and are used to do the normalization void setupGlobal(char *filename){ FILE *fp; long int totalSample = 0; char line[100]; fp = fopen(filename, "r"); if(fp == NULL){ printf("Error opening file\n"); } //get max value mx = 0; while(!feof(fp)){ fgets(line, 100, fp); if(!isalpha(line[0])){ totalSample++; if(mx < abs(atoi(line))) mx = abs(atoi(line)); } } nFactor = (double)LIMIT/mx; //setup dcShift get_DC_shift(); fclose(fp); } //Calculating Tokhura's Distance Using Code Book void calculate_tokhura_distance(long double cepstralCoeff[12], int index, FILE *fp){ int min_index = 0; long double min = DBL_MAX; long double sum[CB_SIZE] = { 0 }; string temp, temp1; for (int j = 0; j < CB_SIZE; j++){ for (int i = 0; i < P; i++){ sum[j] += tokhuraWeights[i] * (cepstralCoeff[i] - codeBook[j][i])*(cepstralCoeff[i] - codeBook[j][i]); } if (sum[j] < min){ min = sum[j]; min_index = j; } } O[index] = min_index + 1; //cout << O[index] << " "; fprintf(fp, "%4d ", O[index]); } //This function calulate the cepstral coefficients Ci's void calculate_Cis(){ //if(fake == 62) system("pause"); double sum=0; Ci[0]=log(Ri[0]*Ri[0]); for(int m=1;m<=P;m++){ sum=0; for(int k=1;k<m;k++){ sum += (k*Ci[k]*Ai[m-k])/(m*1.0); } Ci[m]=Ai[m]+sum; } //fake++; } // Function to apply Durbin Algorithm And Find The value of ai's void durbinAlgo(){ double alpha[13][13],E[13],K[13]; double sum = 0; E[0] = Ri[0]; //loop for p from 1 to 12 for(int i=1;i<=P;i++){ sum=0; for(int j=1;j<=i-1;j++){ sum += alpha[i-1][j]*Ri[i-j]; } K[i]=(Ri[i]-sum)/E[i-1]; alpha[i][i]=K[i]; for(int j=1;j<=i-1;j++){ alpha[i][j]=alpha[i-1][j] - K[i]*alpha[i-1][i-j]; } E[i]=(1-(K[i]*K[i]))*E[i-1]; } //storing the ai values for(int i=1;i<=P;i++){ Ai[i]= alpha[P][i]; } } //calculating the Ris values void calculate_Ris(double *samp){ //if(fake == 62) system("pause"); for(int m =0; m<=P; m++){ Ri[m] = 0; for(int k=0; k<FRAME_SIZE-m; k++){ Ri[m] += samp[k]*samp[k+m]; } } } //function to apply the Raised Sine Window in Ci of each frame void applyingRaisedSinWindow(){ long double sum=0; for(int m=1;m<=P;m++){ sum = (P/2)*sin((PI*m)/P); Ci[m]*=sum; } } //calculating c prime values void calculate_c_prime(double *samp){ calculate_Ris(samp); //calling durbinAlgo to find ai values durbinAlgo(); //finding cepstral constants calculate_Cis(); //applying raised sin window on cis applyingRaisedSinWindow(); //code for universe generation for(int i=1; i<=P; i++){ if(i == P) uni<<setw(10)<<Ci[i]; else uni<<setw(10)<<Ci[i]<<", "; } uni<<endl; } void trim_word(){ int num_frames = 0; int cnt =0; enSize = 0; double cEnergySum = 0, multiplier = 3; int startMarker = -1, endMarker = -1; for(int i=0; i<sSize; i++){ double cEnergy = sample[i]*sample[i]; if(cnt == 100){ energy[enSize++] = cEnergySum; cEnergySum = 0; cnt = 0; } cnt++; cEnergySum += cEnergy; } //printf("\nenergy - \n"); for(int i=0; i<enSize; i++){ //printf("%d: %lf\n", i, energy[i]); } int min_samples = 11200; for(int i=0; i<enSize-4; i++){ if(startMarker == -1 && endMarker == -1 && energy[i+1] > multiplier * silenceEnergy && energy[i+2] > multiplier * silenceEnergy && energy[i+3] > multiplier * silenceEnergy && energy[i+4] > multiplier * silenceEnergy){ startMarker = i*100; }else if(startMarker != -1 && endMarker == -1 && energy[i+1] <= multiplier * silenceEnergy && energy[i+2] <= multiplier * silenceEnergy && energy[i+3] <= multiplier * silenceEnergy && energy[i+4] <= multiplier * silenceEnergy){ int diff = i*100 - startMarker; if(diff < min_samples){ startMarker = 0 > (startMarker - (min_samples - diff)/2) ? 0 : (startMarker - (min_samples - diff)/2); endMarker = enSize*100 < (i*100 + (min_samples - diff)/2) ? enSize*100 : (i*100 + (min_samples - diff)/2); } else endMarker = i*100; }else if(startMarker != -1 && endMarker!= -1) break; } sampSize = 0; ofstream out("trimmed.txt"); for(int i=startMarker; i<=endMarker; i++){ steadySamp[sampSize++] = sample[i]; out<<sample[i]<<endl; } out.close(); //system("pause"); } //[not using] double* trim(){ int i; long double total_energy, current_value; char trimmed_file[100]; int start_marker = 0, end_marker = 0; total_energy = 0; int interval = WIN_SIZE, index_count = 0, arr_index = 0; double samp[WIN_SIZE] = {0}; long double total_max_energy = 0; int initial_shift_pointer = 0, shift_pointer_count = 0, writing_count = 0; long double arr_energy[50]; long count1 = 0; string temp = ""; //cout << "\n................Trimming Waveform..................." << endl; int count = interval; //in.open(normalized_file); ofstream out("energy_trim.txt"); //window shifting logic for (i = 0; i < sSize; i++){ count1++; //if (shift_pointer_count >= initial_shift_pointer){ //current_value = stold(temp); current_value = sample[i]; current_value *= 0.1; total_energy += (current_value*current_value); count--; if (!count){ out << to_string(total_energy) << endl; if (total_energy > total_max_energy){ total_max_energy = total_energy; start_marker = initial_shift_pointer; end_marker = initial_shift_pointer + interval; } total_energy = 0; count = interval; initial_shift_pointer += 500; i = initial_shift_pointer - 1; shift_pointer_count = 0; } } out.close(); //cout << "Start Marker : " << start_marker << endl; //cout << "End Marker : " << end_marker << endl; if(end_marker > sSize){ start_marker -= (end_marker - sSize); end_marker = sSize; } sprintf(trimmed_file, "trim.txt"); ofstream out1(trimmed_file); for(int i=0; i<sSize; i++){ index_count++; current_value = sample[i]; //stold(temp); //current_value = current_value - dc_shift_value; //current_value = current_value * normalization_ratio; if (index_count >= start_marker && index_count < end_marker){ samp[arr_index++] = current_value; out1 << samp[arr_index - 1] << endl; } } out1.close(); return samp; } //generate observation sequence void generate_obs_sequence(char *filename){ int obs_ind = 1; FILE *op = fopen(filename, "w"); if(op == NULL) { printf("locha hai idhar bhaiiiii.. \n"); exit(1); } trim_word(); double fsamp[FRAME_SIZE]; int num_frames = 0; for(int i=0; i<sampSize; i++){ num_frames++; for(int j = 0; j<320; j++) fsamp[j] = steadySamp[i++]; calculate_c_prime(fsamp); calculate_tokhura_distance(Ci, obs_ind++, op); } T = num_frames; cout<<"Number of frames: "<<num_frames<<endl; fprintf(op, "\n"); fclose(op); cout<<"wrote observation seq in file: "<<filename<<"\n"; } //generate observation sequence[not using] void generate_obs_sequence(char *filename, FILE *op){ int obs_ind = 1; double *frame_samples = trim(); double fsamp[FRAME_SIZE]; for(int i=0; i<WIN_SIZE; i++){ for(int j = 0; j<320; j++) fsamp[j] = frame_samples[i++]; calculate_c_prime(fsamp); calculate_tokhura_distance(Ci, obs_ind++, op); } cout<<"wrote observation seq in file: "<<filename<<"\n"; } //training particular file [not using] void train_file(char *filename, int digit){ char line[100], obs_file[100]; // for(int d = 0; d<=1; d++){ erase_model(); // for(int u = 1; u<=20; u++){ // sprintf(filename, "input/recordings/Digit %d/rec_%d.txt", d, u); FILE *f = fopen(filename, "r"); if(f == NULL){ printf("Issue in opening file %s", filename); exit(1); } //setting dcshift and nfactor setupGlobal(filename); sSize = 0; //reading the samples and normalizing them while(!feof(f)){ fgets(line, 100, f); //input file may contain header, so we skip it if(!isalpha(line[0])){ int y = atof(line); double normalizedX = floor((y-dcShift)*nFactor); //if(abs(normalizedX) > 1) sample[sSize++] = normalizedX; } } fclose(f); //framing sprintf(obs_file, "output/delete/digit_%d_obs_seq.txt", digit); generate_obs_sequence(obs_file); initialize_model(digit, 1, "--"); int iteration = 1; while(iteration <= CONVERGE_ITERATIONS){ //cout<<"iteration: "<<iteration++<<endl; iteration++; forward_procedure(0); backward_procedure(); viterbi(); calculate_xi(); calculate_gamma(); reevaluate_model_parameters(); //print(); } char a_file_final[100], b_file_final[100], pi_file_final[100]; sprintf(a_file_final, "output/delete/digit_%d_model_A.txt", digit); write_final_A_values(a_file_final); sprintf(b_file_final, "output/digit_%d_model_B.txt", digit); write_final_B_values(b_file_final); sprintf(pi_file_final, "output/digit_%d_model_PI.txt", digit); write_final_pi_values(pi_file_final); system("pause"); // } } //trains the 20 files void training(){ char filename[100], line[100], obs_file[100], dump_file[100], com_dump[100]; erase_all_model(); FILE *digit_dump; int total_files_trained = 20; int total_words = sizeof(keywords)/sizeof(keywords[0]); for(int d = 0; d<total_words; d++){ erase_model(); sprintf(dump_file, "results/training/training_word_%s.txt", keywords[d]); FILE *dig_dump = fopen(dump_file, "w"); fprintf(common_dump, "\n------------------------------------------------> Word %s <------------------------------------------------\n", keywords[d]); fprintf(dig_dump, "\n------------------------------------------------> Word %s <------------------------------------------------\n", keywords[d]); for(int u = 1; u <= total_files_trained; u++){ sprintf(filename, "input/recordings/%s/rec_%d.txt", keywords[d], u); FILE *f = fopen(filename, "r"); if(f == NULL){ printf("Issue in opening file %s", filename); exit(1); } fprintf(dig_dump, "\n------------------------------------------------ opening file %s ------------------------------------------------\n", filename); fprintf(common_dump, "\n------------------------------------------------ opening file %s ------------------------------------------------\n", filename); //setting dcshift and nfactor setupGlobal(filename); sSize = 0; //reading the samples and normalizing them while(!feof(f)){ fgets(line, 100, f); //input file may contain header, so we skip it if(!isalpha(line[0])){ int y = atof(line); double normalizedX = floor((y-dcShift)*nFactor); //if(abs(normalizedX) > 1) sample[sSize++] = normalizedX; } } fclose(f); //framing //generating observation seq sprintf(obs_file, "output/obs_seq/HMM_OBS_SEQ_%s_%d.txt", keywords[d], u); generate_obs_sequence(obs_file); fprintf(dig_dump, "->obs seq: "); fprintf(common_dump, "->obs seq: "); for(int i=1; i<=T; i++){ fprintf(dig_dump, "%4d ", O[i]); fprintf(common_dump, "%4d ", O[i]); } fprintf(dig_dump, "\n"); fprintf(common_dump, "\n"); //initializing model if(train == 0) initialize_model(d, 1, "--"); else initialize_model(d, 1, "avg"); int iteration = 1; //starts converging model upto CONVERGE_ITERATIONS or till convergence whichever reach early pstar = 0, prev_p_star = -1; while(pstar > prev_p_star && iteration < 1000){ //cout<<"iteration: "<<iteration++<<endl; iteration++; prev_p_star = pstar; forward_procedure(); backward_procedure(); viterbi(); //printing in log file fprintf(dig_dump, "iteration: %d\n", iteration); fprintf(dig_dump, "-->pstar : %g\n", pstar); fprintf(dig_dump, "-->qstar : "); for(int i=1; i<=T; i++){ fprintf(dig_dump, "%d ", Q[i]); } fprintf(dig_dump, "\n"); calculate_xi(); calculate_gamma(); //cout<<"difference: "<<prev_p_star - pstar<<endl; reevaluate_model_parameters(); } //writing final state sequence fprintf(common_dump, "-->qstar : "); for(int i=1; i<=T; i++){ fprintf(common_dump, "%d ", Q[i]); } fprintf(common_dump, "\n"); //writing final model in the log file fprintf(dig_dump, "-------------------------------Final Model Lambda (Pi, A, B) after iterations %d--------------------------------\n", iteration); fprintf(common_dump, "-------------------------------Final Model Lambda (Pi, A, B) after iterations %d--------------------------------\n", iteration); dump_converged_model(dig_dump); dump_converged_model(common_dump); add_to_avg_model(); dump_final_model(u, d); } fclose(dig_dump); average_of_avg_model(total_files_trained); dump_avg_model(d); erase_avg_model(); //system("pause"); } train++; } //TO READ CODEBOOK FROM FILE void read_codebook(){ ifstream in("new_codebook.txt"); for (int i = 0; i < CB_SIZE; i++){ for (int j = 0; j < P; j++){ in >> codeBook[i][j]; } } in.close(); } //runs prediction by loading the model and running solution to prob1 void test_prediction(){ test_ans = 0; max_pobs_model = 0; int total_words = sizeof(keywords)/sizeof(keywords[0]); //checking for all the models for(int k = 0; k<total_words; k++){ if(next_prob_word[k] == 1){ read_average_model(k); solution_to_prob1(k); } } printf("Detected word %s\n", keywords[test_ans]); char correct; printf("Is it correct? (y/n): "); cin>>correct; if(correct == 'y') perform(test_ans); else printf("Sorry!\n"); } //performs live prediction of the data void live_testing(){ char obs_file[100], line[100]; printf("\n----------Live testing----------\n"); system("Recording_Module.exe 3 input.wav input_file.txt"); initialize_model(0, 0, "--"); FILE *f = fopen("input_file.txt", "r"); if(f == NULL){ printf("Issue in opening file input_file.txt"); exit(1); } //setting dcshift and nfactor setupGlobal("input_file.txt"); sSize = 0; //reading the samples and normalizing them while(!feof(f)){ fgets(line, 100, f); //input file may contain header, so we skip it if(!isalpha(line[0])){ int y = atof(line); double normalizedX = floor((y-dcShift)*nFactor); //if(abs(normalizedX) > 1) sample[sSize++] = normalizedX; } } fclose(f); generate_obs_sequence("output/live_test/obs_seq.txt"); test_prediction(); } //print alpha beta gamma on screen void print(){ cout<<"Alpha values - \n"; for(int i = 1; i<=T; i++){ for(int j = 1; j<=N; j++){ cout<<Alpha[i][j]<<" "; } cout<<endl; } cout<<"Beta values -\n"; for(int i = 1; i<=T; i++){ for(int j = 1; j<=N; j++){ cout<<Beta[i][j]<<" "; } cout<<endl; } cout<<"Gamma values -\n"; for(int i = 1; i<=T; i++){ for(int j = 1; j<=N; j++){ cout<<Gamma[i][j]<<" "; } cout<<endl; } } //function to validate output each model void validation(){ char filename[100], line[100]; initialize_model(1, 0); int iteration = 0; ofstream dump("dump.txt"); ////////////////////////////////Block to use sir's data///////////////////////////////////// // ifstream fin("validation/Digit 1/obs_seq_1.txt"); // int temp; // int obs_ind = 1; // while(fin >> temp){ // O[obs_ind] = temp; // for(int i=2; i<=85; i++){ // fin>>temp; // O[i] = temp; // } // break; // } // cout<<"Observation seq\n"; // for(int i=1; i<=85; i++){ // cout<<O[i]<<" "; // } // cout<<endl; /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////Block to use own recordings ////////////////////////////////// sprintf(filename, "input/recordings/Digit 0/rec_1.txt"); FILE *f = fopen(filename, "r"); if(f == NULL){ printf("Issue in opening file %s", filename); exit(1); } //setting dcshift and nfactor setupGlobal(filename); sSize = 0; //reading the samples and normalizing them while(!feof(f)){ fgets(line, 100, f); //input file may contain header, so we skip it if(!isalpha(line[0])){ int y = atof(line); double normalizedX = floor((y-dcShift)*nFactor); //if(abs(normalizedX) > 1) sample[sSize++] = normalizedX; } } fclose(f); char obs_file[100]; sprintf(obs_file, "output/delete/HMM_OBS_SEQ_delete.txt"); generate_obs_sequence(obs_file); /////////////////////////////////////////////////////////////////////////////////////////// //convergence of the model while(pstar > prev_p_star){ //cout<<"iteration: "<<iteration++<<endl; iteration++; prev_p_star = pstar; forward_procedure(0); backward_procedure(); viterbi(); dump<<"Pstar: "<<pstar<<endl; dump<<"Qstar: "; for(int i=1; i<=T; i++){ dump<<Q[i]<<" "; } dump<<endl; calculate_xi(); calculate_gamma(); cout<<"difference: "<<prev_p_star - pstar<<endl; reevaluate_model_parameters(); } cout<<"Output converged on iteration: "<<iteration<<endl; dump<<"Output converged on iteration: "<<iteration<<endl; dump<<"----------------------Alpha values--------------------------\n"; for(int i = 1; i<=T; i++){ for(int j = 1; j<=N; j++){ dump<<Alpha[i][j]<<" "; } dump<<endl; } dump<<"------------------------Beta values--------------------------\n"; for(int i = 1; i<=T; i++){ for(int j = 1; j<=N; j++){ dump<<Beta[i][j]<<" "; } dump<<endl; } dump<<"-----------------------------Gamma values----------------------\n"; for(int i = 1; i<=T; i++){ for(int j = 1; j<=N; j++){ dump<<Gamma[i][j]<<" "; } dump<<endl; } dump<<"------------------------------Xi values ------------------------\n"; for(int i=1; i<=T; i++){ for(int j = 1; j<=N; j++){ for(int k = 1; k<=N; k++){ dump<<Xi[i][j][k]<<" "; } dump<<endl; } dump<<"---\n\n"; } dump<<"------------------------------Model ----------------------------\n"; dump<<"------------------------------A matrix --------------------------\n"; for (int i = 1; i <= N; i++){ for (int j = 1; j <= N; j++){ dump << A[i][j] << " "; } dump<<endl; } dump<<"------------------------------B matrix ----------------------------\n"; for (int i = 1; i <= N; i++){ for (int j = 1; j <= M; j++){ dump << B[i][j] << " "; } dump<<endl; } dump<<"------------------------------Pi matrix ----------------------------\n"; for (int i = 1; i <= N; i++){ dump<<Pi[i]<<" "; } } //function to test the models void testing(){ char filename[100], line[100], test_file[100]; int correctAns = 0, totalCorrectAns = 0; int total_words = sizeof(keywords)/sizeof(keywords[0]); for(int d = 0; d<total_words; d++){ sprintf(test_file, "results/testing/offline/offline_testing_word_%s.txt", keywords[d]); FILE *fp = fopen(test_file, "w"); correctAns = 0; fprintf(fp, "--------------------------------------------* Word %s *--------------------------------------------------------\n", keywords[d]); for(int j = 41; j<=45; j++){ sprintf(filename, "input/recordings/%s/rec_%d.txt", keywords[d], j); printf("\n\n--------Reading input from the file: %s------\n", filename); FILE *f = fopen(filename, "r"); if(f == NULL){ printf("Issue in opening file input_file.txt"); exit(1); } fprintf(fp, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n"); fprintf(fp, "\n---------> Reading file %s <---------\n", filename); //setting dcshift and nfactor setupGlobal(filename); sSize = 0; //reading the samples and normalizing them while(!feof(f)){ fgets(line, 100, f); //input file may contain header, so we skip it if(!isalpha(line[0])){ int y = atof(line); double normalizedX = floor((y-dcShift)*nFactor); sample[sSize++] = normalizedX; } } fclose(f); //generating observation sequence generate_obs_sequence("output/live_test/obs_seq.txt"); fprintf(fp, "observation seq obtained -- "); for(int i=1; i<=T; i++){ fprintf(fp, "%d\t", O[i]); } fprintf(fp, "\n"); test_ans = 0; max_pobs_model = 0; for(int k = 0; k<total_words; k++){ //if(next_prob_word[k] == 1){ read_average_model_for_testing(k); solution_to_prob1(k); erase_avg_model(); //} } printf("\nPredicted utterance: %s\n", keywords[test_ans]); printf("Actual utterance: %s\n", keywords[d]); fprintf(fp, "Predicted utterance: %s\n", keywords[test_ans]); fprintf(fp, "Actual utterance: %s\n", keywords[d]); if(test_ans == d) correctAns++, totalCorrectAns++; } printf("Accuracy for the word %s is : %lf % \n", keywords[d], (correctAns / 5.0f)*100); fprintf(fp, "Accuracy for the word %s is : %lf % \n", keywords[d], (correctAns / 5.0f)*100); //system("pause"); fclose(fp); } printf("Accuracy of the system: %lf %\n\n", (totalCorrectAns/80.0f)*100); } //testing particular file only void test_file(char *filename, char *test){ char line[100], test_file[100]; int correctAns = 0, totalCorrectAns = 0; int total_words = sizeof(keywords)/sizeof(keywords[0]); sprintf(test_file, "results/testing/offline/%s.txt", test); FILE *fp = fopen(test_file, "w"); printf("\n\n--------Reading input from the file: %s------\n", filename); FILE *f = fopen(filename, "r"); if(f == NULL){ printf("Issue in opening file input_file.txt or file does not exist\n"); exit(1); } fprintf(fp, "\n---------> Reading file %s <---------\n", filename); //setting dcshift and nfactor setupGlobal(filename); sSize = 0; //reading the samples and normalizing them while(!feof(f)){ fgets(line, 100, f); //input file may contain header, so we skip it if(!isalpha(line[0])){ int y = atof(line); double normalizedX = floor((y-dcShift)*nFactor); sample[sSize++] = normalizedX; } } fclose(f); //generating observation sequence generate_obs_sequence("results/testing/offline/manual_test_obs_seq.txt"); fprintf(fp, "observation seq obtained -- "); for(int i=1; i<=T; i++){ fprintf(fp, "%d\t", O[i]); } fprintf(fp, "\n"); test_ans = 0; max_pobs_model = 0; for(int k = 0; k<total_words; k++){ read_average_model(k); solution_to_prob1(k, fp); erase_avg_model(); } printf("\nPredicted utterance: %d\n", test_ans); fprintf(fp, "Predicted utterance: %d\n", test_ans); fclose(fp); } //live training of a word void live_training(int choice){ //itr_count will keep track of no of times a particular word is recorded as part of live training. int itr_count=10; int listen=0; printf("---------------------------Live Training Module----------------------------------\n"); printf("Now you'll be asked to record your voice for %d times\n",itr_count); system("pause"); //Giving option for user. //printf("Enter 1 to listen training audio else enter 2\n"); //scanf("%d",&listen); for(int i=1; i<=itr_count; i++){ char command[500], filename[50], obs_file[100], line[50]; char save='a', save_file[100]=""; cout<<"Press s for saving training data else enter n"<<endl; cin>>save; //Will save the live training data. if(save=='s'||save=='S'){ cout<<"Enter file name to be saved"<<endl; cin>>save_file; sprintf(filename,"input/live_training/"); strcat(filename,save_file); strcat(filename,".txt"); sprintf(command, " Recording_Module.exe 3 o.wav "); strcat(command, filename); system(command); } else{ sprintf(filename, "input/live_training/rec_%d.txt" , i); sprintf(command, " Recording_Module.exe 3 input.wav "); strcat(command, filename); system(command); } //Will playback the audio. //if(listen==1) //bool played= PlaySound("input.wav", NULL, SND_SYNC); FILE *f = fopen(filename, "r"); if(f == NULL){ printf("Issue in opening file %s", filename); exit(1); } //setting dcshift and nfactor setupGlobal(filename); sSize = 0; //reading the samples and normalizing them while(!feof(f)){ fgets(line, 100, f); //input file may contain header, so we skip it if(!isalpha(line[0])){ int y = atof(line); double normalizedX = floor((y-dcShift)*nFactor); //if(abs(normalizedX) > 1) sample[sSize++] = normalizedX; } } fclose(f); //framing sprintf(obs_file, "output/obs_seq/HMM_OBS_SEQ_%s_%d.txt", keywords[choice], i); generate_obs_sequence(obs_file); initialize_model(choice, 1, "--"); int iteration = 1; //starts converging model upto CONVERGE_ITERATIONS or till convergence whichever reach early pstar = 0, prev_p_star = -1; while(pstar > prev_p_star && iteration < 1000){ //cout<<"iteration: "<<iteration++<<endl; iteration++; prev_p_star = pstar; forward_procedure(); backward_procedure(); viterbi(); calculate_xi(); calculate_gamma(); //cout<<"difference: "<<prev_p_star - pstar<<endl; reevaluate_model_parameters(); } add_to_avg_model(); dump_final_model(i, choice); } average_of_avg_model(itr_count); dump_avg_model_live(choice); //check here erase_avg_model(); } //driver function int _tmain(int argc, _TCHAR* argv[]){ uni.open("universe.csv"); char com_dump[100]; sprintf(com_dump, "results/training/common_dump.txt"); common_dump = fopen(com_dump, "w"); read_codebook(); for(int i=0; i<16; i++){ if(i == 1 || i == 3 || i==2 || i==6 || i==14) next_prob_word[i] = 0; else next_prob_word[i] = 1; } //training(); char choice; while(1){ cout<<"\nPress 1. for automated test on test files\nPress 2. for manual test using the file\nPress 3. for live testing\nPress 4. for live training\nPress 0. to exit\nEnter your choice: "; cin>>choice; switch(choice){ case 't': { for(int i=0; i<3; i++) training(); break; } case '1': { testing(); break; } case '2': { char filename[100], test[100], test_fn[100]; printf("Make sure file is available in input/manual_testing/ folder and write .txt (extension in the input)\nEnter the filename you want to test - "); scanf("%s", &test_fn); sprintf(filename, "input/manual_testing/%s", test_fn); printf("Enter the filename to store the results in - "); scanf("%s", &test); test_file(filename, test); break; } case '3': { if(environment_known == 0){ printf("--------------Recording silence--------------\n"); system("Recording_Module.exe 3 silence.wav silence_file.txt"); environment_known = 1; } is_live_testing = 1; live_testing(); is_live_testing = 0; break; } case '4': { if(environment_known == 0){ printf("--------------Recording silence--------------\n"); system("Recording_Module.exe 1 silence.wav silence_file.txt"); environment_known = 1; } int choice; cout<<endl; for(int i=0;i<16;i++){ cout<<"Enter "<<i+1<<" for training "<<keywords[i]<<endl; } cout<<"Enter your choice: "; cin>>choice; choice--; live_training(choice); break; } case '0': { cout<<"Exiting the program\n"; return 0; } } } uni.close(); return 0; }
/* * Copyright (C) 2017 The Android Open Source Project * * 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 <string.h> #include <initializer_list> #include <random> #include <sstream> #include <vector> #include "perfetto/ext/base/utils.h" #include "perfetto/ext/tracing/core/basic_types.h" #include "perfetto/ext/tracing/core/shared_memory_abi.h" #include "perfetto/ext/tracing/core/trace_packet.h" #include "perfetto/protozero/proto_utils.h" #include "src/tracing/core/trace_buffer.h" #include "src/tracing/test/fake_packet.h" #include "test/gtest_and_gmock.h" namespace perfetto { using ::testing::ContainerEq; using ::testing::ElementsAre; using ::testing::IsEmpty; class TraceBufferTest : public testing::Test { public: using SequenceIterator = TraceBuffer::SequenceIterator; using ChunkMetaKey = TraceBuffer::ChunkMeta::Key; using ChunkRecord = TraceBuffer::ChunkRecord; static constexpr uint8_t kContFromPrevChunk = SharedMemoryABI::ChunkHeader::kFirstPacketContinuesFromPrevChunk; static constexpr uint8_t kContOnNextChunk = SharedMemoryABI::ChunkHeader::kLastPacketContinuesOnNextChunk; static constexpr uint8_t kChunkNeedsPatching = SharedMemoryABI::ChunkHeader::kChunkNeedsPatching; FakeChunk CreateChunk(ProducerID p, WriterID w, ChunkID c) { return FakeChunk(trace_buffer_.get(), p, w, c); } void ResetBuffer( size_t size_, TraceBuffer::OverwritePolicy policy = TraceBuffer::kOverwrite) { trace_buffer_ = TraceBuffer::Create(size_, policy); ASSERT_TRUE(trace_buffer_); } bool TryPatchChunkContents(ProducerID p, WriterID w, ChunkID c, std::vector<TraceBuffer::Patch> patches, bool other_patches_pending = false) { return trace_buffer_->TryPatchChunkContents( p, w, c, patches.data(), patches.size(), other_patches_pending); } std::vector<FakePacketFragment> ReadPacket( TraceBuffer::PacketSequenceProperties* sequence_properties = nullptr, bool* previous_packet_dropped = nullptr) { std::vector<FakePacketFragment> fragments; TracePacket packet; TraceBuffer::PacketSequenceProperties ignored_sequence_properties{}; bool ignored_previous_packet_dropped; if (!trace_buffer_->ReadNextTracePacket( &packet, sequence_properties ? sequence_properties : &ignored_sequence_properties, previous_packet_dropped ? previous_packet_dropped : &ignored_previous_packet_dropped)) { return fragments; } for (const Slice& slice : packet.slices()) fragments.emplace_back(slice.start, slice.size); return fragments; } void AppendChunks( std::initializer_list<std::tuple<ProducerID, WriterID, ChunkID>> chunks) { for (const auto& c : chunks) { char seed = static_cast<char>(std::get<0>(c) + std::get<1>(c) + std::get<2>(c)); CreateChunk(std::get<0>(c), std::get<1>(c), std::get<2>(c)) .AddPacket(4, seed) .CopyIntoTraceBuffer(); } } bool IteratorSeqEq(ProducerID p, WriterID w, std::initializer_list<ChunkID> chunk_ids) { std::stringstream expected_seq; for (const auto& c : chunk_ids) expected_seq << "{" << p << "," << w << "," << c << "},"; std::stringstream actual_seq; for (auto it = GetReadIterForSequence(p, w); it.is_valid(); it.MoveNext()) { actual_seq << "{" << it.producer_id() << "," << it.writer_id() << "," << it.chunk_id() << "},"; } std::string expected_seq_str = expected_seq.str(); std::string actual_seq_str = actual_seq.str(); EXPECT_EQ(expected_seq_str, actual_seq_str); return expected_seq_str == actual_seq_str; } SequenceIterator GetReadIterForSequence(ProducerID p, WriterID w) { TraceBuffer::ChunkMeta::Key key(p, w, 0); return trace_buffer_->GetReadIterForSequence( trace_buffer_->index_.lower_bound(key)); } void SuppressSanityDchecksForTesting() { trace_buffer_->suppress_sanity_dchecks_for_testing_ = true; } std::vector<ChunkMetaKey> GetIndex() { std::vector<ChunkMetaKey> keys; keys.reserve(trace_buffer_->index_.size()); for (const auto& it : trace_buffer_->index_) keys.push_back(it.first); return keys; } TraceBuffer* trace_buffer() { return trace_buffer_.get(); } size_t size_to_end() { return trace_buffer_->size_to_end(); } private: std::unique_ptr<TraceBuffer> trace_buffer_; }; // ---------------------- // Main TraceBuffer tests // ---------------------- // Note for the test code: remember that the resulting size of a chunk is: // SUM(packets) + 16 (that is sizeof(ChunkRecord)). // Also remember that chunks are rounded up to 16. So, unless we are testing the // rounding logic, might be a good idea to create chunks of that size. TEST_F(TraceBufferTest, ReadWrite_EmptyBuffer) { ResetBuffer(4096); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); } // On each iteration writes a fixed-size chunk and reads it back. TEST_F(TraceBufferTest, ReadWrite_Simple) { ResetBuffer(64 * 1024); for (ChunkID chunk_id = 0; chunk_id < 1000; chunk_id++) { char seed = static_cast<char>(chunk_id); CreateChunk(ProducerID(1), WriterID(1), chunk_id) .AddPacket(42, seed) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(42, seed))); ASSERT_THAT(ReadPacket(), IsEmpty()); EXPECT_EQ(chunk_id + 1u, trace_buffer()->stats().chunks_written()); EXPECT_EQ(trace_buffer()->stats().chunks_written(), trace_buffer()->stats().chunks_read()); EXPECT_LT(0u, trace_buffer()->stats().bytes_written()); EXPECT_EQ(trace_buffer()->stats().bytes_written(), trace_buffer()->stats().bytes_read()); EXPECT_EQ(0u, trace_buffer()->stats().padding_bytes_written()); EXPECT_EQ(0u, trace_buffer()->stats().padding_bytes_cleared()); } } TEST_F(TraceBufferTest, ReadWrite_OneChunkPerWriter) { for (int8_t num_writers = 1; num_writers <= 10; num_writers++) { ResetBuffer(4096); for (char i = 1; i <= num_writers; i++) { ASSERT_EQ(32u, CreateChunk(ProducerID(i), WriterID(i), ChunkID(i)) .AddPacket(32 - 16, i) .CopyIntoTraceBuffer()); } // The expected read sequence now is: c3, c4, c5. trace_buffer()->BeginRead(); for (char i = 1; i <= num_writers; i++) ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(32 - 16, i))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // for(num_writers) } // Writes chunk that up filling the buffer precisely until the end, like this: // [ c0: 512 ][ c1: 512 ][ c2: 1024 ][ c3: 2048 ] // | ---------------- 4k buffer --------------- | TEST_F(TraceBufferTest, ReadWrite_FillTillEnd) { ResetBuffer(4096); for (int i = 0; i < 3; i++) { ASSERT_EQ(512u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(i * 4)) .AddPacket(512 - 16, 'a') .CopyIntoTraceBuffer()); ASSERT_EQ(512u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(i * 4 + 1)) .AddPacket(512 - 16, 'b') .CopyIntoTraceBuffer()); ASSERT_EQ(1024u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(i * 4 + 2)) .AddPacket(1024 - 16, 'c') .CopyIntoTraceBuffer()); ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(i * 4 + 3)) .AddPacket(2048 - 16, 'd') .CopyIntoTraceBuffer()); // At this point the write pointer should have been reset at the beginning. ASSERT_EQ(4096u, size_to_end()); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(512 - 16, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(512 - 16, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(1024 - 16, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(2048 - 16, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } } // Similar to the above, but this time leaves some gap at the end and then // tries to add a chunk that doesn't fit to exercise the padding-at-end logic. // Initial condition: // [ c0: 128 ][ c1: 256 ][ c2: 512 ][ c3: 1024 ][ c4: 2048 ]{ 128 padding } // | ------------------------------- 4k buffer ------------------------------ | // // At this point we try to insert a 512 Bytes chunk (c5). The result should be: // [ c5: 512 ]{ padding }[c3: 1024 ][ c4: 2048 ]{ 128 padding } // | ------------------------------- 4k buffer ------------------------------ | TEST_F(TraceBufferTest, ReadWrite_Padding) { ResetBuffer(4096); ASSERT_EQ(128u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(128 - 16, 'a') .CopyIntoTraceBuffer()); ASSERT_EQ(256u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(256 - 16, 'b') .CopyIntoTraceBuffer()); ASSERT_EQ(512u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(512 - 16, 'c') .CopyIntoTraceBuffer()); ASSERT_EQ(1024u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .AddPacket(1024 - 16, 'd') .CopyIntoTraceBuffer()); ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(4)) .AddPacket(2048 - 16, 'e') .CopyIntoTraceBuffer()); // Now write c5 that will cause wrapping + padding. ASSERT_EQ(128u, size_to_end()); ASSERT_EQ(512u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(5)) .AddPacket(512 - 16, 'f') .CopyIntoTraceBuffer()); ASSERT_EQ(4096u - 512, size_to_end()); // The expected read sequence now is: c3, c4, c5. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(1024 - 16, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(2048 - 16, 'e'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(512 - 16, 'f'))); ASSERT_THAT(ReadPacket(), IsEmpty()); EXPECT_EQ(6u, trace_buffer()->stats().chunks_written()); EXPECT_EQ(3u, trace_buffer()->stats().chunks_overwritten()); EXPECT_EQ(3u, trace_buffer()->stats().chunks_read()); EXPECT_EQ(4480u, trace_buffer()->stats().bytes_written()); EXPECT_EQ(896u, trace_buffer()->stats().bytes_overwritten()); EXPECT_EQ(3584u, trace_buffer()->stats().bytes_read()); EXPECT_EQ(512u, trace_buffer()->stats().padding_bytes_written()); EXPECT_EQ(0u, trace_buffer()->stats().padding_bytes_cleared()); // Adding another chunk should clear some of the padding. ASSERT_EQ(128u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(6)) .AddPacket(128 - 16, 'g') .CopyIntoTraceBuffer()); EXPECT_EQ(384u, trace_buffer()->stats().padding_bytes_cleared()); } // Like ReadWrite_Padding, but this time the padding introduced is the minimum // allowed (16 bytes). This is to exercise edge cases in the padding logic. // [c0: 2048 ][c1: 1024 ][c2: 1008 ][c3: 16] // [c4: 2032 ][c5: 1040 ][c6 :16][c7: 1080 ] TEST_F(TraceBufferTest, ReadWrite_MinimalPadding) { ResetBuffer(4096); ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(2048 - 16, 'a') .CopyIntoTraceBuffer()); ASSERT_EQ(1024u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(1024 - 16, 'b') .CopyIntoTraceBuffer()); ASSERT_EQ(1008u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(1008 - 16, 'c') .CopyIntoTraceBuffer()); ASSERT_EQ(16u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .CopyIntoTraceBuffer()); ASSERT_EQ(4096u, size_to_end()); ASSERT_EQ(2032u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(4)) .AddPacket(2032 - 16, 'd') .CopyIntoTraceBuffer()); ASSERT_EQ(1040u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(5)) .AddPacket(1040 - 16, 'e') .CopyIntoTraceBuffer()); ASSERT_EQ(16u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(6)) .CopyIntoTraceBuffer()); ASSERT_EQ(1008u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(7)) .AddPacket(1008 - 16, 'f') .CopyIntoTraceBuffer()); ASSERT_EQ(4096u, size_to_end()); // The expected read sequence now is: c3, c4, c5. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(2032 - 16, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(1040 - 16, 'e'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(1008 - 16, 'f'))); for (int i = 0; i < 3; i++) ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, ReadWrite_RandomChunksNoWrapping) { for (unsigned int seed = 1; seed <= 32; seed++) { std::minstd_rand0 rnd_engine(seed); ResetBuffer(4096 * (1 + rnd_engine() % 32)); std::uniform_int_distribution<size_t> size_dist(18, 4096); std::uniform_int_distribution<ProducerID> prod_dist(1, kMaxProducerID); std::uniform_int_distribution<WriterID> wri_dist(1, kMaxWriterID); ChunkID chunk_id = 0; std::map<std::tuple<ProducerID, WriterID, ChunkID>, size_t> expected_chunks; for (;;) { const size_t chunk_size = size_dist(rnd_engine); if (base::AlignUp<16>(chunk_size) >= size_to_end()) break; ProducerID p = prod_dist(rnd_engine); WriterID w = wri_dist(rnd_engine); ChunkID c = chunk_id++; expected_chunks.emplace(std::make_tuple(p, w, c), chunk_size); ASSERT_EQ(chunk_size, CreateChunk(p, w, c) .AddPacket(chunk_size - 16, static_cast<char>(chunk_size)) .CopyIntoTraceBuffer()); } // for(;;) trace_buffer()->BeginRead(); for (const auto& it : expected_chunks) { const size_t chunk_size = it.second; ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment( chunk_size - 16, static_cast<char>(chunk_size)))); } ASSERT_THAT(ReadPacket(), IsEmpty()); } } // Tests the case of writing a chunk that leaves just sizeof(ChunkRecord) at // the end of the buffer. TEST_F(TraceBufferTest, ReadWrite_WrappingCases) { ResetBuffer(4096); ASSERT_EQ(4080u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(4080 - 16, 'a') .CopyIntoTraceBuffer()); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4080 - 16, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); ASSERT_EQ(16u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .CopyIntoTraceBuffer()); ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(2048 - 16, 'b') .CopyIntoTraceBuffer()); ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .AddPacket(2048 - 16, 'c') .CopyIntoTraceBuffer()); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(2048 - 16, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(2048 - 16, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Tests that when records are removed when adding padding at the end because // there is no space left. The scenario is the following: // Initial condition: [ c0: 2048 ][ c1: 2048 ] // 2nd iteration: [ c2: 2048] <-- write pointer is here // At this point we try to add a 3072 bytes chunk. It won't fit because the // space left till the end is just 2048 bytes. At this point we expect that a // padding record is added in place of c1, and c1 is removed from the index. // Final situation: [ c3: 3072 ][ PAD ] TEST_F(TraceBufferTest, ReadWrite_PaddingAtEndUpdatesIndex) { ResetBuffer(4096); // Setup initial condition: [ c0: 2048 ][ c1: 2048 ] ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(2048 - 16, 'a') .CopyIntoTraceBuffer()); ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(2048 - 16, 'b') .CopyIntoTraceBuffer()); ASSERT_THAT(GetIndex(), ElementsAre(ChunkMetaKey(1, 1, 0), ChunkMetaKey(1, 1, 1))); // Wrap and get to this: [ c2: 2048] <-- write pointer is here ASSERT_EQ(2048u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(2048 - 16, 'c') .CopyIntoTraceBuffer()); ASSERT_EQ(2048u, size_to_end()); ASSERT_THAT(GetIndex(), ElementsAre(ChunkMetaKey(1, 1, 1), ChunkMetaKey(1, 1, 2))); // Force wrap because of lack of space and get: [ c3: 3072 ][ PAD ]. ASSERT_EQ(3072u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .AddPacket(3072 - 16, 'd') .CopyIntoTraceBuffer()); ASSERT_THAT(GetIndex(), ElementsAre(ChunkMetaKey(1, 1, 3))); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(3072 - 16, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Similar to ReadWrite_PaddingAtEndUpdatesIndex but makes it so that the // various chunks don't perfectly align when wrapping. TEST_F(TraceBufferTest, ReadWrite_PaddingAtEndUpdatesIndexMisaligned) { ResetBuffer(4096); // [c0: 512][c1: 512][c2: 512][c3: 512][c4: 512][c5: 512][c6: 512][c7: 512] for (char i = 0; i < 8; i++) { ASSERT_EQ(512u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(i)) .AddPacket(512 - 16, 'a' + i) .CopyIntoTraceBuffer()); } ASSERT_EQ(8u, GetIndex().size()); // [c8: 2080..........................][PAD][c5: 512][c6: 512][c7: 512] // ^ write pointer is here. ASSERT_EQ(2080u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(8)) .AddPacket(2080 - 16, 'i') .CopyIntoTraceBuffer()); ASSERT_EQ(2016u, size_to_end()); ASSERT_THAT(GetIndex(), ElementsAre(ChunkMetaKey(1, 1, 5), ChunkMetaKey(1, 1, 6), ChunkMetaKey(1, 1, 7), ChunkMetaKey(1, 1, 8))); // [ c9: 3104....................................][ PAD...............]. ASSERT_EQ(3104u, CreateChunk(ProducerID(1), WriterID(1), ChunkID(9)) .AddPacket(3104 - 16, 'j') .CopyIntoTraceBuffer()); ASSERT_THAT(GetIndex(), ElementsAre(ChunkMetaKey(1, 1, 9))); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(3104u - 16, 'j'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Verify that empty packets are skipped. TEST_F(TraceBufferTest, ReadWrite_EmptyPacket) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), 0) .AddPacket(42, 1) .AddPacket(1, 2) .AddPacket(42, 3) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(42, 1))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(42, 3))); ASSERT_THAT(ReadPacket(), IsEmpty()); EXPECT_EQ(0u, trace_buffer()->stats().abi_violations()); } // -------------------------------------- // Fragments stitching and skipping logic // -------------------------------------- TEST_F(TraceBufferTest, Fragments_Simple) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a', kContFromPrevChunk) .AddPacket(20, 'b') .AddPacket(30, 'c') .AddPacket(10, 'd', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(20, 'e', kContFromPrevChunk) .AddPacket(30, 'f') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); // The (10, 'a') entry should be skipped because we don't have provided the // previous chunk, hence should be treated as a data loss. ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'd'), FakePacketFragment(20, 'e'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'f'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Fragments_EdgeCases) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(2, 'a', kContFromPrevChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(2, 'b', kContOnNextChunk) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); // Now add the missing fragment. CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(2, 'c', kContFromPrevChunk) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(2, 'b'), FakePacketFragment(2, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // The following tests verify that chunks received out-of-order are read in the // correct order. // // Fragment order {0,2,1} for sequence {1,1}, without fragmenting packets. TEST_F(TraceBufferTest, Fragments_OutOfOrderLastChunkIsMiddle) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(30, 'c') .CopyIntoTraceBuffer(); EXPECT_EQ(0u, trace_buffer()->stats().chunks_committed_out_of_order()); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(20, 'b') .CopyIntoTraceBuffer(); EXPECT_EQ(1u, trace_buffer()->stats().chunks_committed_out_of_order()); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Fragment order {0,2,1} for sequence {1,1}, with fragmenting packets. TEST_F(TraceBufferTest, Fragments_OutOfOrderLastChunkIsMiddleFragmentation) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(30, 'c', kContFromPrevChunk) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(20, 'b', kContFromPrevChunk | kContOnNextChunk) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'), FakePacketFragment(20, 'b'), FakePacketFragment(30, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Fragment order {0,2,1,3} for sequence {1,1}, with fragmenting packets. Also // verifies that another sequence isn't broken. TEST_F(TraceBufferTest, Fragments_OutOfOrderLastChunkIsMaxFragmentation) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(30, 'c', kContFromPrevChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(2), ChunkID(0)) .AddPacket(10, 'd') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(20, 'b', kContFromPrevChunk | kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .AddPacket(40, 'd') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'), FakePacketFragment(20, 'b'), FakePacketFragment(30, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Fragment order {-2,1,-1,0} for sequence {1,1}, without fragmenting packets. TEST_F(TraceBufferTest, Fragments_OutOfOrderWithIdOverflowADCB) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(kMaxChunkID - 1)) .AddPacket(10, 'a') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(40, 'd') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(30, 'c') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(kMaxChunkID)) .AddPacket(20, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Fragment order {-2,0,-1,1} for sequence {1,1}, without fragmenting packets. TEST_F(TraceBufferTest, Fragments_OutOfOrderWithIdOverflowACBD) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(kMaxChunkID - 1)) .AddPacket(10, 'a') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(30, 'c') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(kMaxChunkID)) .AddPacket(20, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(40, 'd') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Fragments_EmptyChunkBefore) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)).CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(10, 'a') .AddPacket(20, 'b', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(30, 'c', kContFromPrevChunk) .AddPacket(40, 'd', kContOnNextChunk) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'b'), FakePacketFragment(30, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Fragments_EmptyChunkAfter) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .AddPacket(10, 'b', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)).CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Set up a fragmented packet that happens to also have an empty chunk in the // middle of the sequence. Test that it just gets skipped. TEST_F(TraceBufferTest, Fragments_EmptyChunkInTheMiddle) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)).CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(10, 'b', kContFromPrevChunk) .AddPacket(20, 'c') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'), FakePacketFragment(10, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Generates sequences of fragmented packets of increasing length (|seq_len|), // from [P0, P1a][P1y] to [P0, P1a][P1b][P1c]...[P1y]. Test that they are always // read as one packet. TEST_F(TraceBufferTest, Fragments_LongPackets) { for (unsigned seq_len = 1; seq_len <= 10; seq_len++) { ResetBuffer(4096); std::vector<FakePacketFragment> expected_fragments; expected_fragments.emplace_back(20, 'b'); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .AddPacket(20, 'b', kContOnNextChunk) .CopyIntoTraceBuffer(); for (unsigned i = 1; i <= seq_len; i++) { char prefix = 'b' + static_cast<char>(i); expected_fragments.emplace_back(20 + i, prefix); CreateChunk(ProducerID(1), WriterID(1), ChunkID(i)) .AddPacket(20 + i, prefix, kContFromPrevChunk | kContOnNextChunk) .CopyIntoTraceBuffer(); } expected_fragments.emplace_back(30, 'y'); CreateChunk(ProducerID(1), WriterID(1), ChunkID(seq_len + 1)) .AddPacket(30, 'y', kContFromPrevChunk) .AddPacket(50, 'z') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_THAT(ReadPacket(), ContainerEq(expected_fragments)); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'z'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } } // Similar to Fragments_LongPacket, but covers also the case of ChunkID wrapping // over its max value. TEST_F(TraceBufferTest, Fragments_LongPacketWithWrappingID) { ResetBuffer(4096); std::vector<FakePacketFragment> expected_fragments; for (ChunkID chunk_id = static_cast<ChunkID>(-2); chunk_id <= 2; chunk_id++) { char prefix = static_cast<char>('c' + chunk_id); expected_fragments.emplace_back(10 + chunk_id, prefix); CreateChunk(ProducerID(1), WriterID(1), chunk_id) .AddPacket(10 + chunk_id, prefix, kContOnNextChunk) .CopyIntoTraceBuffer(); } trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ContainerEq(expected_fragments)); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Fragments_PreserveUID) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .AddPacket(10, 'b', kContOnNextChunk) .SetUID(11) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(0)) .AddPacket(10, 'c') .AddPacket(10, 'd') .SetUID(22) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(10, 'e', kContFromPrevChunk) .AddPacket(10, 'f') .SetUID(11) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); TraceBuffer::PacketSequenceProperties sequence_properties; ASSERT_THAT(ReadPacket(&sequence_properties), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_EQ(11u, sequence_properties.producer_uid_trusted); ASSERT_THAT( ReadPacket(&sequence_properties), ElementsAre(FakePacketFragment(10, 'b'), FakePacketFragment(10, 'e'))); ASSERT_EQ(11u, sequence_properties.producer_uid_trusted); ASSERT_THAT(ReadPacket(&sequence_properties), ElementsAre(FakePacketFragment(10, 'f'))); ASSERT_EQ(11u, sequence_properties.producer_uid_trusted); ASSERT_THAT(ReadPacket(&sequence_properties), ElementsAre(FakePacketFragment(10, 'c'))); ASSERT_EQ(22u, sequence_properties.producer_uid_trusted); ASSERT_THAT(ReadPacket(&sequence_properties), ElementsAre(FakePacketFragment(10, 'd'))); ASSERT_EQ(22u, sequence_properties.producer_uid_trusted); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Fragments_DiscardedOnPacketSizeDropPacket) { ResetBuffer(4096); // Set up a fragmented packet in the first chunk, which continues in the // second chunk with kPacketSizeDropPacket size. The corrupted fragmented // packet should be skipped. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .AddPacket(10, 'b', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .SetFlags(kContFromPrevChunk) // Var-int encoded TraceWriterImpl::kPacketSizeDropPacket. .AddPacket({0xff, 0xff, 0xff, 0x7f}) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(10, 'd') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Fragments_IncompleteChunkNeedsPatching) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b', kContOnNextChunk | kChunkNeedsPatching) .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/false); trace_buffer()->BeginRead(); // First packet should be read even if the chunk's last packet still needs // patching. ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // -------------------------- // Out of band patching tests // -------------------------- TEST_F(TraceBufferTest, Patching_Simple) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(100, 'a') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(0)) .AddPacket(9, 'b') .ClearBytes(5, 4) // 5 := 4th payload byte. Byte 0 is the varint header. .CopyIntoTraceBuffer(); CreateChunk(ProducerID(3), WriterID(1), ChunkID(0)) .AddPacket(100, 'c') .CopyIntoTraceBuffer(); ASSERT_TRUE(TryPatchChunkContents(ProducerID(2), WriterID(1), ChunkID(0), {{5, {{'Y', 'M', 'C', 'A'}}}})); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment("b00-YMCA", 8))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Patching_SkipIfChunkDoesntExist) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(100, 'a') .CopyIntoTraceBuffer(); ASSERT_FALSE(TryPatchChunkContents(ProducerID(1), WriterID(2), ChunkID(0), {{0, {{'X', 'X', 'X', 'X'}}}})); ASSERT_FALSE(TryPatchChunkContents(ProducerID(1), WriterID(1), ChunkID(1), {{0, {{'X', 'X', 'X', 'X'}}}})); ASSERT_FALSE(TryPatchChunkContents(ProducerID(1), WriterID(1), ChunkID(-1), {{0, {{'X', 'X', 'X', 'X'}}}})); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Patching_AtBoundariesOfChunk) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(100, 'a', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(16, 'b', kContFromPrevChunk | kContOnNextChunk) .ClearBytes(1, 4) .ClearBytes(16 - 4, 4) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(100, 'c', kContFromPrevChunk) .CopyIntoTraceBuffer(); ASSERT_TRUE(TryPatchChunkContents( ProducerID(1), WriterID(1), ChunkID(1), {{1, {{'P', 'E', 'R', 'F'}}}, {16 - 4, {{'E', 'T', 'T', 'O'}}}})); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'a'), FakePacketFragment("PERFb01-b02ETTO", 15), FakePacketFragment(100, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Tests kChunkNeedsPatching logic: chunks that are marked as "pending patch" // should not be read until the patch has happened. TEST_F(TraceBufferTest, Patching_ReadWaitsForPatchComplete) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(16, 'a', kChunkNeedsPatching) .ClearBytes(1, 4) // 1 := 0th payload byte. Byte 0 is the varint header. .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(16, 'b') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(0)) .AddPacket(16, 'c') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(1)) .AddPacket(16, 'd', kChunkNeedsPatching) .ClearBytes(1, 4) // 1 := 0th payload byte. Byte 0 is the varint header. .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(2)) .AddPacket(16, 'e') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(3), WriterID(1), ChunkID(0)) .AddPacket(16, 'f', kChunkNeedsPatching) .ClearBytes(1, 8) // 1 := 0th payload byte. Byte 0 is the varint header. .CopyIntoTraceBuffer(); // The only thing that can be read right now is the 1st packet of the 2nd // sequence. All the rest is blocked waiting for patching. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(16, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); // Now patch the 2nd sequence and check that the sequence is unblocked. ASSERT_TRUE(TryPatchChunkContents(ProducerID(2), WriterID(1), ChunkID(1), {{1, {{'P', 'A', 'T', 'C'}}}})); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment("PATCd01-d02-d03", 15))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(16, 'e'))); ASSERT_THAT(ReadPacket(), IsEmpty()); // Now patch the 3rd sequence, but in the first patch set // |other_patches_pending| to true, so that the sequence is unblocked only // after the 2nd patch. ASSERT_TRUE(TryPatchChunkContents(ProducerID(3), WriterID(1), ChunkID(0), {{1, {{'P', 'E', 'R', 'F'}}}}, /*other_patches_pending=*/true)); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); ASSERT_TRUE(TryPatchChunkContents(ProducerID(3), WriterID(1), ChunkID(0), {{5, {{'E', 'T', 'T', 'O'}}}}, /*other_patches_pending=*/false)); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment("PERFETTOf02-f03", 15))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // namespace perfetto // --------------------- // Malicious input tests // --------------------- TEST_F(TraceBufferTest, Malicious_ZeroSizedChunk) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(32, 'a') .CopyIntoTraceBuffer(); uint8_t valid_ptr = 0; trace_buffer()->CopyChunkUntrusted( ProducerID(1), uid_t(0), WriterID(1), ChunkID(1), 1 /* num packets */, 0 /* flags */, true /* chunk_complete */, &valid_ptr, sizeof(valid_ptr)); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(32, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(32, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(32, 'b'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Attempting to write a chunk bigger than ChunkRecord::kMaxSize should end up // in a no-op. TEST_F(TraceBufferTest, Malicious_ChunkTooBig) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(4096, 'a') .AddPacket(2048, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Malicious_DeclareMorePacketsBeyondBoundaries) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(64, 'a') .IncrementNumPackets() .IncrementNumPackets() .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(2), ChunkID(0)) .IncrementNumPackets() .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(3), ChunkID(0)) .AddPacket(32, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(64, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(32, 'b'))); ASSERT_THAT(ReadPacket(), IsEmpty()); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Malicious_ZeroVarintHeader) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); // Create a standalone chunk where the varint header is == 0. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(4, 'a') .ClearBytes(0, 1) .AddPacket(4, 'b') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(0)) .AddPacket(4, 'c') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'c'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Forge a chunk where the first packet is valid but the second packet has a // varint header that continues beyond the end of the chunk (and also beyond the // end of the buffer). TEST_F(TraceBufferTest, Malicious_OverflowingVarintHeader) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(4079, 'a') // 4079 := 4096 - sizeof(ChunkRecord) - 1 .AddPacket({0x82}) // 0x8*: that the varint continues on the next byte. .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4079, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Malicious_VarintHeaderTooBig) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); // Add a valid chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(32, 'a') .CopyIntoTraceBuffer(); // Forge a packet which has a varint header that is just off by one. CreateChunk(ProducerID(2), WriterID(1), ChunkID(0)) .AddPacket({0x16, '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}) .CopyIntoTraceBuffer(); // Forge a packet which has a varint header that tries to hit an overflow. CreateChunk(ProducerID(3), WriterID(1), ChunkID(0)) .AddPacket({0xff, 0xff, 0xff, 0x7f}) .CopyIntoTraceBuffer(); // Forge a packet which has a jumbo varint header: 0xff, 0xff .. 0x7f. std::vector<uint8_t> chunk; chunk.insert(chunk.end(), 128 - sizeof(ChunkRecord), 0xff); chunk.back() = 0x7f; trace_buffer()->CopyChunkUntrusted( ProducerID(4), uid_t(0), WriterID(1), ChunkID(1), 1 /* num packets */, 0 /* flags*/, true /* chunk_complete */, chunk.data(), chunk.size()); // Add a valid chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(32, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(32, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(32, 'b'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Similar to Malicious_VarintHeaderTooBig, but this time the full chunk // contains an enormous varint number that tries to overflow. TEST_F(TraceBufferTest, Malicious_JumboVarint) { ResetBuffer(64 * 1024); SuppressSanityDchecksForTesting(); std::vector<uint8_t> chunk; chunk.insert(chunk.end(), 64 * 1024 - sizeof(ChunkRecord) * 2, 0xff); chunk.back() = 0x7f; for (int i = 0; i < 3; i++) { trace_buffer()->CopyChunkUntrusted( ProducerID(1), uid_t(0), WriterID(1), ChunkID(1), 1 /* num packets */, 0 /* flags */, true /* chunk_complete */, chunk.data(), chunk.size()); } trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Like the Malicious_ZeroVarintHeader, but put the chunk in the middle of a // sequence that would be otherwise valid. The zero-sized fragment should be // skipped. TEST_F(TraceBufferTest, Malicious_ZeroVarintHeaderInSequence) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(4, 'a', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(4, 'b', kContFromPrevChunk | kContOnNextChunk) .ClearBytes(0, 1) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(4, 'c', kContFromPrevChunk) .AddPacket(4, 'd') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .AddPacket(4, 'e') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(3)) .AddPacket(5, 'f') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'a'), FakePacketFragment(4, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'e'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(5, 'f'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // Similar to Malicious_ZeroVarintHeaderInSequence, but this time the zero-sized // fragment is the last fragment for a chunk and is marked for continuation. The // zero-sized fragment should be skipped. TEST_F(TraceBufferTest, Malicious_ZeroVarintHeaderAtEndOfChunk) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(4, 'a') .AddPacket(4, 'b', kContOnNextChunk) .ClearBytes(4, 4) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(4, 'c', kContFromPrevChunk) .AddPacket(4, 'd') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(4, 'e') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(3)) .AddPacket(4, 'f') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'e'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4, 'f'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Malicious_PatchOutOfBounds) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(2048, 'a') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(16, 'b') .CopyIntoTraceBuffer(); size_t offsets[] = {13, 16, size_t(-4), size_t(-8), size_t(-12), size_t(-16), size_t(-20), size_t(-32), size_t(-1024)}; for (size_t offset : offsets) { ASSERT_FALSE(TryPatchChunkContents(ProducerID(1), WriterID(1), ChunkID(1), {{offset, {{'0', 'd', 'a', 'y'}}}})); } } TEST_F(TraceBufferTest, Malicious_OverrideWithShorterChunkSize) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(2048, 'a') .CopyIntoTraceBuffer(); // The service should ignore this override of the chunk since the chunk size // is different. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(1024, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(2048, 'a'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Malicious_OverrideWithShorterChunkSizeAfterRead) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(30, 'a') .AddPacket(40, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'b'))); // The service should ignore this override of the chunk since the chunk size // is different. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .AddPacket(10, 'b') .AddPacket(10, 'c') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); // Test that the service didn't get stuck in some indeterminate state. // Writing a valid chunk with a larger ID should make things work again. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(10, 'd') .AddPacket(10, 'e') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'e'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Malicious_OverrideWithDifferentOffsetAfterRead) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(30, 'a') .AddPacket(40, 'b') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'b'))); // The attacker in this case speculates on the fact that the read pointer is // @ 70 which is >> the size of the new chunk we overwrite. // The service will not discard this override since the chunk size is correct. // However, it should detect that the packet headers at the current read // offset are invalid and skip the read of this chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .AddPacket(10, 'b') .AddPacket(10, 'c') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); // Test that the service didn't get stuck in some indeterminate state. // Writing a valid chunk with a larger ID should make things work again. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(10, 'd') .AddPacket(10, 'e') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(10, 'e'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // ------------------- // SequenceIterator tests // ------------------- TEST_F(TraceBufferTest, Iterator_OneStreamOrdered) { ResetBuffer(64 * 1024); AppendChunks({ {ProducerID(1), WriterID(1), ChunkID(0)}, {ProducerID(1), WriterID(1), ChunkID(1)}, {ProducerID(1), WriterID(1), ChunkID(2)}, {ProducerID(1), WriterID(1), ChunkID(5)}, {ProducerID(1), WriterID(1), ChunkID(6)}, {ProducerID(1), WriterID(1), ChunkID(7)}, }); ASSERT_TRUE(IteratorSeqEq(ProducerID(1), WriterID(2), {})); ASSERT_TRUE(IteratorSeqEq(ProducerID(-1), WriterID(-1), {})); ASSERT_TRUE(IteratorSeqEq(ProducerID(1), WriterID(1), {0, 1, 2})); } TEST_F(TraceBufferTest, Iterator_OneStreamWrapping) { ResetBuffer(64 * 1024); AppendChunks({ {ProducerID(1), WriterID(1), ChunkID(kMaxChunkID - 2)}, {ProducerID(1), WriterID(1), ChunkID(kMaxChunkID - 1)}, {ProducerID(1), WriterID(1), ChunkID(kMaxChunkID)}, {ProducerID(1), WriterID(1), ChunkID(0)}, {ProducerID(1), WriterID(1), ChunkID(1)}, {ProducerID(1), WriterID(1), ChunkID(2)}, }); ASSERT_TRUE(IteratorSeqEq(ProducerID(1), WriterID(2), {})); ASSERT_TRUE(IteratorSeqEq(ProducerID(-1), WriterID(-1), {})); ASSERT_TRUE( IteratorSeqEq(ProducerID(1), WriterID(1), {kMaxChunkID - 2, kMaxChunkID - 1, kMaxChunkID, 0, 1, 2})); } TEST_F(TraceBufferTest, Iterator_ManyStreamsOrdered) { ResetBuffer(64 * 1024); AppendChunks({ {ProducerID(1), WriterID(1), ChunkID(0)}, {ProducerID(1), WriterID(1), ChunkID(1)}, {ProducerID(1), WriterID(2), ChunkID(0)}, {ProducerID(3), WriterID(1), ChunkID(0)}, {ProducerID(1), WriterID(2), ChunkID(1)}, {ProducerID(1), WriterID(2), ChunkID(2)}, {ProducerID(3), WriterID(1), ChunkID(1)}, {ProducerID(1), WriterID(1), ChunkID(2)}, {ProducerID(3), WriterID(1), ChunkID(2)}, }); ASSERT_TRUE(IteratorSeqEq(ProducerID(1), WriterID(1), {0, 1, 2})); ASSERT_TRUE(IteratorSeqEq(ProducerID(1), WriterID(2), {0, 1, 2})); ASSERT_TRUE(IteratorSeqEq(ProducerID(3), WriterID(1), {0, 1, 2})); } TEST_F(TraceBufferTest, Iterator_ManyStreamsWrapping) { ResetBuffer(64 * 1024); auto Neg = [](int x) -> ChunkID { return kMaxChunkID + static_cast<ChunkID>(x) + 1; }; AppendChunks({ {ProducerID(1), WriterID(1), ChunkID(Neg(-2))}, {ProducerID(1), WriterID(1), ChunkID(Neg(-1))}, {ProducerID(1), WriterID(2), ChunkID(Neg(-1))}, {ProducerID(3), WriterID(1), ChunkID(Neg(-1))}, {ProducerID(1), WriterID(2), ChunkID(0)}, {ProducerID(1), WriterID(2), ChunkID(1)}, {ProducerID(3), WriterID(1), ChunkID(0)}, {ProducerID(1), WriterID(1), ChunkID(0)}, {ProducerID(3), WriterID(1), ChunkID(1)}, }); ASSERT_TRUE(IteratorSeqEq(ProducerID(1), WriterID(1), {Neg(-2), Neg(-1), 0})); ASSERT_TRUE(IteratorSeqEq(ProducerID(1), WriterID(2), {Neg(-1), 0, 1})); ASSERT_TRUE(IteratorSeqEq(ProducerID(3), WriterID(1), {Neg(-1), 0, 1})); } // ------------------- // Re-writing same chunk id // ------------------- TEST_F(TraceBufferTest, Override_ReCommitBeforeRead) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(100, 'a') .AddPacket(100, 'b') .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/false); EXPECT_EQ(0u, trace_buffer()->stats().chunks_rewritten()); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(100, 'a') .AddPacket(100, 'b') .AddPacket(100, 'c') .AddPacket(100, 'd') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); EXPECT_EQ(1u, trace_buffer()->stats().chunks_rewritten()); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(100, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Override_ReCommitAfterPartialRead) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/false); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .AddPacket(40, 'c') .AddPacket(50, 'd') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Override_ReCommitAfterFullRead) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); // Overriding a complete packet here would trigger a DCHECK because the packet // was already marked as complete. SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .AddPacket(40, 'c') .AddPacket(50, 'd') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } // See also the Malicious_Override* tests above. TEST_F(TraceBufferTest, Override_ReCommitInvalid) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(40, 'c') .AddPacket(50, 'd') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'))); // This should not happen when the producer behaves correctly, since it // shouldn't change the contents of chunk 0 after having allocated chunk 1. // // Since we've already started reading from chunk 1, TraceBuffer will // recognize this and discard the override. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'e') .AddPacket(60, 'f') .AddPacket(70, 'g') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Override_ReCommitReordered) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/false); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); // Recommit chunk 0 and add chunk 1, but do this out of order. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(50, 'd') .AddPacket(60, 'e') .PadTo(512) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .AddPacket(40, 'c') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(60, 'e'))); } TEST_F(TraceBufferTest, Override_ReCommitReorderedFragmenting) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/false); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); // Recommit chunk 0 and add chunk 1, but do this out of order. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(50, 'd', kContFromPrevChunk) .AddPacket(60, 'e') .PadTo(512) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .AddPacket(40, 'c', kContOnNextChunk) .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'), FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(60, 'e'))); } TEST_F(TraceBufferTest, Override_ReCommitSameBeforeRead) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(); // Commit again the same chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(); // Then write some new content in a new chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(40, 'c') .AddPacket(50, 'd') .PadTo(512) .CopyIntoTraceBuffer(); // The reader should keep reading from the new chunk. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Override_ReCommitSameAfterRead) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); // This re-commit should be ignored. We just re-committed an identical chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(); // Then write some new content in a new chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(40, 'c') .AddPacket(50, 'd') .PadTo(512) .CopyIntoTraceBuffer(); // The reader should keep reading from the new chunk. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Override_ReCommitIncompleteAfterReadOutOfOrder) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/false); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); // The last packet in an incomplete chunk should be ignored as the producer // may not have completed writing it. ASSERT_THAT(ReadPacket(), IsEmpty()); // Then write some new content in a new chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(40, 'c') .AddPacket(50, 'd') .PadTo(512) .CopyIntoTraceBuffer(); // The read still shouldn't be advancing past the incomplete chunk. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); // Recommit the original chunk with no changes but mark as complete. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b') .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/true); // Reading should resume from the now completed chunk. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(40, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, Override_ReCommitIncompleteFragmenting) { ResetBuffer(4096); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b', kContOnNextChunk) .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/false); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(20, 'a'))); // The last packet in an incomplete chunk should be ignored as the producer // may not have completed writing it. ASSERT_THAT(ReadPacket(), IsEmpty()); // Then write some new content in a new chunk. CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(40, 'c', kContFromPrevChunk) .AddPacket(50, 'd') .PadTo(512) .CopyIntoTraceBuffer(); // The read still shouldn't be advancing past the incomplete chunk. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); // Recommit the original chunk with no changes but mark as complete. CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(20, 'a') .AddPacket(30, 'b', kContOnNextChunk) .PadTo(512) .CopyIntoTraceBuffer(/*chunk_complete=*/true); // Reading should resume from the now completed chunk. trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(30, 'b'), FakePacketFragment(40, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(50, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, DiscardPolicy) { ResetBuffer(4096, TraceBuffer::kDiscard); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(96 - 16, 'a') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(4000 - 16, 'b') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(96 - 16, 'a'))); // As long as the reader catches up, writes should succeed. CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(48 - 16, 'c') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .AddPacket(48 - 16, 'd') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4000 - 16, 'b'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(48 - 16, 'c'))); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(48 - 16, 'd'))); ASSERT_THAT(ReadPacket(), IsEmpty()); // This will succeed. CreateChunk(ProducerID(1), WriterID(1), ChunkID(4)) .AddPacket(4000 - 16, 'e') .CopyIntoTraceBuffer(); // But this will fail, preventing any further write. for (int i = 0; i < 3; i++) { CreateChunk(ProducerID(1), WriterID(i + 2), ChunkID(0)) .AddPacket(120 - 16, 'X') .CopyIntoTraceBuffer(); } trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), ElementsAre(FakePacketFragment(4000 - 16, 'e'))); ASSERT_THAT(ReadPacket(), IsEmpty()); // Even after the reader catches up, writes should still be discarded. for (int i = 0; i < 3; i++) { CreateChunk(ProducerID(1), WriterID(i + 10), ChunkID(0)) .AddPacket(64 - 16, 'X') .CopyIntoTraceBuffer(); } trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(), IsEmpty()); } TEST_F(TraceBufferTest, MissingPacketsOnSequence) { ResetBuffer(4096); SuppressSanityDchecksForTesting(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(0)) .AddPacket(10, 'a') .AddPacket(10, 'b') .AddPacket(10, 'c', kContOnNextChunk) .CopyIntoTraceBuffer(); CreateChunk(ProducerID(2), WriterID(1), ChunkID(0)) .AddPacket(10, 'u') .AddPacket(10, 'v') .AddPacket(10, 'w') .ClearBytes(10, 1) // Clears the varint header of packet "v". .CopyIntoTraceBuffer(); bool previous_packet_dropped = false; trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'a'))); // First packet in first sequence, so previous one didn't exist. ASSERT_TRUE(previous_packet_dropped); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'b'))); // We read packet "a" before. ASSERT_FALSE(previous_packet_dropped); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'u'))); // First packet in second sequence, so previous one didn't exist. ASSERT_TRUE(previous_packet_dropped); // Packet "v" in second sequence is corrupted, so chunk will be skipped. ASSERT_THAT(ReadPacket(), IsEmpty()); CreateChunk(ProducerID(2), WriterID(1), ChunkID(1)) .AddPacket(10, 'x') .AddPacket(10, 'y') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(1)) .AddPacket(10, 'd', kContFromPrevChunk) .AddPacket(10, 'e') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT( ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'c'), FakePacketFragment(10, 'd'))); // We read packet "b" before. ASSERT_FALSE(previous_packet_dropped); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'e'))); // We read packet "d" before. ASSERT_FALSE(previous_packet_dropped); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'x'))); // We didn't read packets "v" and "w". ASSERT_TRUE(previous_packet_dropped); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'y'))); // We read packet "x". ASSERT_FALSE(previous_packet_dropped); ASSERT_THAT(ReadPacket(), IsEmpty()); // Write two large chunks that don't fit into the buffer at the same time. We // will drop the former one before we can read it. CreateChunk(ProducerID(1), WriterID(1), ChunkID(2)) .AddPacket(2000, 'f') .CopyIntoTraceBuffer(); CreateChunk(ProducerID(1), WriterID(1), ChunkID(3)) .AddPacket(3000, 'g') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(3000, 'g'))); // We didn't read packet "f". ASSERT_TRUE(previous_packet_dropped); CreateChunk(ProducerID(2), WriterID(1), ChunkID(2)) .AddPacket(10, 'z') .CopyIntoTraceBuffer(); trace_buffer()->BeginRead(); ASSERT_THAT(ReadPacket(nullptr, &previous_packet_dropped), ElementsAre(FakePacketFragment(10, 'z'))); // We've lost any state from the second producer's sequence because all its // previous chunks were removed from the buffer due to the two large chunks. // So the buffer can't be sure that no packets were dropped. ASSERT_TRUE(previous_packet_dropped); } // TODO(primiano): test stats(). // TODO(primiano): test multiple streams interleaved. // TODO(primiano): more testing on packet merging. } // namespace perfetto
#include <iostream> #include <queue> #include <vector> using namespace std; class Solution { public: int numIslands(vector<vector<char>>& grid) { if (grid.empty()) { return 0; } rows = grid.size(); cols = grid[0].size(); vector<vector<bool>> marked(rows, vector<bool>(cols, false)); int num_islands = 0; // BFS for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { if (marked[row][col]) { continue; } char current_tile_type; if (grid[row][col] == '1') { ++num_islands; current_tile_type = '1'; } else { current_tile_type = '0'; } marked[row][col] = true; queue<pair<int, int>> q; q.push({row, col}); while (!q.empty()) { pair<int, int> cur_pos = q.front(); q.pop(); for (auto neighbor : adj(cur_pos.first, cur_pos.second)) { if (!marked[neighbor.first][neighbor.second] && grid[neighbor.first][neighbor.second] == current_tile_type) { marked[neighbor.first][neighbor.second] = true; q.push({neighbor.first, neighbor.second}); } } } } } return num_islands; } private: int rows; int cols; vector<pair<int, int>> adj(int row, int col) { // Extreme case single tile grid if (cols == 1 && rows == 1) { return {}; } // Extreme case single row grid if (rows == 1) { // Left corner if (col == 0) { return {{row, col + 1}}; } // Right corner if (col == cols - 1) { return {{row, col - 1}}; } // Non corner return {{row, col - 1}, {row, col + 1}}; } // Extreme case single col grid if (cols == 1) { // Top corner if (row == 0) { return {{row + 1, col}}; } // Bottom corner if (row == rows - 1) { return {{row - 1, col}}; } // Non corner return {{row - 1, col}, {row + 1, col}}; } // Top row left corner if (row == 0 && col == 0) { return {{row, col + 1}, {row + 1, col}}; } // Top row right corner if (row == 0 && col == cols - 1) { return {{row, col - 1}, {row + 1, col}}; } // Top row non corner if (row == 0) { return {{row, col + 1}, {row, col - 1}, {row + 1, col}}; } // Bottom row left corner if (row == rows - 1 && col == 0) { return {{row, col + 1}, {row - 1, col}}; } // Bottom row right corner if (row == rows - 1 && col == cols - 1) { return {{row, col - 1}, {row - 1, col}}; } // Bottom row non corner if (row == rows - 1) { return {{row, col - 1}, {row, col + 1}, {row - 1, col}}; } // Left col non corner if (col == 0) { return {{row, col + 1}, {row - 1, col}, {row + 1, col}}; } // Right col non corner if (col == cols - 1) { return {{row, col - 1}, {row - 1, col}, {row + 1, col}}; } // Non edge return {{row - 1, col}, {row, col - 1}, {row, col + 1}, {row + 1, col}}; } }; int main() { Solution solution; vector<vector<char>> input; input = {{'1'}, {'0'}, {'1'}, {'0'}, {'1'}, {'1'}}; cout << "Meant to be 3: " << solution.numIslands(input) << endl; input = {{'1'}}; cout << solution.numIslands(input) << endl; input = {{'1', '1', '0', '1', '0'}}; // 2 cout << solution.numIslands(input) << endl; input = {{'1'}, {'1'}, {'0'}, {'1'}, {'0'}}; // 2 cout << solution.numIslands(input) << endl; input = {{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}}; // 1 cout << solution.numIslands(input) << endl; input = {{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}}; // 3 cout << solution.numIslands(input) << endl; }
#include "ZeloPreCompiledHeader.h" #include "skybox.h" SkyBox::SkyBox() { float side = 50.0f; float side2 = side / 2.0f; float v[24 * 3] = { // Front -side2, -side2, side2, side2, -side2, side2, side2, side2, side2, -side2, side2, side2, // Right side2, -side2, side2, side2, -side2, -side2, side2, side2, -side2, side2, side2, side2, // Back -side2, -side2, -side2, -side2, side2, -side2, side2, side2, -side2, side2, -side2, -side2, // Left -side2, -side2, side2, -side2, side2, side2, -side2, side2, -side2, -side2, -side2, -side2, // Bottom -side2, -side2, side2, -side2, -side2, -side2, side2, -side2, -side2, side2, -side2, side2, // Top -side2, side2, side2, side2, side2, side2, side2, side2, -side2, -side2, side2, -side2 }; GLuint el[] = { 0, 2, 1, 0, 3, 2, 4, 6, 5, 4, 7, 6, 8, 10, 9, 8, 11, 10, 12, 14, 13, 12, 15, 14, 16, 18, 17, 16, 19, 18, 20, 22, 21, 20, 23, 22 }; unsigned int handle[2]; glGenBuffers(2, handle); glBindBuffer(GL_ARRAY_BUFFER, handle[0]); glBufferData(GL_ARRAY_BUFFER, 24 * 3 * sizeof(float), v, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 36 * sizeof(GLuint), el, GL_STATIC_DRAW); glGenVertexArrays(1, &vaoHandle); glBindVertexArray(vaoHandle); glVertexAttribPointer((GLuint) 0, 3, GL_FLOAT, GL_FALSE, 0, ((GLubyte *) NULL + (0))); glEnableVertexAttribArray(0); // Vertex position glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle[1]); glBindVertexArray(0); } void SkyBox::render() const { glBindVertexArray(vaoHandle); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); }
/******************************************************************************/ // // DEVICE.CPP - Source code for the TSPIDevice class // // Copyright (C) 1994-2004 JulMar Entertainment Technology, Inc. // All rights reserved // // This file contains all the code for managing the device class which // encapsulates a TAPI SP device (managing lines and phones). // // This source code is intended only as a supplement to the // TSP++ Class Library product documentation. This source code cannot // be used in part or whole in any form outside the TSP++ library. // /******************************************************************************/ /*---------------------------------------------------------------------------*/ // INCLUDE FILES /*---------------------------------------------------------------------------*/ #include "stdafx.h" #include <process.h> #include <spbstrm.h> #include <stdexcept> #include "spacd.h" using std::runtime_error; /*---------------------------------------------------------------------------*/ // Agent capture points for debug entry /*---------------------------------------------------------------------------*/ extern "C" LONG TSPIAPI TSPI_lineSetAgentGroup(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTGROUPLIST const lpGroupList); extern "C" LONG TSPIAPI TSPI_lineSetAgentState(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, DWORD dwAgentState, DWORD dwNextAgentState); extern "C" LONG TSPIAPI TSPI_lineSetAgentActivity(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, DWORD dwActivityID); extern "C" LONG TSPIAPI TSPI_lineGetAgentStatus(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTSTATUS lpStatus); extern "C" LONG TSPIAPI TSPI_lineGetAgentCaps(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTCAPS lpCapabilities); extern "C" LONG TSPIAPI TSPI_lineGetAgentActivityList(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTACTIVITYLIST lpList); extern "C" LONG TSPIAPI TSPI_lineGetAgentGroupList(DWORD dwDeviceID, DWORD dwAddressID, LPLINEAGENTGROUPLIST lpList); extern "C" LONG TSPIAPI TSPI_lineAgentSpecific(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwAddressID, DWORD dwAgentExtensionID, LPVOID lpvParams, DWORD dwSize); extern "C" LONG TSPIAPI TSPI_lineCreateAgent(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, LPHAGENT lphAgent, LPCWSTR pszMachineName, LPCWSTR pszUserName, LPCWSTR pszAgentID, LPCWSTR pszAgentPIN); extern "C" LONG TSPIAPI TSPI_lineSetAgentMeasurementPeriod(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, HAGENT hAgent, DWORD dwMeasurementPeriod); extern "C" LONG TSPIAPI TSPI_lineGetAgentInfo(DWORD dwDeviceID, HAGENT hAgent, LPLINEAGENTINFO lpAgentInfo); extern "C" LONG TSPIAPI TSPI_lineCreateAgentSession(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, LPHAGENTSESSION lphSession, HAGENT hAgent, LPCWSTR pszAgentPIN, const GUID* pGUID, DWORD dwWorkingAddressID); extern "C" LONG TSPIAPI TSPI_lineGetAgentSessionList(DWORD dwDeviceID, HAGENT hAgent, LPLINEAGENTSESSIONLIST lpSessionList); extern "C" LONG TSPIAPI TSPI_lineSetAgentSessionState(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, HAGENTSESSION hSession, DWORD dwAgentSessionState, DWORD dwNextAgentSessionState); extern "C" LONG TSPIAPI TSPI_lineGetAgentSessionInfo(DWORD dwDeviceID, HAGENTSESSION hAgentSession, LPLINEAGENTSESSIONINFO lpSessionInfo); extern "C" LONG TSPIAPI TSPI_lineGetQueueList(DWORD dwDeviceID, const GUID* pGroupID, LPLINEQUEUELIST lpQueueList); extern "C" LONG TSPIAPI TSPI_lineSetQueueMeasurementPeriod(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, DWORD dwQueueID, DWORD dwMeasurementPeriod); extern "C" LONG TSPIAPI TSPI_lineGetQueueInfo(DWORD dwDeviceID, DWORD dwQueueID, LPLINEQUEUEINFO lpQueueInfo); extern "C" LONG TSPIAPI TSPI_lineGetGroupList(DWORD dwDeviceID, LPLINEAGENTGROUPLIST lpGroupList); extern "C" LONG TSPIAPI TSPI_lineSetAgentStateEx(DRV_REQUESTID dwRequestID, DWORD dwDeviceID, HAGENT hAgent, DWORD dwState, DWORD dwNextState); /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::CTSPIDevice // // Constructor // CTSPIDevice::CTSPIDevice() : CTSPIBaseObject(), m_dwProviderId(0xffffffff), m_lpfnCompletionProc(0), m_hProvider(0), m_hevtDeviceShutdown(0), m_dwIntervalTimeout(0), m_psmProxy(0), m_htIntervalTimer(0), m_htAgentProxy(0) { m_hevtDeviceShutdown = CreateEvent(NULL, TRUE, FALSE, NULL); m_hevtDeviceDeleted = CreateEvent(NULL, TRUE, FALSE, NULL); }// CTSPIDevice::CTSPIDevice /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::~CTSPIDevice // // Destructor for the device object. // // -- Clears all line objects // -- Waits on interval timer thread // -- Waits on agent proxy thread // CTSPIDevice::~CTSPIDevice() { // Tell any device threads to shutdown SetEvent(m_hevtDeviceShutdown); // Tell the interval timer thread to exit if it has been started. SetIntervalTimer(0); // Wait for our child threads to exit to ensure we don't delete the // device before all the threads are done accessing it. if (m_htIntervalTimer != NULL) { WaitForSingleObject(m_htIntervalTimer, INFINITE); CloseHandle(m_htIntervalTimer); } // Stop all agent proxy requests. if (m_htAgentProxy != NULL) { WaitForSingleObject(m_htAgentProxy, INFINITE); CloseHandle(m_htAgentProxy); } // Inform the service provider class that the device is now "deleted" // and that the processing of TSPI_providerShutdown can continue. CloseHandle(m_hevtDeviceShutdown); SetEvent(m_hevtDeviceDeleted); // CServiceProvider::providerShutdown closes the m_hevtDeviceDeleted // handle as it is potentially waiting on it now. }// CTSPIDevice::~CTSPIDevice /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::Init // // This initializer allocates all the connection information for // each phone/line available and sets up all the device information // for this device id. // bool CTSPIDevice::Init(DWORD dwProviderId, DWORD dwBaseLineId, DWORD dwBasePhoneId, DWORD dwNumLines, DWORD dwNumPhones, HPROVIDER hProvider, ASYNC_COMPLETION lpfnCompletion) { // Store all the information about this device. m_dwProviderId = dwProviderId; m_lpfnCompletionProc = lpfnCompletion; m_hProvider = hProvider; _TSP_DTRACE(_T("Device %lx, Base Line=%lx, Count=%lx, Base Phone=%lx, Count=%lx\n"), dwProviderId, dwBaseLineId, dwNumLines, dwBasePhoneId, dwNumPhones); _TSP_DTRACE(_T("Completion Callback function = %08lx\n"), lpfnCompletion); // Ask the derived provider for our registry stream object (v3.0b) TStream* pStream = AllocStream(); // If we are loading from the registry, then give the derived device object // an opportunity to load it's information from the registry. if (pStream != NULL) { try { if (!pStream->open()) SCHEMA_EXCEPT("bad stream"); read(*pStream); } catch (std::exception& e) { UNREFERENCED_PARAMETER(e); _TSP_DTRACE(TRC_WARNINGS, _T("Exception [%s] caught loading provider data from stream\n"), e.what()); delete pStream; return false; } // Load our line information unsigned int i; for (i = 0; i < dwNumLines; i++) { CTSPILineConnection* pLine = GetSP()->CreateLineObject(); AddLineConnectionInfo(pLine); _TSP_DTRACE(_T("Adding Line #%d (id %lx) to device list\n"), i+1, i+dwBaseLineId); pLine->InitWithStream(this, (i + dwBaseLineId), i, *pStream); #ifdef _DEBUG _TSP_DTRACEX(TRC_OBJECTS, _T("%s\n"), pLine->Dump().c_str()); #endif } // Load the phone information. for (i = 0; i < dwNumPhones; i++) { CTSPIPhoneConnection* pPhone = GetSP()->CreatePhoneObject(); AddPhoneConnectionInfo(pPhone); pPhone->InitWithStream(this, (i+dwBasePhoneId), i, *pStream); #ifdef _DEBUG _TSP_DTRACEX(TRC_OBJECTS, _T("%s\n"), pPhone->Dump().c_str()); #endif } LoadObjects(*pStream); pStream->close(); delete pStream; } // Otherwise the derived provider chose not to use the new registry // object storage facility - invoke the Init() method for normal creation. else { // Create a line connection for each listed line device. unsigned int i; for (i = 0; i < dwNumLines; i++) { CTSPILineConnection* pConn = GetSP()->CreateLineObject(); AddLineConnectionInfo (pConn); _TSP_DTRACE(_T("Adding Line #%d (id %lx) to device list\n"), i+1, i+dwBaseLineId); pConn->Init(this, i + dwBaseLineId, i); #ifdef _DEBUG _TSP_DTRACEX(TRC_OBJECTS, _T("%s\n"), pConn->Dump().c_str()); #endif } // Do the same for the phone objects for (i = 0; i < dwNumPhones; i++) { CTSPIPhoneConnection* pConn = GetSP()->CreatePhoneObject(); AddPhoneConnectionInfo(pConn); _TSP_DTRACE(_T("Adding Phone #%d (id %lx) to device list\n"), i+1, i+dwBasePhoneId); pConn->Init(this, i+dwBasePhoneId, i); #ifdef _DEBUG _TSP_DTRACEX(TRC_OBJECTS, _T("%s\n"), pConn->Dump().c_str()); #endif } } // Now that all lines and phones are initialized, run back through the list and // call the virtual function to create the "tapi/terminal" entries for each line // and phone device. for (unsigned i = 0; i < dwNumLines; i++) { CTSPILineConnection* pLine = GetLineConnectionInfo(i); if (pLine->GetTerminalCount() > 0 && pLine->GetDeviceClass(_T("tapi/terminal")) == NULL) pLine->CreateTapiTerminalDeviceClassInfo(); } return true; }// CTSPIDevice::Init /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::SetDeviceStatus // // This function changes the device status for all the lines associated // with the device. // void CTSPIDevice::SetDeviceStatus(bool fConnect) { // Mark each line as connected/disconnected based on our connection // to the hardware. unsigned int count = GetLineCount(); for (unsigned int i = 0; i < count; i++) { CTSPILineConnection* pLine = GetLineConnectionInfo(i); if (pLine != NULL) { pLine->DevStatusConnected(fConnect); pLine->DevStatusInService(fConnect); pLine->RecalcLineFeatures(true); } } }// CTSPIDevice::SetDeviceStatus /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::Save // // This function saves the state of the device and all child objects back // to the registry. It can be used to make changes to the device within // the TSP (for plug&play). // bool CTSPIDevice::Save() { // Ask the derived provider for our registry stream object (v3.0b) TStream* pStream = AllocStream(); // If we can save to the registry, then do so. if (pStream == NULL) return false; try { if (!pStream->open()) SCHEMA_EXCEPT("stream error"); write(*pStream); } catch (std::exception& e) { UNREFERENCED_PARAMETER(e); _TSP_DTRACE(TRC_WARNINGS, _T("Exception [%s] caught saving provider data to stream\n"), e.what()); delete pStream; return false; } // Save our line information int nCount = static_cast<int>(m_arrayLines.size()), i; for (i = 0; i < nCount; i++) m_arrayLines[i]->SaveToStream(*pStream); // Save the phone information. nCount = static_cast<int>(m_arrayPhones.size()); for (i = 0; i < nCount; ++i) m_arrayPhones[i]->SaveToStream(*pStream); // Now save the agent information and close the stream SaveObjects(*pStream); pStream->close(); delete pStream; return true; }// CTSPIDevice::Save /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::read // // Read an entry from the registry // TStream& CTSPIDevice::read(TStream& istm) { // Read and validate the provider ID stored in the stream. DWORD dwProviderID; istm >> dwProviderID; _TSP_ASSERTE(dwProviderID == m_dwProviderId); return istm; }// CTSPIDevice::read /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::write // // Writes the object to a stream // TStream& CTSPIDevice::write(TStream& ostm) const { // Write our permanent provider id. ostm << m_dwProviderId; return ostm; }// CTSPIDevice::write /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::SetIntervalTimer // // Sets the current interval timer timeout. If the timer is set // to zero the thread associated with the timer is destroyed. // void CTSPIDevice::SetIntervalTimer (DWORD dwTimeout) { // Is it the same as before? if (m_dwIntervalTimeout == dwTimeout) return; // Is it now zero? Delete any existing interval timer. if (dwTimeout == 0) m_dwIntervalTimeout = 0; // Otherwise reset the timeout else { // Set the new timeout m_dwIntervalTimeout = dwTimeout; // Create our objects if necessary if (m_htIntervalTimer == NULL) { UINT uiThread; m_htIntervalTimer = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, tsplib_IntervalTimerThread, static_cast<void*>(this), 0, &uiThread)); _TSP_ASSERTE(m_htIntervalTimer != NULL); } } }// CTSPIDevice::SetIntervalTimer /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::OnAsynchRequestComplete // // An asynchronous request has completed and TAPI needs to be // notified. // void CTSPIDevice::OnAsynchRequestComplete(LONG lResult, CTSPIRequest* pRequest) { _TSP_ASSERTE(pRequest != NULL); DRV_REQUESTID dwReqId = pRequest->GetAsynchRequestId(); // If the request is for a PROXY (agent) command, then send the // response back through the proxy application. int iCommand = pRequest->GetCommand(); if (iCommand >= REQUEST_SETAGENTGROUP && iCommand <= REQUEST_AGENTSPECIFIC) { ProxyResponse(dwReqId, lResult); return; } // Get the asynchronous request id. If it is non-zero, inform TAPI // about the request being completed. If it is zero, this is an internally // generated request which has no cooresponding result to TAPI (we already // said it completed ok). if (dwReqId && m_lpfnCompletionProc != NULL) { _TSP_ASSERTE(m_lpfnCompletionProc != NULL); (*m_lpfnCompletionProc)(dwReqId, lResult); #ifdef _DEBUG _TSP_DTRACEX(TRC_REQUESTS, _T("OnAsynchRequestComplete %s"), pRequest->Dump().c_str()); #endif } }// CTSPIDevice::OnAsynchRequestComplete //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::CreateLine // // Create a new line device object and signal TAPI to give us a new // line device id. // CTSPILineConnection* CTSPIDevice::CreateLine(DWORD_PTR dwItemData /*=0*/) { LINEEVENT lpfn = GetSP()->GetLineCreateProc(); if (lpfn == NULL || GetProcAddress(GetSP()->GetResourceInstance(), "TSPI_providerCreateLineDevice") == NULL) { // If we are here, we probably don't have "TSPI_providerEnumDevices" exported, or the // version of TAPI isn't sufficient to handle it. _TSP_DTRACE(_T("WARNING: Attempted to dynamically create line without TAPI support\n")); _TSP_ASSERT(false); return NULL; } CTSPILineConnection* pConn = GetSP()->CreateLineObject(); pConn->Init(this, reinterpret_cast<DWORD>(pConn), GetLineCount(), dwItemData); AddLineConnectionInfo(pConn); (*lpfn)(NULL, NULL, LINE_CREATE, reinterpret_cast<DWORD_PTR>(GetProviderHandle()), reinterpret_cast<DWORD_PTR>(pConn), 0); _TSP_DTRACEX(TRC_STATS, _T("Dynamically created line object <0x%lx>\n"), pConn); return pConn; }// CTSPIDevice::CreateLine //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::RemoveLine // // Remove a line device from our device array. // void CTSPIDevice::RemoveLine (CTSPILineConnection* pLine) { LINEEVENT lpfn = GetSP()->GetLineCreateProc(); if (lpfn == NULL) { // If we are here, we probably don't have "TSPI_providerEnumDevices" exported, or the // version of TAPI isn't sufficient to handle it. _TSP_DTRACE(_T("WARNING: Attempted to dynamically remove line without TAPI support\n")); _TSP_ASSERT(false); return; } // The derived service provider will be responsible for // renumbering the line connection array when providerShutdown // is called. (*lpfn)(NULL, NULL, LINE_REMOVE, static_cast<DWORD_PTR>(pLine->GetDeviceID()), 0, 0); // Mark the line as REMOVED. Once it is closed it will be marked // as DELETED and all further references to it will be returned // in the TSPI_xxx layer. pLine->m_dwFlags |= CTSPIConnection::_IsRemoved; // If the line is closed, then go ahead and delete it now. if (pLine->GetLineHandle() == NULL) pLine->m_dwFlags |= CTSPIConnection::_IsDeleted; // Remove the permanent line identifier from our map. CEnterCode sLock(this); m_mapLineConnections.erase(pLine->GetPermanentDeviceID()); }// CTSPIDevice::RemoveLine //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::CreatePhone // // Create a new phone device object and signal TAPI to give us a new // phone device id. // CTSPIPhoneConnection* CTSPIDevice::CreatePhone(DWORD_PTR dwItemData /*=0*/) { PHONEEVENT lpfn = GetSP()->GetPhoneCreateProc(); if (lpfn == NULL || GetProcAddress(GetSP()->GetResourceInstance(), "TSPI_providerCreatePhoneDevice") == NULL) { // If we are here, we probably don't have "TSPI_providerEnumDevices" exported, or the // version of TAPI isn't sufficient to handle it. _TSP_DTRACE(_T("WARNING: Attempted to dynamically create phone without TAPI support\n")); _TSP_ASSERT(false); return NULL; } CTSPIPhoneConnection* pConn = GetSP()->CreatePhoneObject(); pConn->Init(this, reinterpret_cast<DWORD>(pConn), GetPhoneCount(), dwItemData); AddPhoneConnectionInfo (pConn); (*lpfn)(NULL, PHONE_CREATE, reinterpret_cast<DWORD_PTR>(GetProviderHandle()), reinterpret_cast<DWORD_PTR>(pConn), 0L); _TSP_DTRACEX(TRC_STATS, _T("Dynamically created phone object <0x%lx>\n"), pConn); return pConn; }// CTSPIDevice::CreatePhone //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::RemovePhone // // Remove a phone device from our provider. // void CTSPIDevice::RemovePhone (CTSPIPhoneConnection* pPhone) { PHONEEVENT lpfn = GetSP()->GetPhoneCreateProc(); if (lpfn == NULL) { // If we are here, we probably don't have "TSPI_providerEnumDevices" exported, or the // version of TAPI isn't sufficient to handle it. _TSP_DTRACE(_T("WARNING: Attempted to dynamically remove phone without TAPI support\n")); _TSP_ASSERT(false); return; } // The derived service provider will be responsible for // renumbering the phone connection array when providerShutdown // is called. (*lpfn)(NULL, PHONE_REMOVE, pPhone->GetDeviceID(), 0L, 0L); // Mark the phone as REMOVED. Once it is closed it will be marked // as DELETED and all further references to it will be returned // in the TSPI_xxx layer. pPhone->m_dwFlags |= CTSPIConnection::_IsRemoved; }// CTSPIDevice::RemovePhone //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::RunTimer // // This is the loop that the device interval timer thread uses to periodically // show activity on the line/phone devices. It is only activated if the // derived service provider uses the "SetIntervalTimer" API of this device // object and sets the timeout to a non-zero value. // // It then wakes up every "m_dwIntervalTimeout" msecs and calls the OnTimer() // method of the device. // void CTSPIDevice::RunTimer() { for (;;) { // Wait for either our object to signal (meaning our provider // is being shutdown), or for our timeout value to elapse. LONG lResult = WaitForSingleObject (m_hevtDeviceShutdown, m_dwIntervalTimeout); if (lResult == WAIT_OBJECT_0 || lResult == WAIT_ABANDONED || m_dwIntervalTimeout == 0) break; try { // Let the virtual function handle the timer. OnTimer(); } catch (...) { } } }// CTSPIDevice::RunTimer //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::OnTimer // // This invokes the OnTimer() method of all the lines/phones owned by // this device. // void CTSPIDevice::OnTimer() { // Walk through the line and phone array and call their "OnTimer" function // to let them perform some piece of work in the derived provider. int i, iLineCount = GetLineCount(); for (i = 0; i < iLineCount; i++) { CTSPILineConnection* pLine = GetLineConnectionInfo(i); if (pLine && !pLine->HasBeenDeleted()) pLine->OnTimer(); } int iPhoneCount = GetPhoneCount(); for (i = 0; i < iPhoneCount; i++) { CTSPIPhoneConnection* pPhone = GetPhoneConnectionInfo(i); if (pPhone && !pPhone->HasBeenDeleted()) pPhone->OnTimer(); } }// CTSPIDevice::OnTimer //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::ReceiveData // // This is a data direction function that allows the derived service // provider to simply associate the PERMANENT LINE or PERMANENT PHONE // identifier with a request and when the data is recieved, pass it // here to have it automatically directed to the line or phone associated // with that identifier. // // If no connection id is matched then this function spins through all // the lines and phones on the device and lets each see the event. If // any of them return "true" to indicate that the event was processed, // this loop terminates. // void CTSPIDevice::ReceiveData (DWORD dwPermanentID, LPCVOID lpBuff) { // If we have a connection identifier passed from the caller.. if (dwPermanentID != 0) { // Lookup the line/phone and let it process the data. CTSPILineConnection* pLine = FindLineConnectionByPermanentID(dwPermanentID); if (pLine != NULL) pLine->ReceiveData(lpBuff); CTSPIPhoneConnection* pPhone = FindPhoneConnectionByPermanentID(dwPermanentID); if (pPhone != NULL) pPhone->ReceiveData(lpBuff); } // No line/phone device was specified by the caller. // Spin through all line and phone devices and hand them the data. // If the connection returns true, then stop. else { CEnterCode sLock(this); // Try the lines first if (std::find_if(m_arrayLines.begin(), m_arrayLines.end(), std::bind2nd(std::mem_fun1(&CTSPILineConnection::ReceiveData), lpBuff)) != m_arrayLines.end()) return; // Finally, hit the phone objects std::find_if(m_arrayPhones.begin(), m_arrayPhones.end(), std::bind2nd(std::mem_fun1(&CTSPIPhoneConnection::ReceiveData), lpBuff)); } }// CTSPIDevice::ReceiveData //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::GenericDialogData // // Dialog Data for UI constructions in TAPI 2.0 // LONG CTSPIDevice::GenericDialogData (LPVOID /*lpParam*/, DWORD /*dwSize*/) { return false; }// CTSPIDevice::GenericDialogData //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::OpenDevice // // This method is called when lineOpen or phoneOpen is called. // bool CTSPIDevice::OpenDevice (CTSPIConnection* /*pConn*/) { // This always returns that the device is open since in a 3rd party // view, we would stay connected to the hardware at all times to keep a // current view of the lines we manage. In a first-party provider, this // function would be used to connect to the device. return true; }// CTSPIDevice::Open //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::CloseDevice // // This method is called when the last line/phone connection object is // closed. It will not be called if multiple lines/phones are open on this // device. // bool CTSPIDevice::CloseDevice (CTSPIConnection* /*pConn*/) { return false; }// CTSPIDevice::CloseDevice //////////////////////////////////////////////////////////////////////////// // CTSPIDevice::OnCancelRequest // // Cancel a request which has already been started (its state is not // STATE_INITIAL). The request is about to be deleted and send an // error notification back to TAPI. Generally this happens when the // call or line is closed. The service provider code should determine // what to do based on the state of this request and its command. // void CTSPIDevice::OnCancelRequest (CTSPIRequest* /*pRequest*/) { /* Do nothing */ }// CTSPIDevice::CancelRequest /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::OnNewRequest // // A new request is being added to our connection object. The derived // provider may override this function or CTSPIConnection::OnNewRequest or // the CServiceProvider::OnNewRequest function to catch these and perform // some function BEFORE the request has officially been added. // // If false is returned, the request will be canceled. // bool CTSPIDevice::OnNewRequest (CTSPIConnection* /*pConn*/, CTSPIRequest* /*pReq*/, int* /*piPos*/) { // Return true to continue adding the request or false to cancel the request. return true; }// CTSPIDevice::OnNewRequest /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::FindCallHub // // This function may be used by the service provider to locate a call hub // with calls using the CALLID field of the LINECALLINFO structure. // // If no call hub has been created for the given call id, this function // returns NULL. // const CTSPICallHub* CTSPIDevice::FindCallHub(DWORD dwCallID) const { CEnterCode sLock(this); if (!m_mapCalls.empty()) { TCallMap::const_iterator theIterator = m_mapCalls.find(dwCallID); if (theIterator != m_mapCalls.end()) return (*theIterator).second; } return NULL; }// CTSPIDevice::FindCallHub /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::GetCallHubFromMap // // This function is called to create or locate an existing call hub // for a given callid. // CTSPICallHub* CTSPIDevice::GetCallHubFromMap(DWORD dwCallID) { // Don't support zero call id - always NULL. if (dwCallID == 0) return NULL; // Otherwise search for the call hub CEnterCode sLock(this); if (!m_mapCalls.empty()) { TCallMap::const_iterator theIterator = m_mapCalls.find(dwCallID); if (theIterator != m_mapCalls.end()) return (*theIterator).second; } // Doesn't yet exist, create it. CTSPICallHub* pHub = new CTSPICallHub(dwCallID); m_mapCalls.insert(std::make_pair(dwCallID, pHub)); #ifdef _DEBUG _TSP_DTRACEX(TRC_CALLMAP, _T("Created callhub %s"), pHub->Dump().c_str()); #endif return pHub; }// CTSPIDevice::GetCallHubFromMap /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::RemoveCallHub // // This is called when the final call is removed from a call hub // object - it deletes the call hub and removes it from the map. // void CTSPIDevice::RemoveCallHub(DWORD dwCallID, CTSPICallHub* pHub) { CEnterCode sLock(this); #ifdef _DEBUG _TSP_DTRACEX(TRC_CALLMAP, _T("Deleting callhub %s"), pHub->Dump().c_str()); #endif // Find the hub in question and delete it. if (!m_mapCalls.empty()) { TCallMap::iterator theIterator = m_mapCalls.find(dwCallID); _TSP_ASSERTE(theIterator != m_mapCalls.end()); if (theIterator != m_mapCalls.end()) m_mapCalls.erase(theIterator); } _TSP_ASSERTE(FindCallHub(dwCallID) == NULL); // We are done with this object -- when the reference count hits // zero it will be deleted from memory. pHub->DecRef(); }// CTSPIDevice::RemoveCallHub /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::EnableAgentProxy // // Turn on the agent proxy support for a specific line. // void CTSPIDevice::EnableAgentProxy(CTSPILineConnection* pLine, DWORD dwAgentFeatures) { // Create an OPEN packet DWORD dwSize = sizeof(ACDREQUEST) + sizeof(ACDOPEN); ACDREQUEST* pRequest = reinterpret_cast<ACDREQUEST*>(AllocMem(dwSize)); pRequest->dwSize = dwSize; pRequest->dwType = ACDTYPE_OPEN; pRequest->dwProviderID = GetProviderID(); pRequest->dwLineDeviceID = pLine->GetDeviceID(); ACDOPEN* pInit = reinterpret_cast<ACDOPEN*>(pRequest->vPart); pInit->dwAgentFeatures = dwAgentFeatures; // Walk through our address objects on the line and see what agent capabilities // are supported. for (int iAddress = 0; iAddress < pLine->GetAddressCount(); iAddress++) { CTSPIAddressInfo* pAddress = pLine->GetAddress(iAddress); if (pAddress != NULL) { // Add in any calculated agent features. DWORD dwFeatures = pAddress->GetAgentCaps()->dwFeatures; // If we were not passed any features, try to figure them out. if (dwAgentFeatures == 0) { if (dwFeatures & LINEAGENTFEATURE_SETAGENTGROUP) pInit->dwAgentFeatures |= AGENTFEATURE_SETAGENTGROUP; if (dwFeatures & LINEAGENTFEATURE_SETAGENTSTATE) pInit->dwAgentFeatures |= AGENTFEATURE_SETAGENTSTATE; if (dwFeatures & LINEAGENTFEATURE_SETAGENTACTIVITY) pInit->dwAgentFeatures |= AGENTFEATURE_SETAGENTACTIVITY; if (dwFeatures & LINEAGENTFEATURE_AGENTSPECIFIC) pInit->dwAgentFeatures |= AGENTFEATURE_AGENTSPECIFIC; if (dwFeatures & LINEAGENTFEATURE_GETAGENTACTIVITYLIST) pInit->dwAgentFeatures |= AGENTFEATURE_GETAGENTACTIVITYLIST; if (dwFeatures & LINEAGENTFEATURE_GETAGENTGROUP) pInit->dwAgentFeatures |= AGENTFEATURE_GETAGENTGROUPLIST; } // Setup the status messages we can send based on the features // that the provider is expecting to support on this address. pAddress->GetAgentCaps()->dwAgentStatusMessages |= (LINEAGENTSTATUS_CAPSCHANGE | LINEAGENTSTATUS_VALIDSTATES | LINEAGENTSTATUS_VALIDNEXTSTATES); if (dwFeatures & LINEAGENTFEATURE_SETAGENTGROUP) pAddress->GetAgentCaps()->dwAgentStatusMessages |= LINEAGENTSTATUS_GROUP; if (dwFeatures & LINEAGENTFEATURE_SETAGENTSTATE) pAddress->GetAgentCaps()->dwAgentStatusMessages |= (LINEAGENTSTATUS_STATE | LINEAGENTSTATUS_NEXTSTATE); if (dwFeatures & LINEAGENTFEATURE_SETAGENTACTIVITY) pAddress->GetAgentCaps()->dwAgentStatusMessages |= LINEAGENTSTATUS_ACTIVITY; if (dwFeatures & LINEAGENTFEATURE_GETAGENTACTIVITYLIST) pAddress->GetAgentCaps()->dwAgentStatusMessages |= LINEAGENTSTATUS_ACTIVITYLIST; if (dwFeatures & LINEAGENTFEATURE_GETAGENTGROUP) pAddress->GetAgentCaps()->dwAgentStatusMessages |= LINEAGENTSTATUS_GROUPLIST; // Determine our current agent feature set if the derived provider didn't set it already. if (pAddress->GetAgentStatus()->dwAgentFeatures == 0) { DWORD dwState = pAddress->GetAgentStatus()->dwState; if (dwState == LINEAGENTSTATE_LOGGEDOFF) { // If we support lineSetAgentGroup, then force that to be the method // used for login - this is the standard usage by most TAPI applications // so it should be the way the service provider functions. if (pAddress->GetAgentCaps()->dwFeatures & LINEAGENTFEATURE_SETAGENTGROUP) dwFeatures &= ~(LINEAGENTFEATURE_SETAGENTACTIVITY | LINEAGENTFEATURE_SETAGENTSTATE); // Otherwise if we don't support lineSetAgentGroup, the allow the // lineSetAgentState function to be used for logon or setting the // initial state. else dwFeatures &= ~LINEAGENTFEATURE_SETAGENTACTIVITY; } // Otherwise, if we are logged on but don't have any groups loaded into our // group list then don't allow lineSetAgentGroup. We want to allow it // normally in case the provider wants to use lineSetAgentGroup to perform // a logon w/o real groups. else if (dwState != LINEAGENTSTATE_UNKNOWN) { if (GetAgentGroupCount() == 0) dwFeatures &= ~LINEAGENTFEATURE_SETAGENTGROUP; } // Set the current available features pAddress->SetAgentFeatures(dwFeatures); } } } // If the line doesn't support ANY agent activity, then ignore this request. // Otherwise, send the OPEN request to the proxy. if (pInit->dwAgentFeatures != 0) { // Make sure we include the default ones. pInit->dwAgentFeatures |= (AGENTFEATURE_GETAGENTCAPS | AGENTFEATURE_GETAGENTSTATUS); _TSP_DTRACEX(TRC_AGENTPROXY, _T("Enabling JTProxy for line %ld\n"), pLine->GetDeviceID()); // Ensure that we have the shared memory allocated and an agent thread running. if (m_psmProxy == NULL) { m_psmProxy = new CSharedMemMgr; if (m_psmProxy->Init(ACDPROXY_OUTPUT, MAX_ACD_MAX_SIZE, ACDPROXY_INPUT, MAX_ACD_MAX_SIZE)) { UINT uiThread; m_htAgentProxy = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, tsplib_AgentProxyThread, static_cast<void*>(this), 0, &uiThread)); _TSP_ASSERTE(m_htAgentProxy != NULL); } else { _TSP_DTRACEX(TRC_AGENTPROXY, _T("Unable to connect to the JTProxy application. Agent services have been disabled.\n")); delete m_psmProxy; m_psmProxy = NULL; FreeMem(pRequest); return; } } m_psmProxy->Write(pRequest); } // Free the block FreeMem(pRequest); }// CTSPIDevice::EnableAgentProxy /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::AddAgentActivity // // This function adds a new activity code to the agent capabilities. // int CTSPIDevice::AddAgentActivity (DWORD dwID, LPCTSTR pszName) { // Verify that this activity isn't already in our list. if (DoesAgentActivityExist(dwID) != NULL) return -1; // Create a new agent activity structure. TAgentActivity* pActivity = new TAgentActivity; pActivity->dwID = dwID; pActivity->strName = pszName; CEnterCode sLock(this); m_arrAgentActivities.push_back(pActivity); return m_arrAgentActivities.size()-1; }// CTSPIDevice::AddAgentActivity /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::RemoveAgentActivity // // This function removes an agent activity item from our array. // void CTSPIDevice::RemoveAgentActivity(DWORD dwID) { CEnterCode sLock(this); bool fFound = false; for (TAgentActivityArray::iterator iPos = m_arrAgentActivities.begin(); iPos != m_arrAgentActivities.end(); iPos++) { TAgentActivity* pActivity = (*iPos); if (pActivity->dwID == dwID) { m_arrAgentActivities.erase(iPos); delete pActivity; fFound = true; break; } } sLock.Unlock(); // Notify TAPI that the activities have changed for each line on this // device that supports agent capabilities if (fFound == true) { for (unsigned int i = 0; i < GetLineCount(); i++) { CTSPILineConnection* pLine = GetLineConnectionInfo(i); if (pLine->SupportsAgents()) { for (int j = 0; j < pLine->GetAddressCount(); j++) pLine->GetAddress(j)->OnAgentCapabiltiesChanged(); } } } }// CTSPIDevice::RemoveAgentActivity /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::DoesAgentActivityExist // // This function returns true/false whether the given activity // is valid within our list. // bool CTSPIDevice::DoesAgentActivityExist(DWORD dwActivity) const { CEnterCode sLock(this); for (TAgentActivityArray::const_iterator iPos = m_arrAgentActivities.begin(); iPos != m_arrAgentActivities.end(); iPos++) { if ((*iPos)->dwID == dwActivity) return true; } return false; }// CTSPIDevice::DoesAgentActivityExist /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::GetAgentActivityById // // This function returns the activity structure associated with the ID. // TString CTSPIDevice::GetAgentActivityById(DWORD dwID) const { CEnterCode sLock(this); for (TAgentActivityArray::const_iterator iPos = m_arrAgentActivities.begin(); iPos != m_arrAgentActivities.end(); iPos++) { if ((*iPos)->dwID == dwID) return (*iPos)->strName; } return TString(_T("")); }// CTSPIDevice::GetAgentActivityById /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::AddAgentGroup // // Adds a new agent group to our list. // int CTSPIDevice::AddAgentGroup(LPCTSTR pszName, DWORD dwGroupID1, DWORD dwGroupID2, DWORD dwGroupID3, DWORD dwGroupID4) { // Verify that this group isn't already in our list. if (DoesAgentGroupExist(dwGroupID1, dwGroupID2, dwGroupID3, dwGroupID4)) return -1; // Create a new agent activity structure. TAgentGroup* pGroup = new TAgentGroup; pGroup->strName = pszName; pGroup->GroupID.dwGroupID1 = dwGroupID1; pGroup->GroupID.dwGroupID2 = dwGroupID2; pGroup->GroupID.dwGroupID3 = dwGroupID3; pGroup->GroupID.dwGroupID4 = dwGroupID4; // Now add it to our array CEnterCode sLock(this); m_arrAgentGroups.push_back(pGroup); return m_arrAgentGroups.size()-1; }// CTSPIDevice::AddAgentGroup /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::RemoveAgentGroup // // Removes the specified agent group. // void CTSPIDevice::RemoveAgentGroup(DWORD dwGroupID1, DWORD dwGroupID2, DWORD dwGroupID3, DWORD dwGroupID4) { // Locate the group in our array CEnterCode sLock(this); bool fFound = false; for (TAgentGroupArray::iterator iPos = m_arrAgentGroups.begin(); iPos != m_arrAgentGroups.end(); iPos++) { TAgentGroup* pGroup = (*iPos); if (pGroup->GroupID.dwGroupID1 == dwGroupID1 && pGroup->GroupID.dwGroupID2 == dwGroupID2 && pGroup->GroupID.dwGroupID3 == dwGroupID3 && pGroup->GroupID.dwGroupID4 == dwGroupID4) { m_arrAgentGroups.erase(iPos); delete pGroup; fFound = true; break; } } sLock.Unlock(); // Notify TAPI that the activities have changed for each line on this // device that supports agent capabilities if (fFound == true) { for (unsigned int i = 0; i < GetLineCount(); i++) { CTSPILineConnection* pLine = GetLineConnectionInfo(i); if (pLine->SupportsAgents()) { for (int j = 0; j < pLine->GetAddressCount(); j++) pLine->GetAddress(j)->OnAgentCapabiltiesChanged(); } } } }// CTSPIDevice::RemoveAgentGroup /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::DoesAgentGroupExist // // This function returns true/false whether the given group // is valid within our list. // bool CTSPIDevice::DoesAgentGroupExist(DWORD dwGroupID1, DWORD dwGroupID2, DWORD dwGroupID3, DWORD dwGroupID4) const { CEnterCode sLock(this); for (TAgentGroupArray::const_iterator iPos = m_arrAgentGroups.begin(); iPos != m_arrAgentGroups.end(); iPos++) { TAgentGroup* pGroup = (*iPos); if (pGroup->GroupID.dwGroupID1 == dwGroupID1 && pGroup->GroupID.dwGroupID2 == dwGroupID2 && pGroup->GroupID.dwGroupID3 == dwGroupID3 && pGroup->GroupID.dwGroupID4 == dwGroupID4) return true; } return false; }// CTSPIDevice::DoesAgentGroupExist /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::GetAgentGroupById // // Returns the agent group by the identifier // TString CTSPIDevice::GetAgentGroupById(DWORD dwGroupID1, DWORD dwGroupID2, DWORD dwGroupID3, DWORD dwGroupID4) const { // Locate the group in our array CEnterCode sLock(this); for (TAgentGroupArray::const_iterator iPos = m_arrAgentGroups.begin(); iPos != m_arrAgentGroups.end(); iPos++) { TAgentGroup* pGroup = (*iPos); if (pGroup->GroupID.dwGroupID1 == dwGroupID1 && pGroup->GroupID.dwGroupID2 == dwGroupID2 && pGroup->GroupID.dwGroupID3 == dwGroupID3 && pGroup->GroupID.dwGroupID4 == dwGroupID4) return pGroup->strName; } return TString(_T("")); }// CTSPIDevice::GetAgentGroupById /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::AddAgentSpecificExtension // // Adds a new agent specific handler extension. // int CTSPIDevice::AddAgentSpecificExtension(DWORD dwID1, DWORD dwID2, DWORD dwID3, DWORD dwID4) { // Verify that this group isn't already in our list. if (DoesAgentSpecificExtensionExist(dwID1, dwID2, dwID3, dwID4) != NULL) return -1; // Create a new agent activity structure. TAgentSpecificEntry* pEntry = new TAgentSpecificEntry; pEntry->dwID1 = dwID1; pEntry->dwID2 = dwID1; pEntry->dwID3 = dwID1; pEntry->dwID4 = dwID1; // Now add it to our array CEnterCode sLock(this); m_arrAgentExtensions.push_back(pEntry); return m_arrAgentExtensions.size()-1; }// CTSPIDevice::AddAgentSpecificExtension /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::RemoveAgentSpecificExtension // // Removes the specified agent extension // void CTSPIDevice::RemoveAgentSpecificExtension(DWORD dwID1, DWORD dwID2, DWORD dwID3, DWORD dwID4) { // Locate the group in our array CEnterCode sLock(this); bool fFound = false; for (TAgentExtensionArray::iterator iPos = m_arrAgentExtensions.begin(); iPos != m_arrAgentExtensions.end(); iPos++) { TAgentSpecificEntry* pEntry = (*iPos); if (pEntry->dwID1 == dwID1 && pEntry->dwID2 == dwID2 && pEntry->dwID3 == dwID3 && pEntry->dwID4 == dwID4) { m_arrAgentExtensions.erase(iPos); delete pEntry; fFound = true; break; } } sLock.Unlock(); // Notify TAPI that the activities have changed for each line on this // device that supports agent capabilities if (fFound == true) { for (unsigned int i = 0; i < GetLineCount(); i++) { CTSPILineConnection* pLine = GetLineConnectionInfo(i); if (pLine->SupportsAgents()) { for (int j = 0; j < pLine->GetAddressCount(); j++) pLine->GetAddress(j)->OnAgentCapabiltiesChanged(); } } } }// CTSPIDevice::RemoveSpecificExtension /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::DoesAgentSpecificExtension // // Locate an extension by the id. // bool CTSPIDevice::DoesAgentSpecificExtensionExist(DWORD dwID1, DWORD dwID2, DWORD dwID3, DWORD dwID4) const { // Locate the group in our array CEnterCode sLock(this); for (TAgentExtensionArray::const_iterator iPos = m_arrAgentExtensions.begin(); iPos != m_arrAgentExtensions.end(); iPos++) { TAgentSpecificEntry* pEntry = (*iPos); if (pEntry->dwID1 == dwID1 && pEntry->dwID2 == dwID2 && pEntry->dwID3 == dwID3 && pEntry->dwID4 == dwID4) return true; } return false; }// CTSPIDevice::DoesAgentSpecificExtensionExist /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::AgentProxy // // This function is run by a secondary thread which pulls requests // from our agent proxy application and sends them through the service // provider. // void CTSPIDevice::AgentProxy() { for (;;) { // Wait for either our object to signal (meaning our provider // is being shutdown), or for the proxy buffer to have information. ACDREQUEST* pRequest; if (m_psmProxy == NULL || !m_psmProxy->ReadSpecific(GetProviderID(), &pRequest, m_hevtDeviceShutdown)) break; // Validate that we got something. if (pRequest == NULL) continue; // See if the proxy application just OPENED itself. // If so, we need to tell it about each of the lines which // are expecting agent handling. if (pRequest->dwType == ACDTYPE_OPEN) { _TSP_DTRACEX(TRC_AGENTPROXY, _T("Received PROXY_open\n")); for (unsigned int iLine = 0; iLine < GetLineCount(); iLine++) { CTSPILineConnection* pLine = GetLineConnectionInfo(iLine); if (pLine != NULL && !pLine->HasBeenDeleted() && pLine->SupportsAgents()) pLine->EnableAgentProxy(); } } // Or if this is a request to run, run it. else if (pRequest->dwType == ACDTYPE_PROXYREQUEST) { LPLINEPROXYREQUEST pProxy = reinterpret_cast<LPLINEPROXYREQUEST>(pRequest->vPart); switch (pProxy->dwRequestType) { // lineSetAgentGroup case LINEPROXYREQUEST_SETAGENTGROUP: TSPI_lineSetAgentGroup(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->SetAgentGroup.dwAddressID, &pProxy->SetAgentGroup.GroupList); break; // lineSetAgentState case LINEPROXYREQUEST_SETAGENTSTATE: TSPI_lineSetAgentState(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->SetAgentState.dwAddressID, pProxy->SetAgentState.dwAgentState, pProxy->SetAgentState.dwNextAgentState); break; // lineSetAgentActivity case LINEPROXYREQUEST_SETAGENTACTIVITY: TSPI_lineSetAgentActivity(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->SetAgentActivity.dwAddressID, pProxy->SetAgentActivity.dwActivityID); break; // lineGetAgentStatus case LINEPROXYREQUEST_GETAGENTSTATUS: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetAgentStatus( pRequest->dwLineDeviceID, pProxy->GetAgentStatus.dwAddressID, &pProxy->GetAgentStatus.AgentStatus)); break; // lineGetAgentCaps case LINEPROXYREQUEST_GETAGENTCAPS: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetAgentCaps( pRequest->dwLineDeviceID, pProxy->GetAgentCaps.dwAddressID, &pProxy->GetAgentCaps.AgentCaps)); break; // lineGetAgentActivityList case LINEPROXYREQUEST_GETAGENTACTIVITYLIST: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetAgentActivityList( pRequest->dwLineDeviceID, pProxy->GetAgentActivityList.dwAddressID, &pProxy->GetAgentActivityList.ActivityList)); break; // lineGetAgentGroupList case LINEPROXYREQUEST_GETAGENTGROUPLIST: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetAgentGroupList( pRequest->dwLineDeviceID, pProxy->GetAgentGroupList.dwAddressID, &pProxy->GetAgentGroupList.GroupList)); break; // lineAgentSpecific case LINEPROXYREQUEST_AGENTSPECIFIC: TSPI_lineAgentSpecific(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->AgentSpecific.dwAddressID, pProxy->AgentSpecific.dwAgentExtensionIDIndex, &pProxy->AgentSpecific.Params[0], pProxy->AgentSpecific.dwSize); break; case LINEPROXYREQUEST_CREATEAGENT: TSPI_lineCreateAgent(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, &pProxy->CreateAgent.hAgent, pRequest->chMachine, pRequest->chUserName, GetWStringFromVARBlock(pProxy, pProxy->CreateAgent.dwAgentIDSize, pProxy->CreateAgent.dwAgentIDOffset), GetWStringFromVARBlock(pProxy, pProxy->CreateAgent.dwAgentPINSize, pProxy->CreateAgent.dwAgentPINOffset)); break; case LINEPROXYREQUEST_SETAGENTMEASUREMENTPERIOD: TSPI_lineSetAgentMeasurementPeriod( reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->SetAgentMeasurementPeriod.hAgent, pProxy->SetAgentMeasurementPeriod.dwMeasurementPeriod); break; case LINEPROXYREQUEST_GETAGENTINFO: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetAgentInfo( pRequest->dwLineDeviceID, pProxy->GetAgentInfo.hAgent, &pProxy->GetAgentInfo.AgentInfo)); break; case LINEPROXYREQUEST_CREATEAGENTSESSION: TSPI_lineCreateAgentSession(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, &pProxy->CreateAgentSession.hAgentSession, pProxy->CreateAgentSession.hAgent, GetWStringFromVARBlock(pProxy, pProxy->CreateAgentSession.dwAgentPINSize, pProxy->CreateAgentSession.dwAgentPINOffset), &pProxy->CreateAgentSession.GroupID, pProxy->CreateAgentSession.dwWorkingAddressID); break; case LINEPROXYREQUEST_GETAGENTSESSIONLIST: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetAgentSessionList(pRequest->dwLineDeviceID, pProxy->GetAgentSessionList.hAgent, &pProxy->GetAgentSessionList.SessionList)); break; case LINEPROXYREQUEST_SETAGENTSESSIONSTATE: TSPI_lineSetAgentSessionState(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->SetAgentSessionState.hAgentSession, pProxy->SetAgentSessionState.dwAgentSessionState, pProxy->SetAgentSessionState.dwNextAgentSessionState); break; case LINEPROXYREQUEST_GETAGENTSESSIONINFO: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetAgentSessionInfo( pRequest->dwLineDeviceID, pProxy->GetAgentSessionInfo.hAgentSession, &pProxy->GetAgentSessionInfo.SessionInfo)); break; case LINEPROXYREQUEST_GETQUEUELIST: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetQueueList(pRequest->dwLineDeviceID, &pProxy->GetQueueList.GroupID, &pProxy->GetQueueList.QueueList)); break; case LINEPROXYREQUEST_SETQUEUEMEASUREMENTPERIOD: TSPI_lineSetQueueMeasurementPeriod(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->SetQueueMeasurementPeriod.dwQueueID, pProxy->SetQueueMeasurementPeriod.dwMeasurementPeriod); break; case LINEPROXYREQUEST_GETQUEUEINFO: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetQueueInfo( pRequest->dwLineDeviceID, pProxy->GetQueueInfo.dwQueueID, &pProxy->GetQueueInfo.QueueInfo)); break; case LINEPROXYREQUEST_GETGROUPLIST: ProxyResponse(reinterpret_cast<DRV_REQUESTID>(pRequest), TSPI_lineGetGroupList(pRequest->dwLineDeviceID, &pProxy->GetGroupList.GroupList)); break; case LINEPROXYREQUEST_SETAGENTSTATEEX: TSPI_lineSetAgentStateEx(reinterpret_cast<DRV_REQUESTID>(pRequest), pRequest->dwLineDeviceID, pProxy->SetAgentStateEx.hAgent, pProxy->SetAgentStateEx.dwAgentState, pProxy->SetAgentStateEx.dwNextAgentState); break; default: _TSP_DTRACEX(TRC_WARNINGS, _T("PROBLEM: Unknown agent proxy request type: 0x%lx from %s\\%s"), pRequest->dwType, pRequest->chMachine, pRequest->chUserName); break; } } } // Delete the shared memory object for the proxy delete m_psmProxy; m_psmProxy = NULL; }// CTSPIDevice::AgentProxy /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::ProxyResponse // // Returns a response to the proxy application concerning an event. // void CTSPIDevice::ProxyResponse(DRV_REQUESTID dwRequestID, LONG lResult) { // Convert the DRV_REQUESTID back into our pointer and validate // that it may be passed back to the proxy application. ACDREQUEST* pRequest = reinterpret_cast<ACDREQUEST*>(dwRequestID); if (pRequest == NULL || IsBadReadPtr(pRequest, sizeof(ACDREQUEST)) || pRequest->dwType != ACDTYPE_PROXYREQUEST) { _TSP_DTRACE(_T("ProxyResponse: bad ACDREQUEST 0x%lx, type=%ld, (possibly completed request twice?)\n"), pRequest, pRequest->dwType); return; } // If there is no proxy installed/running or if the requestid and the // result are the same, then it is ok ignore it. if (m_psmProxy != NULL && (dwRequestID > 0 && dwRequestID != static_cast<DRV_REQUESTID>(lResult))) { // Fill in our result. pRequest->lResult = lResult; pRequest->dwType = ACDTYPE_PROXYRESPONSE; pRequest->dwProviderID = GetProviderID(); // Throw it back to the agent app and delete the memory block. m_psmProxy->Write(pRequest); } // Delete the request received from the proxy delete [] (BYTE*) pRequest; }// CTSPIDevice::ProxyResponse /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::ProxyNotify // // Sends an asynch notification to the proxy application // void CTSPIDevice::ProxyNotify(CTSPILineConnection* pLine, DWORD dwMsg, DWORD dwParam1, DWORD dwParam2, DWORD dwParam3) { // If there is no proxy installed/running then exit. if (m_psmProxy == NULL) return; // Otherwise send it. DWORD dwSize = sizeof(ACDREQUEST) + sizeof(ACDNOTIFY); ACDREQUEST* pRequest = reinterpret_cast<ACDREQUEST*>(AllocMem(dwSize)); pRequest->dwSize = dwSize; pRequest->dwType = ACDTYPE_NOTIFY; pRequest->dwProviderID = GetProviderID(); pRequest->dwLineDeviceID = pLine->GetDeviceID(); ACDNOTIFY* pNotify = reinterpret_cast<ACDNOTIFY*>(pRequest->vPart); pNotify->dwMsg = dwMsg; pNotify->dwParam1 = dwParam1; pNotify->dwParam2 = dwParam2; pNotify->dwParam3 = dwParam3; // Send the notify request to the proxy. m_psmProxy->Write(pRequest); // Free the block FreeMem(pRequest); }// CTSPIDevice::ProxyNotify /////////////////////////////////////////////////////////////////////////// // tsplib_IntervalTimerThread // // Runs the interval timer for this device // unsigned __stdcall tsplib_IntervalTimerThread(void* pParam) { _TSP_DTRACEX(TRC_THREADS, _T("IntervalTimerThread(0x%lx) starting\n"), GetCurrentThreadId()); reinterpret_cast<CTSPIDevice*>(pParam)->RunTimer(); _TSP_DTRACEX(TRC_THREADS, _T("IntervalTimerThread(0x%lx) ending\n"), GetCurrentThreadId()); _endthreadex(0); return 0; }// tsplib_IntervalTimerThread /////////////////////////////////////////////////////////////////////////// // tsplib_AgentProxyThread // // Runs the agent proxy delivery thread for this device // unsigned __stdcall tsplib_AgentProxyThread(void* pParam) { _TSP_DTRACEX(TRC_THREADS, _T("AgentProxyThread(0x%lx) starting\n"), GetCurrentThreadId()); reinterpret_cast<CTSPIDevice*>(pParam)->AgentProxy(); _TSP_DTRACEX(TRC_THREADS, _T("AgentProxyThread(0x%lx) ending\n"), GetCurrentThreadId()); _endthreadex(0); return 0; }// tsplib_AgentProxyThread #ifdef _DEBUG /////////////////////////////////////////////////////////////////////////// // CTSPIDevice::Dump // // Debug "dump" of the object and it's contents. // TString CTSPIDevice::Dump() const { TStringStream outstm; CEnterCode Lock(this); outstm << _T("0x") << hex << (DWORD)this; outstm << _T(",ProviderID=0x") << hex << m_dwProviderId; outstm << _T(" [") << m_strDevInfo << _T("] "); outstm << _T("AgentProxy is"); if (m_psmProxy == NULL) outstm << _T(" not"); outstm << _T(" running"); return(outstm.str()); }// CTSPIDevice::Dump #endif
// Fill out your copyright notice in the Description page of Project Settings. #include "EFBTTaskSetBlackboardVector.h" #include "AIController.h" #include "BehaviorTree/BlackboardComponent.h" #include "BehaviorTree/Blackboard/BlackboardKeyType_Object.h" #include "BehaviorTree/Blackboard/BlackboardKeyType_Vector.h" EBTNodeResult::Type UEFBTTaskSetBlackboardVector::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { if (auto const AIController = Cast<AAIController>(OwnerComp.GetOwner())) { if (const auto Actor = Cast<AActor>(AIController->GetBlackboardComponent()->GetValue<UBlackboardKeyType_Object>(ActorKey.SelectedKeyName))) { AIController->GetBlackboardComponent()->SetValue<UBlackboardKeyType_Vector>(VectorKey.SelectedKeyName,Actor->GetActorLocation()); return EBTNodeResult::Succeeded; } } return Super::ExecuteTask(OwnerComp, NodeMemory); }
/* file: df_classification_train_dense_default_batch_fpt_cpu.cpp */ /******************************************************************************* * Copyright 2014-2020 Intel Corporation * * 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. *******************************************************************************/ /* //++ // Implementation of decision forest training functions for the default method //-- */ #include "algorithms/kernel/dtrees/forest/classification/df_classification_train_container.h" #include "algorithms/kernel/dtrees/forest/classification/df_classification_train_dense_default_impl.i" namespace daal { namespace algorithms { namespace decision_forest { namespace classification { namespace training { namespace interface2 { template class BatchContainer<DAAL_FPTYPE, defaultDense, DAAL_CPU>; } namespace internal { template class ClassificationTrainBatchKernel<DAAL_FPTYPE, defaultDense, DAAL_CPU>; } } // namespace training } // namespace classification } // namespace decision_forest } // namespace algorithms } // namespace daal
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "data/script_tests.json.h" #include "core_io.h" #include "key.h" #include "keystore.h" #include "script/script.h" #include "script/script_error.h" #include "script/sign.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_3dcoin.h" #if defined(HAVE_CONSENSUS_LIB) #include "script/bitcoinconsensus.h" #endif #include <fstream> #include <stdint.h> #include <string> #include <vector> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include <univalue.h> using namespace std; // Uncomment if you want to output updated JSON tests. // #define UPDATE_JSON_TESTS static const unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; unsigned int ParseScriptFlags(string strFlags); string FormatScriptFlags(unsigned int flags); UniValue read_json(const std::string& jsondata) { UniValue v; if (!v.read(jsondata) || !v.isArray()) { BOOST_ERROR("Parse error."); return UniValue(UniValue::VARR); } return v.get_array(); } struct ScriptErrorDesc { ScriptError_t err; const char *name; }; static ScriptErrorDesc script_errors[]={ {SCRIPT_ERR_OK, "OK"}, {SCRIPT_ERR_UNKNOWN_ERROR, "UNKNOWN_ERROR"}, {SCRIPT_ERR_EVAL_FALSE, "EVAL_FALSE"}, {SCRIPT_ERR_OP_RETURN, "OP_RETURN"}, {SCRIPT_ERR_SCRIPT_SIZE, "SCRIPT_SIZE"}, {SCRIPT_ERR_PUSH_SIZE, "PUSH_SIZE"}, {SCRIPT_ERR_OP_COUNT, "OP_COUNT"}, {SCRIPT_ERR_STACK_SIZE, "STACK_SIZE"}, {SCRIPT_ERR_SIG_COUNT, "SIG_COUNT"}, {SCRIPT_ERR_PUBKEY_COUNT, "PUBKEY_COUNT"}, {SCRIPT_ERR_VERIFY, "VERIFY"}, {SCRIPT_ERR_EQUALVERIFY, "EQUALVERIFY"}, {SCRIPT_ERR_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY"}, {SCRIPT_ERR_CHECKSIGVERIFY, "CHECKSIGVERIFY"}, {SCRIPT_ERR_NUMEQUALVERIFY, "NUMEQUALVERIFY"}, {SCRIPT_ERR_BAD_OPCODE, "BAD_OPCODE"}, {SCRIPT_ERR_DISABLED_OPCODE, "DISABLED_OPCODE"}, {SCRIPT_ERR_INVALID_STACK_OPERATION, "INVALID_STACK_OPERATION"}, {SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "INVALID_ALTSTACK_OPERATION"}, {SCRIPT_ERR_UNBALANCED_CONDITIONAL, "UNBALANCED_CONDITIONAL"}, {SCRIPT_ERR_NEGATIVE_LOCKTIME, "NEGATIVE_LOCKTIME"}, {SCRIPT_ERR_UNSATISFIED_LOCKTIME, "UNSATISFIED_LOCKTIME"}, {SCRIPT_ERR_SIG_HASHTYPE, "SIG_HASHTYPE"}, {SCRIPT_ERR_SIG_DER, "SIG_DER"}, {SCRIPT_ERR_MINIMALDATA, "MINIMALDATA"}, {SCRIPT_ERR_SIG_PUSHONLY, "SIG_PUSHONLY"}, {SCRIPT_ERR_SIG_HIGH_S, "SIG_HIGH_S"}, {SCRIPT_ERR_SIG_NULLDUMMY, "SIG_NULLDUMMY"}, {SCRIPT_ERR_PUBKEYTYPE, "PUBKEYTYPE"}, {SCRIPT_ERR_CLEANSTACK, "CLEANSTACK"}, {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "DISCOURAGE_UPGRADABLE_NOPS"} }; const char *FormatScriptError(ScriptError_t err) { for (unsigned int i=0; i<ARRAYLEN(script_errors); ++i) if (script_errors[i].err == err) return script_errors[i].name; BOOST_ERROR("Unknown scripterror enumeration value, update script_errors in script_tests.cpp."); return ""; } ScriptError_t ParseScriptError(const std::string &name) { for (unsigned int i=0; i<ARRAYLEN(script_errors); ++i) if (script_errors[i].name == name) return script_errors[i].err; BOOST_ERROR("Unknown scripterror \"" << name << "\" in test description"); return SCRIPT_ERR_UNKNOWN_ERROR; } BOOST_FIXTURE_TEST_SUITE(script_tests, BasicTestingSetup) CMutableTransaction BuildCreditingTransaction(const CScript& scriptPubKey) { CMutableTransaction txCredit; txCredit.nVersion = 1; txCredit.nLockTime = 0; txCredit.vin.resize(1); txCredit.vout.resize(1); txCredit.vin[0].prevout.SetNull(); txCredit.vin[0].scriptSig = CScript() << CScriptNum(0) << CScriptNum(0); txCredit.vin[0].nSequence = CTxIn::SEQUENCE_FINAL; txCredit.vout[0].scriptPubKey = scriptPubKey; txCredit.vout[0].nValue = 0; return txCredit; } CMutableTransaction BuildSpendingTransaction(const CScript& scriptSig, const CMutableTransaction& txCredit) { CMutableTransaction txSpend; txSpend.nVersion = 1; txSpend.nLockTime = 0; txSpend.vin.resize(1); txSpend.vout.resize(1); txSpend.vin[0].prevout.hash = txCredit.GetHash(); txSpend.vin[0].prevout.n = 0; txSpend.vin[0].scriptSig = scriptSig; txSpend.vin[0].nSequence = CTxIn::SEQUENCE_FINAL; txSpend.vout[0].scriptPubKey = CScript(); txSpend.vout[0].nValue = 0; return txSpend; } void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, int flags, const std::string& message, int scriptError) { bool expect = (scriptError == SCRIPT_ERR_OK); ScriptError err; CMutableTransaction tx = BuildSpendingTransaction(scriptSig, BuildCreditingTransaction(scriptPubKey)); CMutableTransaction tx2 = tx; BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, flags, MutableTransactionSignatureChecker(&tx, 0), &err) == expect, message); BOOST_CHECK_MESSAGE(err == scriptError, std::string(FormatScriptError(err)) + " where " + std::string(FormatScriptError((ScriptError_t)scriptError)) + " expected: " + message); #if defined(HAVE_CONSENSUS_LIB) CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << tx2; BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(begin_ptr(scriptPubKey), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), 0, flags, NULL) == expect,message); #endif } void static NegateSignatureS(std::vector<unsigned char>& vchSig) { // Parse the signature. std::vector<unsigned char> r, s; r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]); s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]); // Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1. static const unsigned char order[33] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41 }; while (s.size() < 33) { s.insert(s.begin(), 0x00); } int carry = 0; for (int p = 32; p >= 1; p--) { int n = (int)order[p] - s[p] - carry; s[p] = (n + 256) & 0xFF; carry = (n < 0); } assert(carry == 0); if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) { s.erase(s.begin()); } // Reconstruct the signature. vchSig.clear(); vchSig.push_back(0x30); vchSig.push_back(4 + r.size() + s.size()); vchSig.push_back(0x02); vchSig.push_back(r.size()); vchSig.insert(vchSig.end(), r.begin(), r.end()); vchSig.push_back(0x02); vchSig.push_back(s.size()); vchSig.insert(vchSig.end(), s.begin(), s.end()); } namespace { const unsigned char vchKey0[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; const unsigned char vchKey1[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0}; const unsigned char vchKey2[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0}; struct KeyData { CKey key0, key0C, key1, key1C, key2, key2C; CPubKey pubkey0, pubkey0C, pubkey0H; CPubKey pubkey1, pubkey1C; CPubKey pubkey2, pubkey2C; KeyData() { key0.Set(vchKey0, vchKey0 + 32, false); key0C.Set(vchKey0, vchKey0 + 32, true); pubkey0 = key0.GetPubKey(); pubkey0H = key0.GetPubKey(); pubkey0C = key0C.GetPubKey(); *const_cast<unsigned char*>(&pubkey0H[0]) = 0x06 | (pubkey0H[64] & 1); key1.Set(vchKey1, vchKey1 + 32, false); key1C.Set(vchKey1, vchKey1 + 32, true); pubkey1 = key1.GetPubKey(); pubkey1C = key1C.GetPubKey(); key2.Set(vchKey2, vchKey2 + 32, false); key2C.Set(vchKey2, vchKey2 + 32, true); pubkey2 = key2.GetPubKey(); pubkey2C = key2C.GetPubKey(); } }; class TestBuilder { private: CScript scriptPubKey; CTransaction creditTx; CMutableTransaction spendTx; bool havePush; std::vector<unsigned char> push; std::string comment; int flags; int scriptError; void DoPush() { if (havePush) { spendTx.vin[0].scriptSig << push; havePush = false; } } void DoPush(const std::vector<unsigned char>& data) { DoPush(); push = data; havePush = true; } public: TestBuilder(const CScript& redeemScript, const std::string& comment_, int flags_, bool P2SH = false) : scriptPubKey(redeemScript), havePush(false), comment(comment_), flags(flags_), scriptError(SCRIPT_ERR_OK) { if (P2SH) { creditTx = BuildCreditingTransaction(CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL); } else { creditTx = BuildCreditingTransaction(redeemScript); } spendTx = BuildSpendingTransaction(CScript(), creditTx); } TestBuilder& ScriptError(ScriptError_t err) { scriptError = err; return *this; } TestBuilder& Add(const CScript& script) { DoPush(); spendTx.vin[0].scriptSig += script; return *this; } TestBuilder& Num(int num) { DoPush(); spendTx.vin[0].scriptSig << num; return *this; } TestBuilder& Push(const std::string& hex) { DoPush(ParseHex(hex)); return *this; } TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32) { uint256 hash = SignatureHash(scriptPubKey, spendTx, 0, nHashType); std::vector<unsigned char> vchSig, r, s; uint32_t iter = 0; do { key.Sign(hash, vchSig, iter++); if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) { NegateSignatureS(vchSig); } r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]); s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]); } while (lenR != r.size() || lenS != s.size()); vchSig.push_back(static_cast<unsigned char>(nHashType)); DoPush(vchSig); return *this; } TestBuilder& Push(const CPubKey& pubkey) { DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end())); return *this; } TestBuilder& PushRedeem() { DoPush(std::vector<unsigned char>(scriptPubKey.begin(), scriptPubKey.end())); return *this; } TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout) { assert(havePush); std::vector<unsigned char> datain = ParseHex(hexin); std::vector<unsigned char> dataout = ParseHex(hexout); assert(pos + datain.size() <= push.size()); BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment); push.erase(push.begin() + pos, push.begin() + pos + datain.size()); push.insert(push.begin() + pos, dataout.begin(), dataout.end()); return *this; } TestBuilder& DamagePush(unsigned int pos) { assert(havePush); assert(pos < push.size()); push[pos] ^= 1; return *this; } TestBuilder& Test() { TestBuilder copy = *this; // Make a copy so we can rollback the push. DoPush(); DoTest(creditTx.vout[0].scriptPubKey, spendTx.vin[0].scriptSig, flags, comment, scriptError); *this = copy; return *this; } UniValue GetJSON() { DoPush(); UniValue array(UniValue::VARR); array.push_back(FormatScript(spendTx.vin[0].scriptSig)); array.push_back(FormatScript(creditTx.vout[0].scriptPubKey)); array.push_back(FormatScriptFlags(flags)); array.push_back(FormatScriptError((ScriptError_t)scriptError)); array.push_back(comment); return array; } std::string GetComment() { return comment; } const CScript& GetScriptPubKey() { return creditTx.vout[0].scriptPubKey; } }; std::string JSONPrettyPrint(const UniValue& univalue) { std::string ret = univalue.write(4); // Workaround for libunivalue pretty printer, which puts a space between comma's and newlines size_t pos = 0; while ((pos = ret.find(" \n", pos)) != std::string::npos) { ret.replace(pos, 2, "\n"); pos++; } return ret; } } BOOST_AUTO_TEST_CASE(script_build) { const KeyData keys; std::vector<TestBuilder> tests; tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK", 0 ).PushSig(keys.key0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK, bad sig", 0 ).PushSig(keys.key0).DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2PKH", 0 ).PushSig(keys.key1).Push(keys.pubkey1C)); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2PKH, bad pubkey", 0 ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5).ScriptError(SCRIPT_ERR_EQUALVERIFY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK anyonecanpay", 0 ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK anyonecanpay marked with normal hashtype", 0 ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG, "P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG, "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true ).PushSig(keys.key0).DamagePush(10).PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).DamagePush(10).PushRedeem().ScriptError(SCRIPT_ERR_EQUALVERIFY)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3", 0 ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3, 2 sigs", 0 ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true ).Num(0).PushSig(keys.key1).Num(0).PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much R padding but no DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much S padding but no DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much S padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too little R padding but no DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too little R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with bad sig with too much R padding but no DERSIG", 0 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with too much R padding but no DERSIG", 0 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 1, without DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 2, without DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 3, without DERSIG", 0 ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 4, without DERSIG", 0 ).Num(0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 5, without DERSIG", 0 ).Num(1).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 6, without DERSIG", 0 ).Num(1)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 7, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 8, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 9, without DERSIG", 0 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 10, without DERSIG", 0 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220")); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 11, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 12, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with multi-byte hashtype, without DERSIG", 0 ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with multi-byte hashtype, with DERSIG", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with high S but no LOW_S", 0 ).PushSig(keys.key2, SIGHASH_ALL, 32, 33)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with high S", SCRIPT_VERIFY_LOW_S ).PushSig(keys.key2, SIGHASH_ALL, 32, 33).ScriptError(SCRIPT_ERR_SIG_HIGH_S)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG, "P2PK with hybrid pubkey but no STRICTENC", 0 ).PushSig(keys.key0, SIGHASH_ALL)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG, "P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with hybrid pubkey but no STRICTENC", 0 ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0 ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).Num(0).PushSig(keys.key1, SIGHASH_ALL)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG, "1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).Num(0).PushSig(keys.key1, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK with undefined hashtype but no STRICTENC", 0 ).PushSig(keys.key1, 5)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key1, 5).ScriptError(SCRIPT_ERR_SIG_HASHTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0 ).PushSig(keys.key1, 5).DamagePush(10)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key1, 5).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_HASHTYPE)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3 with nonzero dummy but no NULLDUMMY", 0 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT, "3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT, "3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0 ).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY ).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true ).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with non-push scriptSig but with P2SH validation", 0 ).PushSig(keys.key2).Add(CScript() << OP_NOP8)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true ).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY ).Num(0).PushSig(keys.key1).PushSig(keys.key1)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH ).Num(11).PushSig(keys.key0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH ).Num(11).PushSig(keys.key0).ScriptError(SCRIPT_ERR_CLEANSTACK)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2SH with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH, true ).Num(11).PushSig(keys.key0).PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2SH with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true ).Num(11).PushSig(keys.key0).PushRedeem().ScriptError(SCRIPT_ERR_CLEANSTACK)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2SH with CLEANSTACK", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).PushRedeem()); std::set<std::string> tests_set; { UniValue json_tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests))); for (unsigned int idx = 0; idx < json_tests.size(); idx++) { const UniValue& tv = json_tests[idx]; tests_set.insert(JSONPrettyPrint(tv.get_array())); } } std::string strGen; BOOST_FOREACH(TestBuilder& test, tests) { test.Test(); std::string str = JSONPrettyPrint(test.GetJSON()); #ifndef UPDATE_JSON_TESTS if (tests_set.count(str) == 0) { BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment()); } #endif strGen += str + ",\n"; } #ifdef UPDATE_JSON_TESTS FILE* file = fopen("script_tests.json.gen", "w"); fputs(strGen.c_str(), file); fclose(file); #endif } BOOST_AUTO_TEST_CASE(script_json_test) { // Read tests from test/data/script_tests.json // Format is an array of arrays // Inner arrays are [ "scriptSig", "scriptPubKey", "flags", "expected_scripterror" ] // ... where scriptSig and scriptPubKey are stringified // scripts. UniValue tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; string strTest = test.write(); if (test.size() < 4) // Allow size > 3; extra stuff ignored (useful for comments) { if (test.size() != 1) { BOOST_ERROR("Bad test: " << strTest); } continue; } string scriptSigString = test[0].get_str(); CScript scriptSig = ParseScript(scriptSigString); string scriptPubKeyString = test[1].get_str(); CScript scriptPubKey = ParseScript(scriptPubKeyString); unsigned int scriptflags = ParseScriptFlags(test[2].get_str()); int scriptError = ParseScriptError(test[3].get_str()); DoTest(scriptPubKey, scriptSig, scriptflags, strTest, scriptError); } } BOOST_AUTO_TEST_CASE(script_PushData) { // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on // the stack as the 1-75 opcodes do. static const unsigned char direct[] = { 1, 0x5a }; static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a }; static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a }; static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a }; ScriptError err; vector<vector<unsigned char> > directStack; BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); vector<vector<unsigned char> > pushdata1Stack; BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), &err)); BOOST_CHECK(pushdata1Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); vector<vector<unsigned char> > pushdata2Stack; BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), &err)); BOOST_CHECK(pushdata2Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); vector<vector<unsigned char> > pushdata4Stack; BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), &err)); BOOST_CHECK(pushdata4Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } CScript sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction) { uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL); CScript result; // // NOTE: CHECKMULTISIG has an unfortunate bug; it requires // one extra item on the stack, before the signatures. // Putting OP_0 on the stack is the workaround; // fixing the bug would mean splitting the block chain (old // clients would not accept new CHECKMULTISIG transactions, // and vice-versa) // result << OP_0; BOOST_FOREACH(const CKey &key, keys) { vector<unsigned char> vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; } return result; } CScript sign_multisig(CScript scriptPubKey, const CKey &key, CTransaction transaction) { std::vector<CKey> keys; keys.push_back(key); return sign_multisig(scriptPubKey, keys, transaction); } BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) { ScriptError err; CKey key1, key2, key3; key1.MakeNewKey(true); key2.MakeNewKey(false); key3.MakeNewKey(true); CScript scriptPubKey12; scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CMutableTransaction txFrom12 = BuildCreditingTransaction(scriptPubKey12); CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), txFrom12); CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); txTo12.vout[0].nValue = 2; BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) { ScriptError err; CKey key1, key2, key3, key4; key1.MakeNewKey(true); key2.MakeNewKey(false); key3.MakeNewKey(true); key4.MakeNewKey(false); CScript scriptPubKey23; scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom23 = BuildCreditingTransaction(scriptPubKey23); CMutableTransaction txTo23 = BuildSpendingTransaction(CScript(), txFrom23); std::vector<CKey> keys; keys.push_back(key1); keys.push_back(key2); CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); keys.clear(); keys.push_back(key1); keys.push_back(key3); CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); keys.clear(); keys.push_back(key2); keys.push_back(key3); CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); keys.clear(); keys.push_back(key2); keys.push_back(key2); // Can't re-use sig CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); // Must have signatures CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); } BOOST_AUTO_TEST_CASE(script_combineSigs) { // Test the CombineSignatures function CBasicKeyStore keystore; vector<CKey> keys; vector<CPubKey> pubkeys; for (int i = 0; i < 3; i++) { CKey key; key.MakeNewKey(i%2 == 1); keys.push_back(key); pubkeys.push_back(key.GetPubKey()); keystore.AddKey(key); } CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(keys[0].GetPubKey().GetID())); CMutableTransaction txTo = BuildSpendingTransaction(CScript(), txFrom); CScript& scriptPubKey = txFrom.vout[0].scriptPubKey; CScript& scriptSig = txTo.vin[0].scriptSig; CScript empty; CScript combined = CombineSignatures(scriptPubKey, txTo, 0, empty, empty); BOOST_CHECK(combined.empty()); // Single signature case: SignSignature(keystore, txFrom, txTo, 0); // changes scriptSig combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig); BOOST_CHECK(combined == scriptSig); CScript scriptSigCopy = scriptSig; // Signing again will give a different, valid signature: SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig); // P2SH, single-signature case: CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG; keystore.AddCScript(pkSingle); scriptPubKey = GetScriptForDestination(CScriptID(pkSingle)); SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig); BOOST_CHECK(combined == scriptSig); scriptSigCopy = scriptSig; SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig); // dummy scriptSigCopy with placeholder, should always choose non-placeholder: scriptSigCopy = CScript() << OP_0 << vector<unsigned char>(pkSingle.begin(), pkSingle.end()); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, scriptSigCopy); BOOST_CHECK(combined == scriptSig); // Hardest case: Multisig 2-of-3 scriptPubKey = GetScriptForMultisig(2, pubkeys); keystore.AddCScript(scriptPubKey); SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig); BOOST_CHECK(combined == scriptSig); // A couple of partially-signed versions: vector<unsigned char> sig1; uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL); BOOST_CHECK(keys[0].Sign(hash1, sig1)); sig1.push_back(SIGHASH_ALL); vector<unsigned char> sig2; uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE); BOOST_CHECK(keys[1].Sign(hash2, sig2)); sig2.push_back(SIGHASH_NONE); vector<unsigned char> sig3; uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE); BOOST_CHECK(keys[2].Sign(hash3, sig3)); sig3.push_back(SIGHASH_SINGLE); // Not fussy about order (or even existence) of placeholders or signatures: CScript partial1a = CScript() << OP_0 << sig1 << OP_0; CScript partial1b = CScript() << OP_0 << OP_0 << sig1; CScript partial2a = CScript() << OP_0 << sig2; CScript partial2b = CScript() << sig2 << OP_0; CScript partial3a = CScript() << sig3; CScript partial3b = CScript() << OP_0 << OP_0 << sig3; CScript partial3c = CScript() << OP_0 << sig3 << OP_0; CScript complete12 = CScript() << OP_0 << sig1 << sig2; CScript complete13 = CScript() << OP_0 << sig1 << sig3; CScript complete23 = CScript() << OP_0 << sig2 << sig3; combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial1b); BOOST_CHECK(combined == partial1a); combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial2a); BOOST_CHECK(combined == complete12); combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial1a); BOOST_CHECK(combined == complete12); combined = CombineSignatures(scriptPubKey, txTo, 0, partial1b, partial2b); BOOST_CHECK(combined == complete12); combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial1b); BOOST_CHECK(combined == complete13); combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial3a); BOOST_CHECK(combined == complete23); combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial2b); BOOST_CHECK(combined == complete23); combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a); BOOST_CHECK(combined == partial3c); } BOOST_AUTO_TEST_CASE(script_standard_push) { ScriptError err; for (int i=0; i<67000; i++) { CScript script; script << i; BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push."); BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data."); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) { std::vector<unsigned char> data(i, '\111'); CScript script; script << data; BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push."); BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data."); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } } BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts) { // IsPushOnly returns false when given a script containing only pushes that // are invalid due to truncation. IsPushOnly() is consensus critical // because P2SH evaluation uses it, although this specific behavior should // not be consensus critical as the P2SH evaluation would fail first due to // the invalid push. Still, it doesn't hurt to test it explicitly. static const unsigned char direct[] = { 1 }; BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly()); } BOOST_AUTO_TEST_CASE(script_GetScriptAsm) { BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2, true)); BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY, true)); BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2)); BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY)); string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090"); string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2"); vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey)); BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[ALL] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[NONE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[SINGLE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[ALL|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[NONE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[SINGLE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "01 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "02 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "03 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "81 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "82 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "83 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey)); } static CScript ScriptFromHex(const char* hex) { std::vector<unsigned char> data = ParseHex(hex); return CScript(data.begin(), data.end()); } BOOST_AUTO_TEST_CASE(script_FindAndDelete) { // Exercise the FindAndDelete functionality CScript s; CScript d; CScript expect; s = CScript() << OP_1 << OP_2; d = CScript(); // delete nothing should be a no-op expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); s = CScript() << OP_1 << OP_2 << OP_3; d = CScript() << OP_2; expect = CScript() << OP_1 << OP_3; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = CScript() << OP_3 << OP_1 << OP_3 << OP_3 << OP_4 << OP_3; d = CScript() << OP_3; expect = CScript() << OP_1 << OP_4; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 4); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff03"); // PUSH 0x02ff03 onto stack d = ScriptFromHex("0302ff03"); expect = CScript(); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff030302ff03"); // PUSH 0x2ff03 PUSH 0x2ff03 d = ScriptFromHex("0302ff03"); expect = CScript(); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 2); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff030302ff03"); d = ScriptFromHex("02"); expect = s; // FindAndDelete matches entire opcodes BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff030302ff03"); d = ScriptFromHex("ff"); expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); // This is an odd edge case: strip of the push-three-bytes // prefix, leaving 02ff03 which is push-two-bytes: s = ScriptFromHex("0302ff030302ff03"); d = ScriptFromHex("03"); expect = CScript() << ParseHex("ff03") << ParseHex("ff03"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 2); BOOST_CHECK(s == expect); // Byte sequence that spans multiple opcodes: s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY d = ScriptFromHex("feed51"); expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); // doesn't match 'inside' opcodes BOOST_CHECK(s == expect); s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY d = ScriptFromHex("02feed51"); expect = ScriptFromHex("69"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = ScriptFromHex("516902feed5169"); d = ScriptFromHex("feed51"); expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); s = ScriptFromHex("516902feed5169"); d = ScriptFromHex("02feed51"); expect = ScriptFromHex("516969"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = CScript() << OP_0 << OP_0 << OP_1 << OP_1; d = CScript() << OP_0 << OP_1; expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = CScript() << OP_0 << OP_0 << OP_1 << OP_0 << OP_1 << OP_1; d = CScript() << OP_0 << OP_1; expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass BOOST_CHECK_EQUAL(s.FindAndDelete(d), 2); BOOST_CHECK(s == expect); // Another weird edge case: // End with invalid push (not enough data)... s = ScriptFromHex("0003feed"); d = ScriptFromHex("03feed"); // ... can remove the invalid push expect = ScriptFromHex("00"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = ScriptFromHex("0003feed"); d = ScriptFromHex("00"); expect = ScriptFromHex("03feed"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); } BOOST_AUTO_TEST_SUITE_END()
#include "L1Trigger/GlobalCaloTrigger/test/L1GctLutFromFile.h"
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE476_NULL_Pointer_Dereference__class_45.cpp Label Definition File: CWE476_NULL_Pointer_Dereference__class.label.xml Template File: sources-sinks-45.tmpl.cpp */ /* * @description * CWE: 476 NULL Pointer Dereference * BadSource: Set data to NULL * GoodSource: Initialize data * Sinks: * GoodSink: Check data for NULL before attempting to print data->a * BadSink : Print data->a * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file * * */ #include "std_testcase.h" namespace CWE476_NULL_Pointer_Dereference__class_45 { static TwoIntsClass * badData; static TwoIntsClass * goodG2BData; static TwoIntsClass * goodB2GData; #ifndef OMITBAD static void badSink() { TwoIntsClass * data = badData; /* POTENTIAL FLAW: Attempt to use data, which may be NULL */ printIntLine(data->intOne); /* avoid memory leak - deleting a NULL pointer is a no-op in C++ so no need to check for NULL */ delete data; } void bad() { TwoIntsClass * data; /* POTENTIAL FLAW: Set data to NULL */ data = NULL; badData = data; badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink() { TwoIntsClass * data = goodG2BData; /* POTENTIAL FLAW: Attempt to use data, which may be NULL */ printIntLine(data->intOne); /* avoid memory leak - deleting a NULL pointer is a no-op in C++ so no need to check for NULL */ delete data; } static void goodG2B() { TwoIntsClass * data; { TwoIntsClass * tmpData = new TwoIntsClass; tmpData->intOne = 0; tmpData->intTwo = 0; /* FIX: Initialize data */ data = tmpData; } goodG2BData = data; goodG2BSink(); } /* goodB2G() uses the BadSource with the GoodSink */ static void goodB2GSink() { TwoIntsClass * data = goodB2GData; /* FIX: Check for NULL before attempting to print data */ if (data != NULL) { printIntLine(data->intOne); delete data; } else { printLine("data is NULL"); } } static void goodB2G() { TwoIntsClass * data; /* POTENTIAL FLAW: Set data to NULL */ data = NULL; goodB2GData = data; goodB2GSink(); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE476_NULL_Pointer_Dereference__class_45; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
/* * Project2 - indexR * EECS 3540 - Project 2 * Jospeh Livecchi * Hash Table Source - A thread safe hash table with read/write locks. dynamical resizes, collisions are handled by linked list */ #include "SafeHashTable.h" SafeHashTable::SafeHashTable(){ //buckets = new vector<SafeBucket*>(); this->prime_cnt = -1; this->fill_ratio = 0.75; this->num_elemets = 0; this->table_size = NextCubanPrime(); this->buckets = new vector<SafeBucket*>(table_size, nullptr); pthread_rwlock_init(&table_lock, NULL); } SafeHashTable::~SafeHashTable(){ pthread_rwlock_destroy(&table_lock); for (auto it=buckets->begin(); it!=buckets->end(); ++it){ delete (*it); } } /* --------- Read Methods --------- */ SafeBucket* SafeHashTable::get(string w){ SafeBucket* temp_bucket = new SafeBucket(w); SafeBucket* result = nullptr; int rc = pthread_rwlock_rdlock(&table_lock); int loc = temp_bucket->hash() % table_size; if(buckets->at(loc) != nullptr ){ if( buckets->at(loc)->getWord() == temp_bucket->getWord() ){ result = buckets->at(loc); }else{ SafeBucket* link = buckets->at(loc)->getLink(); while( (link!= nullptr) ){ if( link->getWord() == temp_bucket->getWord()){ result = link; break; } link = link->getLink(); } } } rc = pthread_rwlock_unlock(&table_lock); delete temp_bucket; return result; } bool SafeHashTable::contains(string w){ SafeBucket* bucket = new SafeBucket(w); bool found = false; int rc = pthread_rwlock_rdlock(&table_lock); int loc = bucket->hash() % table_size; if(buckets->at(loc) == nullptr){ found = false; }else if(buckets->at(loc)->getWord() == bucket->getWord()){ found = true; }else{ SafeBucket* link = buckets->at(loc)->getLink(); while( (link!= nullptr) && !found ){ if( link->getWord() == bucket->getWord()) found = true; link = link->getLink(); } } pthread_rwlock_unlock(&table_lock); delete bucket; return found; } void SafeHashTable::checkTableSize(){ double cur_ratio = this->num_elemets / (double) table_size; if(cur_ratio > this->fill_ratio){ // cout << "The table needs to be resized! " << cur_ratio << ":" << this->fill_ratio << endl; resize(); } } int SafeHashTable::NextCubanPrime(){ //Cuban Prime numbers: 3y2 + 3y + 1 prime_cnt += 3; return (3*prime_cnt*prime_cnt) + (3*prime_cnt) + 1; } int SafeHashTable::count(){ pthread_rwlock_rdlock(&table_lock); return num_elemets; pthread_rwlock_unlock(&table_lock); } int SafeHashTable::size(){ pthread_rwlock_rdlock(&table_lock); return table_size; pthread_rwlock_unlock(&table_lock); } double SafeHashTable::ratio(){ pthread_rwlock_rdlock(&table_lock); return this->num_elemets / (double) table_size; pthread_rwlock_unlock(&table_lock); } void SafeHashTable::print(){ cout <<"Table Size: " << table_size << endl; for (int i = 0; i < table_size; i++){ if( buckets->at(i) != nullptr){ cout << "[" << i << "] : "; buckets->at(i)->print(); if(buckets->at(i)->getLink() != nullptr){ SafeBucket* link = buckets->at(i)->getLink(); while(link != nullptr){ cout << "\n\t -> "; link->print(); link = link->getLink(); } } cout << endl; } } } list<string>* SafeHashTable::getKeys(){ list<string>* keys = new list<string>(); pthread_rwlock_rdlock(&table_lock); for(auto it = buckets->begin(); it != buckets->end(); ++it){ SafeBucket* item = (*it); while(item != nullptr){ keys->push_back(item->getWord()); item = item->getLink(); } } pthread_rwlock_unlock(&table_lock); return keys; } /* -------------- Write Methods -------------- */ void SafeHashTable::insert(string w){ int rc = pthread_rwlock_wrlock(&table_lock); insert(new SafeBucket(w)); rc = pthread_rwlock_unlock(&table_lock); checkTableSize(); } void SafeHashTable::insert(SafeBucket* bucket){ int loc = bucket->hash() % table_size; if( buckets->at(loc) == nullptr){ buckets->at(loc) = bucket; }else{ SafeBucket* link_element = buckets->at(loc); while(link_element->getLink() != nullptr){ link_element = link_element->getLink(); } link_element->setLink(bucket); } this->num_elemets++; } void SafeHashTable::resize(){ int rc = pthread_rwlock_wrlock(&table_lock); int new_size = NextCubanPrime(); // cout << "=====================================================\n"; // cout << "Resizing!!! New Table size: " << new_size << endl; // cout << "Old Table Data: " << buckets->size() << " Cap: "<< buckets->capacity() << endl; vector<SafeBucket*>* old_buckets = buckets; this->buckets = new vector<SafeBucket*>(new_size, nullptr); // cout << "New Table Data: " << buckets->size() << " Cap: "<< buckets->capacity() << endl; // cout << "=====================================================\n"; num_elemets= 0; table_size = new_size; SafeBucket* temp_holder; SafeBucket* temp_link_holder; for( auto it = old_buckets->begin(); it != old_buckets->end(); ++it ){ temp_holder = (*it); while(temp_holder != nullptr){ temp_link_holder = temp_holder->getLink(); temp_holder->setLink(nullptr); insert(temp_holder); temp_holder = temp_link_holder; } } rc = pthread_rwlock_unlock(&table_lock); delete old_buckets; }
/* MANGO Multimedia Development Platform Copyright (C) 2012-2021 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include <mango/simd/simd.hpp> namespace mango::simd { // ----------------------------------------------------------------- // f64x2 // ----------------------------------------------------------------- #ifdef __aarch64__ #ifdef MANGO_COMPILER_CLANG template <u32 x, u32 y> static inline f64x2 shuffle(f64x2 v) { static_assert(x < 2 && y < 2, "Index out of range."); return __builtin_shufflevector(v.data, v.data, x, y + 2); } template <u32 x, u32 y> static inline f64x2 shuffle(f64x2 a, f64x2 b) { static_assert(x < 2 && y < 2, "Index out of range."); return __builtin_shufflevector(a.data, b.data, x, y + 2); } #else template <u32 x, u32 y> static inline f64x2 shuffle(f64x2 v) { static_assert(x < 2 && y < 2, "Index out of range."); float64x2_t result; result = vmovq_n_f64(vgetq_lane_f64(v, x)); result = vsetq_lane_f64(vgetq_lane_f64(v, y), result, 1); return result; } template <u32 x, u32 y> static inline f64x2 shuffle(f64x2 a, f64x2 b) { static_assert(x < 2 && y < 2, "Index out of range."); float64x2_t result; result = vmovq_n_f64(vgetq_lane_f64(a, x)); result = vsetq_lane_f64(vgetq_lane_f64(b, y), result, 1); return result; } #endif // MANGO_COMPILER_CLANG // indexed access template <unsigned int Index> static inline f64x2 set_component(f64x2 a, f64 s) { static_assert(Index < 2, "Index out of range."); return vsetq_lane_f64(s, a, Index); } template <unsigned int Index> static inline f64 get_component(f64x2 a) { static_assert(Index < 2, "Index out of range."); return vgetq_lane_f64(a, Index); } static inline f64x2 f64x2_zero() { return vdupq_n_f64(0.0); } static inline f64x2 f64x2_set(f64 s) { return vdupq_n_f64(s); } static inline f64x2 f64x2_set(f64 x, f64 y) { float64x2_t temp = { x, y }; return temp; } #if defined(MANGO_COMPILER_GCC) static inline f64x2 f64x2_uload(const f64* source) { f64x2 temp; std::memcpy(&temp, source, sizeof(temp)); return temp; } static inline void f64x2_ustore(f64* dest, f64x2 a) { std::memcpy(dest, &a, sizeof(a)); } #else static inline f64x2 f64x2_uload(const f64* source) { return vld1q_f64(source); } static inline void f64x2_ustore(f64* dest, f64x2 a) { vst1q_f64(dest, a); } #endif // MANGO_COMPILER_GCC static inline f64x2 unpackhi(f64x2 a, f64x2 b) { return vcombine_f64(vget_high_f64(a), vget_high_f64(b)); } static inline f64x2 unpacklo(f64x2 a, f64x2 b) { return vcombine_f64(vget_low_f64(a), vget_low_f64(b)); } // bitwise static inline f64x2 bitwise_nand(f64x2 a, f64x2 b) { return vreinterpretq_f64_s64(vbicq_s64(vreinterpretq_s64_f64(a), vreinterpretq_s64_f64(b))); } static inline f64x2 bitwise_and(f64x2 a, f64x2 b) { return vreinterpretq_f64_s64(vandq_s64(vreinterpretq_s64_f64(a), vreinterpretq_s64_f64(b))); } static inline f64x2 bitwise_or(f64x2 a, f64x2 b) { return vreinterpretq_f64_s64(vorrq_s64(vreinterpretq_s64_f64(a), vreinterpretq_s64_f64(b))); } static inline f64x2 bitwise_xor(f64x2 a, f64x2 b) { return vreinterpretq_f64_s64(veorq_s64(vreinterpretq_s64_f64(a), vreinterpretq_s64_f64(b))); } static inline f64x2 bitwise_not(f64x2 a) { return vreinterpretq_f64_u64(veorq_u64(vreinterpretq_u64_f64(a), vceqq_f64(a, a))); } static inline f64x2 min(f64x2 a, f64x2 b) { return vminq_f64(a, b); } static inline f64x2 max(f64x2 a, f64x2 b) { return vmaxq_f64(a, b); } static inline f64x2 abs(f64x2 a) { return vabsq_f64(a); } static inline f64x2 neg(f64x2 a) { return vnegq_f64(a); } static inline f64x2 sign(f64x2 a) { f64 x = vgetq_lane_f64(a, 0); f64 y = vgetq_lane_f64(a, 1); x = x < 0 ? -1.0 : (x > 0 ? 1.0 : 0.0); y = y < 0 ? -1.0 : (y > 0 ? 1.0 : 0.0); return f64x2_set(x, y); } static inline f64x2 add(f64x2 a, f64x2 b) { return vaddq_f64(a, b); } static inline f64x2 sub(f64x2 a, f64x2 b) { return vsubq_f64(a, b); } static inline f64x2 mul(f64x2 a, f64x2 b) { return vmulq_f64(a, b); } static inline f64x2 div(f64x2 a, f64x2 b) { return vdivq_f64(a, b); } static inline f64x2 div(f64x2 a, f64 b) { f64x2 s = vdupq_n_f64(b); return vdivq_f64(a, s); } static inline f64x2 hadd(f64x2 a, f64x2 b) { return vpaddq_f64(a, b); } static inline f64x2 hsub(f64x2 a, f64x2 b) { b = vnegq_f64(b); return vpaddq_f64(a, b); } static inline f64x2 madd(f64x2 a, f64x2 b, f64x2 c) { // a + b * c return vmlaq_f64(a, b, c); } static inline f64x2 msub(f64x2 a, f64x2 b, f64x2 c) { // b * c - a return vnegq_f64(vmlsq_f64(a, b, c)); } static inline f64x2 nmadd(f64x2 a, f64x2 b, f64x2 c) { // a - b * c return vmlsq_f64(a, b, c); } static inline f64x2 nmsub(f64x2 a, f64x2 b, f64x2 c) { // -(a + b * c) return vnegq_f64(vmlaq_f64(a, b, c)); } static inline f64x2 lerp(f64x2 a, f64x2 b, f64x2 s) { // a * (1.0 - s) + b * s // (a - a * s) + (b * s) return madd(nmadd(a, a, s), b, s); } #if defined(MANGO_FAST_MATH) static inline f64x2 rcp(f64x2 a) { f64x2 e = vrecpeq_f64(a); e = vmulq_f64(vrecpsq_f64(a, e), e); return e; } static inline f64x2 rsqrt(f64x2 a) { f64x2 e = vrsqrteq_f64(a); e = vmulq_f64(vrsqrtsq_f64(vmulq_f64(a, e), e), e); return e; } #else static inline f64x2 rcp(f64x2 a) { f64x2 e = vrecpeq_f64(a); e = vmulq_f64(vrecpsq_f64(a, e), e); e = vmulq_f64(vrecpsq_f64(a, e), e); return e; } static inline f64x2 rsqrt(f64x2 a) { f64x2 e = vrsqrteq_f64(a); e = vmulq_f64(vrsqrtsq_f64(vmulq_f64(a, e), e), e); e = vmulq_f64(vrsqrtsq_f64(vmulq_f64(a, e), e), e); return e; } #endif // MANGO_FAST_MATH static inline f64x2 sqrt(f64x2 a) { return vsqrtq_f64(a); } static inline f64 dot2(f64x2 a, f64x2 b) { const float64x2_t prod = vmulq_f64(a, b); return vaddvq_f64(prod); } // compare static inline mask64x2 compare_neq(f64x2 a, f64x2 b) { return veorq_u64(vceqq_f64(a, b), vceqq_f64(a, a)); } static inline mask64x2 compare_eq(f64x2 a, f64x2 b) { return vceqq_f64(a, b); } static inline mask64x2 compare_lt(f64x2 a, f64x2 b) { return vcltq_f64(a, b); } static inline mask64x2 compare_le(f64x2 a, f64x2 b) { return vcleq_f64(a, b); } static inline mask64x2 compare_gt(f64x2 a, f64x2 b) { return vcgtq_f64(a, b); } static inline mask64x2 compare_ge(f64x2 a, f64x2 b) { return vcgeq_f64(a, b); } static inline f64x2 select(mask64x2 mask, f64x2 a, f64x2 b) { return vbslq_f64(mask, a, b); } // rounding static inline f64x2 round(f64x2 s) { return vrndaq_f64(s); } static inline f64x2 trunc(f64x2 s) { return vrndq_f64(s); } static inline f64x2 floor(f64x2 s) { return vrndmq_f64(s); } static inline f64x2 ceil(f64x2 s) { return vrndpq_f64(s); } static inline f64x2 fract(f64x2 s) { return sub(s, floor(s)); } // ----------------------------------------------------------------- // masked functions // ----------------------------------------------------------------- static inline f64x2 min(f64x2 a, f64x2 b, mask64x2 mask) { return vreinterpretq_f64_u64(vandq_u64(mask, vreinterpretq_u64_f64(min(a, b)))); } static inline f64x2 max(f64x2 a, f64x2 b, mask64x2 mask) { return vreinterpretq_f64_u64(vandq_u64(mask, vreinterpretq_u64_f64(max(a, b)))); } static inline f64x2 add(f64x2 a, f64x2 b, mask64x2 mask) { return vreinterpretq_f64_u64(vandq_u64(mask, vreinterpretq_u64_f64(add(a, b)))); } static inline f64x2 sub(f64x2 a, f64x2 b, mask64x2 mask) { return vreinterpretq_f64_u64(vandq_u64(mask, vreinterpretq_u64_f64(sub(a, b)))); } static inline f64x2 mul(f64x2 a, f64x2 b, mask64x2 mask) { return vreinterpretq_f64_u64(vandq_u64(mask, vreinterpretq_u64_f64(mul(a, b)))); } static inline f64x2 div(f64x2 a, f64x2 b, mask64x2 mask) { return vreinterpretq_f64_u64(vandq_u64(mask, vreinterpretq_u64_f64(div(a, b)))); } // ----------------------------------------------------------------- // masked functions // ----------------------------------------------------------------- #define SIMD_MASK_DOUBLE128 #include "common_mask.hpp" #undef SIMD_MASK_DOUBLE128 #else // __aarch64__ template <u32 x, u32 y> static inline f64x2 shuffle(f64x2 v) { static_assert(x < 2 && y < 2, "Index out of range."); return {{ v.data[x], v.data[y] }}; } template <u32 x, u32 y> static inline f64x2 shuffle(f64x2 a, f64x2 b) { static_assert(x < 2 && y < 2, "Index out of range."); return {{ a.data[x], b.data[y] }}; } // indexed access template <unsigned int Index> static inline f64x2 set_component(f64x2 a, f64 s) { static_assert(Index < 2, "Index out of range."); a.data[Index] = s; return a; } template <unsigned int Index> static inline f64 get_component(f64x2 a) { static_assert(Index < 2, "Index out of range."); return a.data[Index]; } static inline f64x2 f64x2_zero() { return {{ 0.0, 0.0 }}; } static inline f64x2 f64x2_set(f64 s) { return {{ s, s }}; } static inline f64x2 f64x2_set(f64 x, f64 y) { return {{ x, y }}; } static inline f64x2 f64x2_uload(const f64* source) { return f64x2_set(source[0], source[1]); } static inline void f64x2_ustore(f64* dest, f64x2 a) { dest[0] = a.data[0]; dest[1] = a.data[1]; } static inline f64x2 unpackhi(f64x2 a, f64x2 b) { return f64x2_set(a.data[1], b.data[1]); } static inline f64x2 unpacklo(f64x2 a, f64x2 b) { return f64x2_set(a.data[0], b.data[0]); } // bitwise static inline f64x2 bitwise_nand(f64x2 a, f64x2 b) { const Double x(~Double(a.data[0]).u & Double(b.data[0]).u); const Double y(~Double(a.data[1]).u & Double(b.data[1]).u); return f64x2_set(x, y); } static inline f64x2 bitwise_and(f64x2 a, f64x2 b) { const Double x(Double(a.data[0]).u & Double(b.data[0]).u); const Double y(Double(a.data[1]).u & Double(b.data[1]).u); return f64x2_set(x, y); } static inline f64x2 bitwise_or(f64x2 a, f64x2 b) { const Double x(Double(a.data[0]).u | Double(b.data[0]).u); const Double y(Double(a.data[1]).u | Double(b.data[1]).u); return f64x2_set(x, y); } static inline f64x2 bitwise_xor(f64x2 a, f64x2 b) { const Double x(Double(a.data[0]).u ^ Double(b.data[0]).u); const Double y(Double(a.data[1]).u ^ Double(b.data[1]).u); return f64x2_set(x, y); } static inline f64x2 bitwise_not(f64x2 a) { const Double x(~Double(a.data[0]).u); const Double y(~Double(a.data[1]).u); return f64x2_set(x, y); } static inline f64x2 min(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = std::min(a.data[0], b.data[0]); v.data[1] = std::min(a.data[1], b.data[1]); return v; } static inline f64x2 max(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = std::max(a.data[0], b.data[0]); v.data[1] = std::max(a.data[1], b.data[1]); return v; } static inline f64x2 abs(f64x2 a) { f64x2 v; v.data[0] = std::abs(a.data[0]); v.data[1] = std::abs(a.data[1]); return v; } static inline f64x2 neg(f64x2 a) { return f64x2_set(-a.data[0], -a.data[1]); } static inline f64x2 sign(f64x2 a) { f64x2 v; v.data[0] = a.data[0] < 0 ? -1.0f : (a.data[0] > 0 ? 1.0f : 0.0f); v.data[1] = a.data[1] < 0 ? -1.0f : (a.data[1] > 0 ? 1.0f : 0.0f); return v; } static inline f64x2 add(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = a.data[0] + b.data[0]; v.data[1] = a.data[1] + b.data[1]; return v; } static inline f64x2 sub(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = a.data[0] - b.data[0]; v.data[1] = a.data[1] - b.data[1]; return v; } static inline f64x2 mul(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = a.data[0] * b.data[0]; v.data[1] = a.data[1] * b.data[1]; return v; } static inline f64x2 div(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = a.data[0] / b.data[0]; v.data[1] = a.data[1] / b.data[1]; return v; } static inline f64x2 div(f64x2 a, f64 b) { f64x2 v; v.data[0] = a.data[0] / b; v.data[1] = a.data[1] / b; return v; } static inline f64x2 hadd(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = a.data[0] + a.data[1]; v.data[1] = b.data[0] + b.data[1]; return v; } static inline f64x2 hsub(f64x2 a, f64x2 b) { f64x2 v; v.data[0] = a.data[0] - a.data[1]; v.data[1] = b.data[0] - b.data[1]; return v; } static inline f64x2 madd(f64x2 a, f64x2 b, f64x2 c) { // a + b * c f64x2 v; v.data[0] = a.data[0] + b.data[0] * c.data[0]; v.data[1] = a.data[1] + b.data[1] * c.data[1]; return v; } static inline f64x2 msub(f64x2 a, f64x2 b, f64x2 c) { // b * c - a f64x2 v; v.data[0] = b.data[0] * c.data[0] - a.data[0]; v.data[1] = b.data[1] * c.data[1] - a.data[1]; return v; } static inline f64x2 nmadd(f64x2 a, f64x2 b, f64x2 c) { // a - b * c f64x2 v; v.data[0] = a.data[0] - b.data[0] * c.data[0]; v.data[1] = a.data[1] - b.data[1] * c.data[1]; return v; } static inline f64x2 nmsub(f64x2 a, f64x2 b, f64x2 c) { // -(a + b * c) f64x2 v; v.data[0] = -(a.data[0] + b.data[0] * c.data[0]); v.data[1] = -(a.data[1] + b.data[1] * c.data[1]); return v; } static inline f64x2 lerp(f64x2 a, f64x2 b, f64x2 s) { // a * (1.0 - s) + b * s // (a - a * s) + (b * s) return madd(nmadd(a, a, s), b, s); } static inline f64x2 rcp(f64x2 a) { f64x2 v; v.data[0] = 1.0 / a.data[0]; v.data[1] = 1.0 / a.data[1]; return v; } static inline f64x2 rsqrt(f64x2 a) { f64x2 v; v.data[0] = 1.0 / std::sqrt(a.data[0]); v.data[1] = 1.0 / std::sqrt(a.data[1]); return v; } static inline f64x2 sqrt(f64x2 a) { f64x2 v; v.data[0] = std::sqrt(a.data[0]); v.data[1] = std::sqrt(a.data[1]); return v; } static inline f64 dot2(f64x2 a, f64x2 b) { return a.data[0] * b.data[0] + a.data[1] * b.data[1]; } // compare static inline mask64x2 compare_neq(f64x2 a, f64x2 b) { u64 x = a.data[0] != b.data[0] ? ~0 : 0; u64 y = a.data[1] != b.data[1] ? ~0 : 0; uint64x2_t mask = { x, y }; return mask; } static inline mask64x2 compare_eq(f64x2 a, f64x2 b) { u64 x = a.data[0] == b.data[0] ? ~0 : 0; u64 y = a.data[1] == b.data[1] ? ~0 : 0; uint64x2_t mask = { x, y }; return mask; } static inline mask64x2 compare_lt(f64x2 a, f64x2 b) { u64 x = a.data[0] < b.data[0] ? ~0 : 0; u64 y = a.data[1] < b.data[1] ? ~0 : 0; uint64x2_t mask = { x, y }; return mask; } static inline mask64x2 compare_le(f64x2 a, f64x2 b) { u64 x = a.data[0] <= b.data[0] ? ~0 : 0; u64 y = a.data[1] <= b.data[1] ? ~0 : 0; uint64x2_t mask = { x, y }; return mask; } static inline mask64x2 compare_gt(f64x2 a, f64x2 b) { u64 x = a.data[0] > b.data[0] ? ~0 : 0; u64 y = a.data[1] > b.data[1] ? ~0 : 0; uint64x2_t mask = { x, y }; return mask; } static inline mask64x2 compare_ge(f64x2 a, f64x2 b) { u64 x = a.data[0] >= b.data[0] ? ~0 : 0; u64 y = a.data[1] >= b.data[1] ? ~0 : 0; uint64x2_t mask = { x, y }; return mask; } static inline f64x2 select(mask64x2 mask, f64x2 a, f64x2 b) { f64x2 m; m.data[0] = vgetq_lane_u64(mask, 0); m.data[1] = vgetq_lane_u64(mask, 1); return bitwise_or(bitwise_and(m, a), bitwise_nand(m, b)); } // rounding static inline f64x2 round(f64x2 s) { f64x2 v; v.data[0] = std::round(s.data[0]); v.data[1] = std::round(s.data[1]); return v; } static inline f64x2 trunc(f64x2 s) { f64x2 v; v.data[0] = std::trunc(s.data[0]); v.data[1] = std::trunc(s.data[1]); return v; } static inline f64x2 floor(f64x2 s) { f64x2 v; v.data[0] = std::floor(s.data[0]); v.data[1] = std::floor(s.data[1]); return v; } static inline f64x2 ceil(f64x2 s) { f64x2 v; v.data[0] = std::ceil(s.data[0]); v.data[1] = std::ceil(s.data[1]); return v; } static inline f64x2 fract(f64x2 s) { f64x2 v; v.data[0] = s.data[0] - std::floor(s.data[0]); v.data[1] = s.data[1] - std::floor(s.data[1]); return v; } // ----------------------------------------------------------------- // masked functions // ----------------------------------------------------------------- #define SIMD_ZEROMASK_DOUBLE128 #define SIMD_MASK_DOUBLE128 #include <mango/simd/common_mask.hpp> #undef SIMD_ZEROMASK_DOUBLE128 #undef SIMD_MASK_DOUBLE128 #endif // __aarch64__ } // namespace mango::simd
/* ************************************************************************ * Copyright 2018-2019 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "cblas_interface.hpp" #include "near.hpp" #include "rocblas.hpp" #include "rocblas_init.hpp" #include "rocblas_math.hpp" #include "rocblas_random.hpp" #include "rocblas_test.hpp" #include "rocblas_vector.hpp" #include "unit.hpp" #include "utility.hpp" template <typename T1, typename T2 = T1> void testing_asum_batched_bad_arg_template(const Arguments& arg) { rocblas_int N = 100; rocblas_int incx = 1; rocblas_int batch_count = 5; static const size_t safe_size = 100; T2 rocblas_result = 10; T2* h_rocblas_result = &rocblas_result; rocblas_local_handle handle; device_batch_vector<T1> dx(N, 1, batch_count); CHECK_HIP_ERROR(dx.memcheck()); CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); EXPECT_ROCBLAS_STATUS( (rocblas_asum_batched<T1, T2>(handle, N, nullptr, incx, batch_count, h_rocblas_result)), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS( (rocblas_asum_batched<T1, T2>(handle, N, dx.ptr_on_device(), incx, batch_count, nullptr)), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS((rocblas_asum_batched<T1, T2>( nullptr, N, dx.ptr_on_device(), incx, batch_count, h_rocblas_result)), rocblas_status_invalid_handle); } template <typename T1, typename T2 = T1> void testing_asum_batched_template(const Arguments& arg) { rocblas_int N = arg.N; rocblas_int incx = arg.incx; rocblas_int batch_count = arg.batch_count; double rocblas_error_1; double rocblas_error_2; rocblas_local_handle handle; // check to prevent undefined memory allocation error if(N <= 0 || incx <= 0 || batch_count <= 0) { device_batch_vector<T1> dx(3, 1, 2); CHECK_HIP_ERROR(dx.memcheck()); device_vector<T2> dr(std::max(2, std::abs(batch_count))); CHECK_HIP_ERROR(dr.memcheck()); CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_device)); EXPECT_ROCBLAS_STATUS( (rocblas_asum_batched<T1, T2>(handle, N, dx.ptr_on_device(), incx, batch_count, dr)), (N > 0 && incx > 0 && batch_count < 0) ? rocblas_status_invalid_size : rocblas_status_success); return; } // Naming: dx is in GPU (device) memory. hx is in CPU (host) memory, plz follow this practice // allocate memory device_batch_vector<T1> dx(N, incx, batch_count); host_batch_vector<T1> hx(N, incx, batch_count); device_vector<T2> dr(batch_count); host_vector<T2> hr1(batch_count); host_vector<T2> hr(batch_count); CHECK_HIP_ERROR(dx.memcheck()); CHECK_HIP_ERROR(hx.memcheck()); CHECK_HIP_ERROR(dr.memcheck()); CHECK_HIP_ERROR(hr1.memcheck()); CHECK_HIP_ERROR(hr.memcheck()); // // Initialize memory on host. // rocblas_init(hx); // // Transfer from host to device. // CHECK_HIP_ERROR(dx.transfer_from(hx)); double gpu_time_used, cpu_time_used; if(arg.unit_check || arg.norm_check) { // GPU BLAS rocblas_pointer_mode_host CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); CHECK_ROCBLAS_ERROR( (rocblas_asum_batched<T1, T2>(handle, N, dx.ptr_on_device(), incx, batch_count, hr1))); // GPU BLAS rocblas_pointer_mode_device CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_device)); CHECK_ROCBLAS_ERROR( (rocblas_asum_batched<T1, T2>(handle, N, dx.ptr_on_device(), incx, batch_count, dr))); // // Transfer from device to host. // CHECK_HIP_ERROR(hr.transfer_from(dr)); T2 cpu_result[batch_count]; // CPU BLAS cpu_time_used = get_time_us(); for(int i = 0; i < batch_count; i++) { cblas_asum<T1, T2>(N, hx[i], incx, cpu_result + i); } cpu_time_used = get_time_us() - cpu_time_used; if(arg.unit_check) { unit_check_general<T2>(1, batch_count, 1, cpu_result, hr1); unit_check_general<T2>(1, batch_count, 1, cpu_result, hr); } if(arg.norm_check) { std::cout << "cpu=" << std::scientific << cpu_result[0] << ", gpu_host_ptr=" << hr1[0] << ", gpu_dev_ptr=" << hr[0] << "\n"; rocblas_error_1 = std::abs((cpu_result[0] - hr1[0]) / cpu_result[0]); rocblas_error_2 = std::abs((cpu_result[0] - hr[0]) / cpu_result[0]); } } if(arg.timing) { int number_cold_calls = 2; int number_hot_calls = 100; CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); for(int iter = 0; iter < number_cold_calls; iter++) { rocblas_asum_batched<T1, T2>(handle, N, dx.ptr_on_device(), incx, batch_count, hr1); } gpu_time_used = get_time_us(); // in microseconds for(int iter = 0; iter < number_hot_calls; iter++) { rocblas_asum_batched<T1, T2>(handle, N, dx.ptr_on_device(), incx, batch_count, hr1); } gpu_time_used = (get_time_us() - gpu_time_used) / number_hot_calls; std::cout << "N,incx,batch_count,rocblas(us)"; if(arg.norm_check) std::cout << ",CPU(us),error_host_ptr,error_dev_ptr"; std::cout << std::endl; std::cout << N << "," << incx << "," << batch_count << "," << gpu_time_used; if(arg.norm_check) std::cout << "," << cpu_time_used << "," << rocblas_error_1 << "," << rocblas_error_2; std::cout << std::endl; } } template <typename T> void testing_asum_batched_bad_arg(const Arguments& arg) { testing_asum_batched_bad_arg_template<T>(arg); } template <> void testing_asum_batched_bad_arg<rocblas_float_complex>(const Arguments& arg) { testing_asum_batched_bad_arg_template<rocblas_float_complex, float>(arg); } template <> void testing_asum_batched_bad_arg<rocblas_double_complex>(const Arguments& arg) { testing_asum_batched_bad_arg_template<rocblas_double_complex, double>(arg); } template <typename T> void testing_asum_batched(const Arguments& arg) { return testing_asum_batched_template<T>(arg); } template <> void testing_asum_batched<rocblas_float_complex>(const Arguments& arg) { return testing_asum_batched_template<rocblas_float_complex, float>(arg); } template <> void testing_asum_batched<rocblas_double_complex>(const Arguments& arg) { return testing_asum_batched_template<rocblas_double_complex, double>(arg); }
// Copyright 2010-2021, Google Inc. // 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 of conditions 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 materials provided with the // distribution. // * Neither the name of Google Inc. 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 "rewriter/english_variants_rewriter.h" #include <string> #include <vector> #include "base/logging.h" #include "base/mozc_hash_set.h" #include "base/util.h" #include "converter/segments.h" #include "protocol/commands.pb.h" #include "request/conversion_request.h" namespace mozc { EnglishVariantsRewriter::EnglishVariantsRewriter() {} EnglishVariantsRewriter::~EnglishVariantsRewriter() {} bool EnglishVariantsRewriter::ExpandEnglishVariants( const std::string &input, std::vector<std::string> *variants) const { DCHECK(variants); if (input.empty()) { return false; } // multi-word if (input.find(' ') != std::string::npos) { return false; } std::string lower = input; std::string upper = input; std::string capitalized = input; Util::LowerString(&lower); Util::UpperString(&upper); Util::CapitalizeString(&capitalized); if (lower == upper) { // given word is non-ascii. return false; } variants->clear(); // If |input| is non-standard expression, like "iMac", only // expand lowercase. if (input != lower && input != upper && input != capitalized) { variants->push_back(lower); return true; } if (input != lower) { variants->push_back(lower); } if (input != capitalized) { variants->push_back(capitalized); } if (input != upper) { variants->push_back(upper); } return true; } bool EnglishVariantsRewriter::IsT13NCandidate( Segment::Candidate *candidate) const { return (Util::IsEnglishTransliteration(candidate->content_value) && Util::GetScriptType(candidate->content_key) == Util::HIRAGANA); } bool EnglishVariantsRewriter::IsEnglishCandidate( Segment::Candidate *candidate) const { return (Util::IsEnglishTransliteration(candidate->content_value) && Util::GetScriptType(candidate->content_key) == Util::ALPHABET); } bool EnglishVariantsRewriter::ExpandEnglishVariantsWithSegment( Segment *seg) const { CHECK(seg); bool modified = false; mozc_hash_set<std::string> expanded_t13n_candidates; mozc_hash_set<std::string> original_candidates; for (size_t i = 0; i < seg->candidates_size(); ++i) { original_candidates.insert(seg->candidate(i).value); } for (int i = seg->candidates_size() - 1; i >= 0; --i) { Segment::Candidate *original_candidate = seg->mutable_candidate(i); DCHECK(original_candidate); // http://b/issue?id=5137299 // If the entry is comming from user dictionary, // expand English variants. if (original_candidate->attributes & Segment::Candidate::NO_VARIANTS_EXPANSION && !(original_candidate->attributes & Segment::Candidate::USER_DICTIONARY)) { continue; } if (IsT13NCandidate(original_candidate)) { if (expanded_t13n_candidates.find(original_candidate->value) != expanded_t13n_candidates.end()) { original_candidate->attributes |= Segment::Candidate::NO_VARIANTS_EXPANSION; continue; } // Expand T13N candidate variants modified = true; original_candidate->attributes |= Segment::Candidate::NO_VARIANTS_EXPANSION; std::vector<std::string> variants; if (ExpandEnglishVariants(original_candidate->content_value, &variants)) { CHECK(!variants.empty()); for (auto it = variants.rbegin(); it != variants.rend(); ++it) { std::string new_value; Util::ConcatStrings(*it, original_candidate->functional_value(), &new_value); expanded_t13n_candidates.insert(new_value); if (original_candidates.find(new_value) != original_candidates.end()) { continue; } Segment::Candidate *new_candidate = seg->insert_candidate(i + 1); DCHECK(new_candidate); new_candidate->Init(); new_candidate->value = std::move(new_value); new_candidate->key = original_candidate->key; new_candidate->content_value = std::move(*it); new_candidate->content_key = original_candidate->content_key; new_candidate->cost = original_candidate->cost; new_candidate->wcost = original_candidate->wcost; new_candidate->structure_cost = original_candidate->structure_cost; new_candidate->lid = original_candidate->lid; new_candidate->rid = original_candidate->rid; new_candidate->attributes |= Segment::Candidate::NO_VARIANTS_EXPANSION; } } } else if (IsEnglishCandidate(original_candidate)) { // Fix variants for English candidate modified = true; original_candidate->attributes |= Segment::Candidate::NO_VARIANTS_EXPANSION; } } return modified; } int EnglishVariantsRewriter::capability( const ConversionRequest &request) const { if (request.request().mixed_conversion()) { return RewriterInterface::ALL; } return RewriterInterface::CONVERSION; } bool EnglishVariantsRewriter::Rewrite(const ConversionRequest &request, Segments *segments) const { bool modified = false; for (size_t i = segments->history_segments_size(); i < segments->segments_size(); ++i) { Segment *seg = segments->mutable_segment(i); DCHECK(seg); modified |= ExpandEnglishVariantsWithSegment(seg); } return modified; } } // namespace mozc
/* * EasyWave - A realtime tsunami simulation program with GPU support. * Copyright (C) 2014 Andrey Babeyko, Johannes Spazier * GFZ German Research Centre for Geosciences (http://www.gfz-potsdam.de) * * Parts of this program (especially the GPU extension) were developed * within the context of the following publicly funded project: * - TRIDEC, EU 7th Framework Programme, Grant Agreement 258723 * (http://www.tridec-online.eu) * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"), * complemented with the following provision: For the scientific transparency * and verification of results obtained and communicated to the public after * using a modified version of the work, You (as the recipient of the source * code and author of this modified version, used to produce the published * results in scientific communications) commit to make this modified source * code available in a repository that is easily and freely accessible for a * duration of five years after the communication of the obtained results. * * You may not use this work except in compliance with the Licence. * * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. */ #define HEADER "\neasyWave ver.2013-04-11\n" #define DPCT_USM_LEVEL_NONE #include <CL/sycl.hpp> #include <dpct/dpct.hpp> #include "utilits.h" #include "easywave.h" #include "cOgrd.h" #include "cOkadaEarthquake.h" // CUDA kernels #include "kernels.dp.hpp" #include <cmath> double diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return (double)((double)temp.tv_nsec / 1000000000.0 + (double)temp.tv_sec); } int commandLineHelp( void ); int main( int argc, char **argv ) { dpct::device_ext &dev_ct1 = dpct::get_current_device(); sycl::queue &q_ct1 = dev_ct1.default_queue(); char buf[1024]; int ierr = 0; int argn; long int elapsed; int lastProgress,lastPropagation; int loop; // reading parameters from a file FILE *fp; char fileLabel[5]; unsigned short shval; int isBin,i,j,m,k; float fval; double dval; printf(HEADER); Err.setchannel(MSG_OUTFILE); // Read parameters from command line and use default struct EWPARAMS Par; // Bathymetry if( ( argn = utlCheckCommandLineOption( argc, argv, "grid", 4 ) ) != 0 ) { /* TODO: strdup not necessary here because all arguments in argv reside until program exit -> memory leak */ Par.fileBathymetry = strdup( argv[argn+1] ); } else return commandLineHelp(); // Source: Okada faults or Surfer grid if( ( argn = utlCheckCommandLineOption( argc, argv, "source", 6 ) ) != 0 ) { Par.fileSource = strdup( argv[argn+1] ); } else return commandLineHelp(); // Simulation time, [sec] if( ( argn = utlCheckCommandLineOption( argc, argv, "time", 4 ) ) != 0 ) { Par.timeMax = atoi( argv[argn+1] ); Par.timeMax *= 60; } else return commandLineHelp(); // Optional parameters or their default values // Model name if( ( argn = utlCheckCommandLineOption( argc, argv, "label", 3 ) ) != 0 ) { Par.modelName = strdup( argv[argn+1] ); } else Par.modelName = strdup( "eWave" ); // Deactivate logging if( ( argn = utlCheckCommandLineOption( argc, argv, "nolog", 5 ) ) != 0 ) ; else { Log.start( "easywave.log" ); Log.timestamp_disable(); } // Use Coriolis force //if( ( argn = utlCheckCommandLineOption( argc, argv, "coriolis", 3 ) ) != 0 ) // Par.coriolis = 1; //else Par.coriolis = 0; // Periodic dumping of mariograms and cumulative 2D-plots (wavemax, arrival times), [sec] if( ( argn = utlCheckCommandLineOption( argc, argv, "dump", 4 ) ) != 0 ) Par.outDump = atoi( argv[argn+1] ); else Par.outDump = 0; // Reporting simulation progress, [sec model time] if( ( argn = utlCheckCommandLineOption( argc, argv, "progress", 4 ) ) != 0 ) Par.outProgress = (int)(atof(argv[argn+1])*60); else Par.outProgress = 600; // 2D-wave propagation output, [sec model time] if( ( argn = utlCheckCommandLineOption( argc, argv, "propagation", 4 ) ) != 0 ) Par.outPropagation = (int)(atof(argv[argn+1])*60); else Par.outPropagation = 300; // minimal calculation depth, [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "min_depth", 9 ) ) != 0 ) Par.dmin = (float)atof(argv[argn+1]); else Par.dmin = 10.; // timestep, [sec] if( ( argn = utlCheckCommandLineOption( argc, argv, "step", 4 ) ) != 0 ) Par.dt = atoi(argv[argn+1]); else Par.dt = 0; // will be estimated automatically // Initial uplift: relative threshold if( ( argn = utlCheckCommandLineOption( argc, argv, "ssh0_rel", 8 ) ) != 0 ) Par.ssh0ThresholdRel = (float)atof(argv[argn+1]); else Par.ssh0ThresholdRel = 0.01; // Initial uplift: absolute threshold, [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "ssh0_abs", 8 ) ) != 0 ) Par.ssh0ThresholdAbs = (float)atof(argv[argn+1]); else Par.ssh0ThresholdAbs = 0.0; // Threshold for 2-D arrival time (0 - do not calculate), [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "ssh_arrival", 9 ) ) != 0 ) Par.sshArrivalThreshold = (float)atof(argv[argn+1]); else Par.sshArrivalThreshold = 0.001; // Threshold for clipping of expanding computational area, [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "ssh_clip", 8 ) ) != 0 ) Par.sshClipThreshold = (float)atof(argv[argn+1]); else Par.sshClipThreshold = 1.e-4; // Threshold for resetting the small ssh (keep expanding area from unnesessary growing), [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "ssh_zero", 8 ) ) != 0 ) Par.sshZeroThreshold = (float)atof(argv[argn+1]); else Par.sshZeroThreshold = 1.e-5; // Threshold for transparency (for png-output), [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "ssh_transparency", 8 ) ) != 0 ) Par.sshTransparencyThreshold = (float)atof(argv[argn+1]); else Par.sshTransparencyThreshold = 0.0; // Points Of Interest (POIs) input file if( ( argn = utlCheckCommandLineOption( argc, argv, "poi", 3 ) ) != 0 ) { Par.filePOIs = strdup( argv[argn+1] ); } else Par.filePOIs = NULL; // POI fitting: max search distance, [km] if( ( argn = utlCheckCommandLineOption( argc, argv, "poi_search_dist", 15 ) ) != 0 ) Par.poiDistMax = (float)atof(argv[argn+1]); else Par.poiDistMax = 10.0; Par.poiDistMax *= 1000.; // POI fitting: min depth, [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "poi_min_depth", 13 ) ) != 0 ) Par.poiDepthMin = (float)atof(argv[argn+1]); else Par.poiDepthMin = 1.0; // POI fitting: max depth, [m] if( ( argn = utlCheckCommandLineOption( argc, argv, "poi_max_depth", 13 ) ) != 0 ) Par.poiDepthMax = (float)atof(argv[argn+1]); else Par.poiDepthMax = 10000.0; // report of POI loading if( ( argn = utlCheckCommandLineOption( argc, argv, "poi_report", 7 ) ) != 0 ) Par.poiReport = 1; else Par.poiReport = 0; // POI output interval, [sec] if( ( argn = utlCheckCommandLineOption( argc, argv, "poi_dt_out", 10 ) ) != 0 ) Par.poiDt = atoi(argv[argn+1]); else Par.poiDt = 30; if( ( argn = utlCheckCommandLineOption( argc, argv, "gpu", 3 ) ) != 0 ) Par.gpu = true; else Par.gpu = false; if( ( argn = utlCheckCommandLineOption( argc, argv, "adjust_ztop", 11 ) ) != 0 ) Par.adjustZtop = true; else Par.adjustZtop = false; if( ( argn = utlCheckCommandLineOption( argc, argv, "verbose", 7 ) ) != 0 ) Par.verbose = true; else Par.verbose = false; // Log command line sprintf( buf, "Command line: " ); for( argn=1; argn<argc; argn++ ) { strcat( buf, " " ); strcat( buf, argv[argn] ); } Log.print( "%s", buf ); Log.print( "Loading bathymetry from %s", Par.fileBathymetry ); // check if bathymetry file is in ascii or binary format if( (fp=fopen(Par.fileBathymetry,"rb")) == NULL ) return Err.post( Err.msgOpenFile(Par.fileBathymetry) ); memset( fileLabel, 0, 5 ); ierr = fread( fileLabel, 4, 1, fp ); if( !strcmp( fileLabel,"DSAA" ) ) isBin = 0; else if( !strcmp( fileLabel,"DSBB" ) ) isBin = 1; else return Err.post( "%s: not GRD-file!", Par.fileBathymetry ); fclose(fp); // set the values of NLon and NLat int NLon, NLat; double LonMin, LatMin; double LonMax, LatMax; double DLon, DLat; double Dx, Dy; if( isBin ) { fp = fopen( Par.fileBathymetry, "rb" ); ierr = fread( fileLabel, 4, 1, fp ); ierr = fread( &shval, sizeof(unsigned short), 1, fp ); NLon = shval; ierr = fread( &shval, sizeof(unsigned short), 1, fp ); NLat = shval; } else { fp = fopen( Par.fileBathymetry, "rt" ); ierr = fscanf( fp, "%s", fileLabel ); ierr = fscanf( fp, " %d %d ", &NLon, &NLat ); } // set the values of min/max Lon and Lat if( isBin ) { ierr = fread( &LonMin, sizeof(double), 1, fp ); ierr = fread( &LonMax, sizeof(double), 1, fp ); ierr = fread( &LatMin, sizeof(double), 1, fp ); ierr = fread( &LatMax, sizeof(double), 1, fp ); ierr = fread( &dval, sizeof(double), 1, fp ); ierr = fread( &dval, sizeof(double), 1, fp ); // zmin zmax } else { ierr = fscanf( fp, " %lf %lf ", &LonMin, &LonMax ); ierr = fscanf( fp, " %lf %lf ", &LatMin, &LatMax ); ierr = fscanf( fp, " %*s %*s " ); // zmin, zmax } DLon = (LonMax - LonMin)/(NLon - 1); // in degrees DLat = (LatMax - LatMin)/(NLat - 1); Dx = Re * g2r( DLon ); // in m along the equator Dy = Re * g2r( DLat ); // allocate memory for GRIDNODE structure and for caching arrays float* node = (float*) malloc(sizeof(float)*NLon*NLat*MAX_VARS_PER_NODE); if (node == NULL) return Err.post( Err.msgAllocateMem() ); float* R6 = (float*) malloc( sizeof(float) * (NLat+1) ); if (R6 == NULL) return Err.post( Err.msgAllocateMem() ); float* C1 = (float*) malloc( sizeof(float) * (NLon+1) ); if (C1 == NULL) return Err.post( Err.msgAllocateMem() ); float* C3 = (float*) malloc( sizeof(float) * (NLon+1) ); if (C3 == NULL) return Err.post( Err.msgAllocateMem() ); float* C2 = (float*) malloc( sizeof(float) * (NLat+1) ); if (C2 == NULL) return Err.post( Err.msgAllocateMem() ); float* C4 = (float*) malloc( sizeof(float) * (NLat+1) ); if (C4 == NULL) return Err.post( Err.msgAllocateMem() ); if( isBin ) { /* NOTE: optimal would be reading everything in one step, but that does not work because rows and columns are transposed * (only possible with binary data at all) - use temporary buffer for now (consumes additional memory!) */ float *buf = new float[ NLat*NLon ]; ierr = fread( buf, sizeof(float), NLat*NLon, fp ); for( i=1; i<=NLon; i++ ) { for( j=1; j<=NLat; j++ ) { m = idx(j,i); if( isBin ) fval = buf[ (j-1) * NLon + (i-1) ]; //ierr = fread( &fval, sizeof(float), 1, fp ); Node(m, iTopo) = fval; Node(m, iTime) = -1; Node(m, iD) = -fval; if( Node(m, iD) < 0 ) { Node(m, iD) = 0.0f; } else if( Node(m, iD) < Par.dmin ) { Node(m, iD) = Par.dmin; } } } delete[] buf; } else { for( j=1; j<=NLat; j++ ) { for( i=1; i<=NLon; i++ ) { m = idx(j,i); ierr = fscanf( fp, " %f ", &fval ); Node(m, iTopo) = fval; Node(m, iTime) = -1; Node(m, iD) = -fval; if( Node(m, iD) < 0 ) { Node(m, iD) = 0.0f; } else if( Node(m, iD) < Par.dmin ) { Node(m, iD) = Par.dmin; } } } } for( k=1; k<MAX_VARS_PER_NODE-2; k++ ) { for( int i=1; i<=NLon; i++ ) { for( int j=1; j<=NLat; j++ ) { Node(idx(j,i), k) = 0; } } } fclose( fp ); if( !Par.dt ) { // time step not explicitly defined // Make bathymetry from topography. Compute stable time step. double dtLoc=RealMax; for( i=1; i<=NLon; i++ ) { for( j=1; j<=NLat; j++ ) { m = idx(j,i); if( Node(m, iD) == 0.0f ) continue; dtLoc = My_min( dtLoc, 0.8 * (Dx*cosdeg(getLat(j))) / sqrt(Gravity*Node(m, iD)) ); } } if( dtLoc > 15 ) Par.dt = 15; else if( dtLoc > 10 ) Par.dt = 10; else if( dtLoc > 5 ) Par.dt = 5; else if( dtLoc > 2 ) Par.dt = 2; else if( dtLoc > 1 ) Par.dt = 1; else return Err.post("Bathymetry requires too small time step (<1sec)"); Log.print("Stable CFL time step: %g sec", dtLoc); } // Correct bathymetry for edge artefacts for( i=1; i<=NLon; i++ ) { if( Node(idx(1,i), iD) != 0 && Node(idx(2,i), iD) == 0 ) Node(idx(1,i), iD) = 0.; if( Node(idx(NLat,i), iD) != 0 && Node(idx(NLat-1,i), iD) == 0 ) Node(idx(NLat,i), iD) = 0.; } for( j=1; j<=NLat; j++ ) { if( Node(idx(j,1), iD) != 0 && Node(idx(j,2), iD) == 0 ) Node(idx(j,1), iD) = 0.; if( Node(idx(j,NLon), iD) != 0 && Node(idx(j,NLon-1), iD) == 0 ) Node(idx(j,NLon), iD) = 0.; } // Calculate caching grid parameters for speedup for( j=1; j<=NLat; j++ ) { R6[j] = cosdeg( LatMin + (j-0.5)*DLat ); } for( i=1; i<=NLon; i++ ) { for( j=1; j<=NLat; j++ ) { m = idx(j,i); if( Node(m, iD) == 0 ) continue; Node(m, iR1) = Par.dt/Dy/R6[j]; if( i != NLon ) { if( Node(m+NLat, iD) != 0 ) { Node(m, iR2) = 0.5*Gravity*Par.dt/Dy/R6[j]*(Node(m, iD)+Node(m+NLat, iD)); Node(m, iR3) = 0.5*Par.dt*Omega*sindeg( LatMin + (j-0.5)*DLat ); } } else { Node(m, iR2) = 0.5*Gravity*Par.dt/Dy/R6[j]*Node(m, iD)*2; Node(m, iR3) = 0.5*Par.dt*Omega*sindeg( LatMin + (j-0.5)*DLat ); } if( j != NLat ) { if( Node(m+1, iD) != 0 ) { Node(m, iR4) = 0.5*Gravity*Par.dt/Dy*(Node(m, iD)+Node(m+1, iD)); Node(m, iR5) = 0.5*Par.dt*Omega*sindeg( LatMin + j*DLat ); } } /* FIXME: Bug? */ else { Node(m, iR2) = 0.5*Gravity*Par.dt/Dy*Node(m, iD)*2; Node(m, iR3) = 0.5*Par.dt*Omega*sindeg( LatMin + j*DLat ); } } } for( i=1; i<=NLon; i++ ) { C1[i] = 0; if( Node(idx(1,i), iD) != 0 ) C1[i] = 1./sqrt(Gravity*Node(idx(1,i), iD)); C3[i] = 0; if( Node(idx(NLat,i), iD) != 0 ) C3[i] = 1./sqrt(Gravity*Node(idx(NLat,i), iD)); } for( j=1; j<=NLat; j++ ) { C2[j] = 0; if( Node(idx(j,1), iD) != 0 ) C2[j] = 1./sqrt(Gravity*Node(idx(j,1), iD)); C4[j] = 0; if( Node(idx(j,NLon), iD) != 0 ) C4[j] = 1./sqrt(Gravity*Node(idx(j,NLon), iD)); } int NPOIs = 0; // read first record and get idea about the input type char record[256], /*buf[256],*/id[64]; FILE *fpAcc,*fpRej; int i0,j0,imin,imax,jmin,jmax,flag,it,n; int rad,nmin; double d2,d2min,lenLon,lenLat,depth; //double POIdistMax,POIdepthMin,POIdepthMax; double lon, lat; char **idPOI; long* idxPOI; int* flagRunupPOI; float **sshPOI; int* timePOI = NULL; int NtPOI; // Read points of interest if( Par.filePOIs != NULL ) { Log.print("Loading POIs from %s", Par.filePOIs ); int MaxPOIs = utlGetNumberOfRecords( Par.filePOIs ); if( !MaxPOIs ) return Err.post( "Empty POIs file" ); idPOI = new char*[MaxPOIs]; if( !idPOI ) return Err.post( Err.msgAllocateMem() ); idxPOI = new long[MaxPOIs]; if( !idxPOI ) return Err.post( Err.msgAllocateMem() ); flagRunupPOI = new int[MaxPOIs]; if( !flagRunupPOI ) return Err.post( Err.msgAllocateMem() ); sshPOI = new float*[MaxPOIs]; if( !sshPOI ) return Err.post( Err.msgAllocateMem() ); fp = fopen( Par.filePOIs, "rt" ); int line = 0; utlReadNextRecord( fp, record, &line ); int itype = sscanf( record, "%s %s %s", buf, buf, buf ); fclose( fp ); if( itype == 2 ) { // poi-name and grid-index fp = fopen( Par.filePOIs, "rt" ); line = NPOIs = 0; while( utlReadNextRecord( fp, record, &line ) != EOF ) { i = sscanf( record, "%s %d", id, &nmin ); if( i != 2 ) { Log.print( "! Bad POI record: %s", record ); continue; } idPOI[NPOIs] = strdup(id); idxPOI[NPOIs] = nmin; flagRunupPOI[NPOIs] = 1; NPOIs++; } fclose( fp ); Log.print( "%d POIs of %d loaded successfully; %d POIs rejected", NPOIs, MaxPOIs, (MaxPOIs-NPOIs) ); } else if( itype == 3 ) { // poi-name and coordinates if( Par.poiReport ) { fpAcc = fopen( "poi_accepted.lst", "wt" ); fprintf( fpAcc, "ID lon lat lonIJ latIJ depthIJ dist[km]\n" ); fpRej = fopen( "poi_rejected.lst", "wt" ); } lenLat = My_PI*Re/180; fp = fopen( Par.filePOIs, "rt" ); line = NPOIs = 0; while( utlReadNextRecord( fp, record, &line ) != EOF ) { i = sscanf( record, "%s %lf %lf %d", id, &lon, &lat, &flag ); if( i == 3 ) flag = 1; else if( i == 4 ) ; else { Log.print( "! Bad POI record: %s", record ); if( Par.poiReport ) fprintf( fpRej, "%s\n", record ); continue; } // find the closest water grid node. Local distances could be // treated as cartesian (2 min cell distortion at 60 degrees is only about 2 meters or 0.2%) i0 = (int)((lon - LonMin)/DLon) + 1; j0 = (int)((lat - LatMin)/DLat) + 1; if( i0<1 || i0>NLon || j0<1 || j0>NLat ) { Log.print( "!POI out of grid: %s", record ); if( Par.poiReport ) fprintf( fpRej, "%s\n", record ); continue; } lenLon = lenLat * R6[j0]; for( nmin=-1,rad=0; rad<NLon && rad<NLat; rad++ ) { d2min = RealMax; imin = i0-rad; if( imin < 1 ) imin = 1; imax = i0+rad+1; if( imax > NLon ) imax = NLon; jmin = j0-rad; if( jmin < 1 ) jmin = 1; jmax = j0+rad+1; if( jmax > NLat ) jmax = NLat; for( i=imin; i<=imax; i++ ) for( j=jmin; j<=jmax; j++ ) { if( i != imin && i != imax && j != jmin && j != jmax ) continue; n = idx(j,i); depth = Node(n, iD); if( depth < Par.poiDepthMin || depth > Par.poiDepthMax ) continue; d2 = pow( lenLon*(lon-getLon(i)), 2. ) + pow( lenLat*(lat-getLat(j)), 2. ); if( d2 < d2min ) { d2min = d2; nmin = n; } } if( nmin > 0 ) break; } if (sqrt(d2min) > Par.poiDistMax) { Log.print( "! Closest water node too far: %s", record ); if( Par.poiReport ) fprintf( fpRej, "%s\n", record ); continue; } idPOI[NPOIs] = strdup(id); idxPOI[NPOIs] = nmin; flagRunupPOI[NPOIs] = flag; NPOIs++; i = nmin/NLat + 1; j = nmin - (i-1)*NLat + 1; if( Par.poiReport ) fprintf(fpAcc, "%s %.4f %.4f %.4f %.4f %.1f %.3f\n", id, lon, lat, getLon(i), getLat(j), Node(nmin, iD), sqrt(d2min) / 1000); } fclose( fp ); Log.print( "%d POIs of %d loaded successfully; %d POIs rejected", NPOIs, MaxPOIs, (MaxPOIs-NPOIs) ); if( Par.poiReport ) { fclose( fpAcc ); fclose( fpRej ); } } // if mareograms if( Par.poiDt ) { NtPOI = Par.timeMax/Par.poiDt + 1; timePOI = new int[NtPOI]; for( it=0; it<NtPOI; it++ ) timePOI[it] = -1; for( n=0; n<NPOIs; n++ ) { sshPOI[n] = new float[NtPOI]; for( it=0; it<NtPOI; it++ ) sshPOI[n][it] = 0.; } } } // Init tsunami with faults or uplift-grid //ierr = ewSource(); if(ierr) return ierr; char dsaa_label[8]; int srcType; double dz,absuzmax,absuzmin; cOkadaEarthquake eq; cOgrd uZ; // check input file type: GRD or fault if( (fp = fopen( Par.fileSource, "rb" )) == NULL ) return Err.post( Err.msgOpenFile(Par.fileSource) ); memset( dsaa_label, 0, 5 ); ierr = fread( dsaa_label, 4, 1, fp ); if( !strcmp( dsaa_label,"DSAA" ) || !strcmp( dsaa_label,"DSBB" ) ) srcType = 1; else srcType = 2; fclose(fp); // load GRD file if( srcType == 1) { ierr = uZ.readGRD( Par.fileSource ); if(ierr) return ierr; } // read fault(s) from file if( srcType == 2) { int effSymSource = 0; //long l; double dist,energy,factLat,effRad,effMax; ierr = eq.read( Par.fileSource ); if(ierr) return ierr; if( Par.adjustZtop ) { // check fault parameters Err.disable(); ierr = eq.finalizeInput(); while( ierr ) { i = ierr/10; ierr = ierr - 10*i; if( ierr == FLT_ERR_STRIKE ) { Log.print( "No strike on input: Employing effective symmetric source model" ); if( eq.nfault > 1 ) { Err.enable(); return Err.post("Symmetric source assumes only 1 fault"); } eq.fault[0].strike = 0.; effSymSource = 1; } else if( ierr == FLT_ERR_ZTOP ) { Log.print( "Automatic depth correction to fault top @ 10 km" ); eq.fault[i].depth = eq.fault[i].width/2 * sindeg(eq.fault[i].dip) + 10.e3; } else { Err.enable(); return ierr; } ierr = eq.finalizeInput(); } Err.enable(); } else { // check fault parameters Err.disable(); ierr = eq.finalizeInput(); if( ierr ) { i = ierr/10; ierr = ierr - 10*i; if( ierr != FLT_ERR_STRIKE ) { Err.enable(); ierr = eq.finalizeInput(); return ierr; } Log.print( "No strike on input: Employing effective symmetric source model" ); Err.enable(); if( eq.nfault > 1 ) return Err.post("symmetric source assumes only 1 fault"); eq.fault[0].strike = 0.; effSymSource = 1; ierr = eq.finalizeInput(); if(ierr) return ierr; } Err.enable(); } // calculate uplift on a rectangular grid // set grid resolution, grid dimensions will be set automatically uZ.dx = DLon; uZ.dy = DLat; ierr = eq.calculate( uZ ); if(ierr) return ierr; if( effSymSource ) { // integrate for tsunami energy energy = 0.; for( j=0; j<uZ.ny; j++ ) { factLat = Dx*cosdeg(uZ.getY(0,j))*Dy; for( i=0; i<uZ.nx; i++ ) energy += pow(uZ(i, j), 2.) * factLat; } energy *= (1000*9.81/2); effRad = eq.fault[0].length / sqrt(2 * M_PI); effMax = 1. / effRad / sqrt(M_PI / 2) / sqrt(1000 * 9.81 / 2) * sqrt(energy); Log.print( "Effective source radius: %g km, max height: %g m", effRad/1000, effMax ); // transfer uplift onto tsunami grid and define deformed area for acceleration for( i=0; i<uZ.nx; i++ ) { for( j=0; j<uZ.ny; j++ ) { dist = GeoDistOnSphere( uZ.getX(i,j),uZ.getY(i,j), eq.fault[0].lon,eq.fault[0].lat ) * 1000; if( dist < effRad ) uZ(i, j) = effMax * cos(M_PI / 2 * dist / effRad); else uZ(i,j) = 0.; } } } // effective source } // src_type == fault // remove noise in the source absuzmax = uZ.getMaxAbsVal(); if( (Par.ssh0ThresholdRel + Par.ssh0ThresholdAbs) != 0 ) { absuzmin = RealMax; if( Par.ssh0ThresholdRel != 0 ) absuzmin = Par.ssh0ThresholdRel*absuzmax; if( Par.ssh0ThresholdAbs != 0 && Par.ssh0ThresholdAbs < absuzmin ) absuzmin = Par.ssh0ThresholdAbs; for( i=0; i<uZ.nx; i++ ) { for( j=0; j<uZ.ny; j++ ) { if (fabs(uZ(i, j)) < absuzmin) uZ(i, j) = 0; } } } // calculated (if needed) arrival threshold (negative value means it is relative) if (Par.sshArrivalThreshold < 0) Par.sshArrivalThreshold = absuzmax * fabs(Par.sshArrivalThreshold); // transfer uplift onto tsunami grid and define deformed area for acceleration // set initial min and max values int Imin = NLon; int Imax = 1; int Jmin = NLat; int Jmax = 1; /* FIXME: change loops */ for( i=1; i<=NLon; i++ ) { for( j=1; j<=NLat; j++ ) { lon = getLon(i); lat = getLat(j); if( Node(idx(j,i), iD) != 0. ) dz = Node(idx(j,i), iH) = uZ.getVal( lon,lat ); else dz = Node(idx(j,i), iH) = 0.; if (fabs(dz) > Par.sshClipThreshold) { Imin = My_min( Imin, i ); Imax = My_max( Imax, i ); Jmin = My_min( Jmin, j ); Jmax = My_max( Jmax, j ); } } } if( Imin == NLon ) return Err.post( "Zero initial displacement" ); Imin = My_max( Imin - 2, 2 ); Imax = My_min( Imax + 2, NLon-1 ); Jmin = My_max( Jmin - 2, 2 ); Jmax = My_min( Jmax + 2, NLat-1 ); Log.print( "Read source from %s", Par.fileSource ); // Write model parameters into the log Log.print("\nModel parameters for this simulation:"); Log.print("timestep: %d sec", Par.dt); Log.print("max time: %g min", (float)Par.timeMax/60); Log.print("poi_dt_out: %d sec", Par.poiDt); Log.print("poi_report: %s", (Par.poiReport ? "yes" : "no") ); Log.print("poi_search_dist: %g km", Par.poiDistMax/1000.); Log.print("poi_min_depth: %g m", Par.poiDepthMin); Log.print("poi_max_depth: %g m", Par.poiDepthMax); //Log.print("coriolis: %s", (Par.coriolis ? "yes" : "no") ); Log.print("min_depth: %g m", Par.dmin); Log.print("ssh0_rel: %g", Par.ssh0ThresholdRel); Log.print("ssh0_abs: %g m", Par.ssh0ThresholdAbs); Log.print("ssh_arrival: %g m", Par.sshArrivalThreshold); Log.print("ssh_clip: %g m", Par.sshClipThreshold); Log.print("ssh_zero: %g m", Par.sshZeroThreshold); Log.print("ssh_transparency: %g m\n", Par.sshTransparencyThreshold); int Nrec2DOutput; char* IndexFile; if( Par.outPropagation ) { // start index file sprintf( buf, "%s.2D.idx", Par.modelName ); IndexFile = strdup(buf); fp = fopen( IndexFile, "wt" ); fprintf( fp, "%g %g %d %g %g %d\n", LonMin, LonMax, NLon, LatMin, LatMax, NLat ); fclose( fp ); Nrec2DOutput = 0; } short nOutI; short nOutJ; double lonOutMin; double lonOutMax; double latOutMin; double latOutMax; double dtmp; float ftmp; Log.print("Starting main loop..."); timespec start, inter, end; clock_gettime(CLOCK_MONOTONIC, &start); float* d_node; dpct::dpct_malloc((void **)&d_node, sizeof(float) * NLat * NLon * MAX_VARS_PER_NODE); dpct::async_dpct_memcpy(d_node, node, sizeof(float) * NLat * NLon * MAX_VARS_PER_NODE, dpct::host_to_device); float* d_R6; dpct::dpct_malloc((void **)&d_R6, sizeof(float) * (NLat + 1)); dpct::async_dpct_memcpy(d_R6, R6, sizeof(float) * (NLat + 1), dpct::host_to_device); float* d_C2; dpct::dpct_malloc((void **)&d_C2, sizeof(float) * (NLat + 1)); dpct::async_dpct_memcpy(d_C2, C2, sizeof(float) * (NLat + 1), dpct::host_to_device); float* d_C4; dpct::dpct_malloc((void **)&d_C4, sizeof(float) * (NLat + 1)); dpct::async_dpct_memcpy(d_C4, C4, sizeof(float) * (NLat + 1), dpct::host_to_device); float* d_C1; dpct::dpct_malloc((void **)&d_C1, sizeof(float) * (NLon + 1)); dpct::async_dpct_memcpy(d_C1, C1, sizeof(float) * (NLon + 1), dpct::host_to_device); float* d_C3; dpct::dpct_malloc((void **)&d_C3, sizeof(float) * (NLon + 1)); dpct::async_dpct_memcpy(d_C3, C3, sizeof(float) * (NLon + 1), dpct::host_to_device); int* d_Imin; dpct::dpct_malloc((void **)&d_Imin, sizeof(int)); int* d_Imax; dpct::dpct_malloc((void **)&d_Imax, sizeof(int)); int* d_Jmin; dpct::dpct_malloc((void **)&d_Jmin, sizeof(int)); int* d_Jmax; dpct::dpct_malloc((void **)&d_Jmax, sizeof(int)); for( Par.time=0,loop=1,lastProgress=Par.outProgress,lastPropagation=Par.outPropagation; Par.time<=Par.timeMax; loop++,Par.time+=Par.dt,lastProgress+=Par.dt,lastPropagation+=Par.dt ) { /* FIXME: check if Par.poiDt can be used for those purposes */ if( Par.filePOIs && Par.poiDt && ((Par.time/Par.poiDt)*Par.poiDt == Par.time) ) { // SavePOIs dpct::dpct_memcpy(node, d_node, sizeof(float) * NLat * NLon * MAX_VARS_PER_NODE, dpct::device_to_host); it = Par.time / Par.poiDt; timePOI[it] = Par.time; for( n=0; n<NPOIs; n++ ) { float ampFactor = 1.; if( flagRunupPOI[n] ) ampFactor = pow( Node(idxPOI[n], iD), 0.25 ); sshPOI[n][it] = ampFactor * Node(idxPOI[n], iH); } } // sea floor topography (mass conservation) sycl::range<3> grids((Jmax - Jmin + 16) / 16, (Imax - Imin + 16) / 16, 1); sycl::range<3> threads(16, 16, 1); { dpct::buffer_t d_node_buf_ct0 = dpct::get_buffer(d_node); dpct::buffer_t d_R6_buf_ct1 = dpct::get_buffer(d_R6); q_ct1.submit([&](sycl::handler &cgh) { auto d_node_acc_ct0 = d_node_buf_ct0.get_access<sycl::access::mode::read_write>(cgh); auto d_R6_acc_ct1 = d_R6_buf_ct1.get_access<sycl::access::mode::read_write>(cgh); auto dpct_global_range = grids * threads; cgh.parallel_for( sycl::nd_range<3>( sycl::range<3>(dpct_global_range.get(2), dpct_global_range.get(1), dpct_global_range.get(0)), sycl::range<3>(threads.get(2), threads.get(1), threads.get(0))), [=](sycl::nd_item<3> item_ct1) { kernel((float *)(&d_node_acc_ct0[0]), (float *)(&d_R6_acc_ct1[0]), Imin, Jmin, Imax, Jmax, NLat, Par.sshZeroThreshold, Par.sshArrivalThreshold, Par.time, item_ct1); }); }); } { dpct::buffer_t d_node_buf_ct0 = dpct::get_buffer(d_node); dpct::buffer_t d_C1_buf_ct1 = dpct::get_buffer(d_C1); dpct::buffer_t d_C2_buf_ct2 = dpct::get_buffer(d_C2); dpct::buffer_t d_C3_buf_ct3 = dpct::get_buffer(d_C3); dpct::buffer_t d_C4_buf_ct4 = dpct::get_buffer(d_C4); q_ct1.submit([&](sycl::handler &cgh) { auto d_node_acc_ct0 = d_node_buf_ct0.get_access<sycl::access::mode::read_write>(cgh); auto d_C1_acc_ct1 = d_C1_buf_ct1.get_access<sycl::access::mode::read_write>(cgh); auto d_C2_acc_ct2 = d_C2_buf_ct2.get_access<sycl::access::mode::read_write>(cgh); auto d_C3_acc_ct3 = d_C3_buf_ct3.get_access<sycl::access::mode::read_write>(cgh); auto d_C4_acc_ct4 = d_C4_buf_ct4.get_access<sycl::access::mode::read_write>(cgh); cgh.parallel_for( sycl::nd_range<3>(sycl::range<3>(1, 1, 1), sycl::range<3>(1, 1, 1)), [=](sycl::nd_item<3> item_ct1) { kernel2((float *)(&d_node_acc_ct0[0]), (const float *)(&d_C1_acc_ct1[0]), (const float *)(&d_C2_acc_ct2[0]), (const float *)(&d_C3_acc_ct3[0]), (const float *)(&d_C4_acc_ct4[0]), Imin, Jmin, Imax, Jmax, NLat, NLon); }); }); } { dpct::buffer_t d_node_buf_ct0 = dpct::get_buffer(d_node); dpct::buffer_t d_R6_buf_ct1 = dpct::get_buffer(d_R6); q_ct1.submit([&](sycl::handler &cgh) { auto d_node_acc_ct0 = d_node_buf_ct0.get_access<sycl::access::mode::read_write>(cgh); auto d_R6_acc_ct1 = d_R6_buf_ct1.get_access<sycl::access::mode::read_write>(cgh); auto dpct_global_range = grids * threads; cgh.parallel_for( sycl::nd_range<3>( sycl::range<3>(dpct_global_range.get(2), dpct_global_range.get(1), dpct_global_range.get(0)), sycl::range<3>(threads.get(2), threads.get(1), threads.get(0))), [=](sycl::nd_item<3> item_ct1) { kernel3((float *)(&d_node_acc_ct0[0]), (float *)(&d_R6_acc_ct1[0]), Imin, Jmin, Imax, Jmax, NLat, item_ct1); }); }); } dpct::dpct_memcpy(d_Imin, &Imin, sizeof(int), dpct::host_to_device); dpct::dpct_memcpy(d_Imax, &Imax, sizeof(int), dpct::host_to_device); dpct::dpct_memcpy(d_Jmin, &Jmin, sizeof(int), dpct::host_to_device); dpct::dpct_memcpy(d_Jmax, &Jmax, sizeof(int), dpct::host_to_device); { dpct::buffer_t d_node_buf_ct0 = dpct::get_buffer(d_node); dpct::buffer_t d_C1_buf_ct1 = dpct::get_buffer(d_C1); dpct::buffer_t d_C2_buf_ct2 = dpct::get_buffer(d_C2); dpct::buffer_t d_C3_buf_ct3 = dpct::get_buffer(d_C3); dpct::buffer_t d_C4_buf_ct4 = dpct::get_buffer(d_C4); dpct::buffer_t d_Imin_buf_ct5 = dpct::get_buffer(d_Imin); dpct::buffer_t d_Jmin_buf_ct6 = dpct::get_buffer(d_Jmin); dpct::buffer_t d_Imax_buf_ct7 = dpct::get_buffer(d_Imax); dpct::buffer_t d_Jmax_buf_ct8 = dpct::get_buffer(d_Jmax); q_ct1.submit([&](sycl::handler &cgh) { auto d_node_acc_ct0 = d_node_buf_ct0.get_access<sycl::access::mode::read_write>(cgh); auto d_C1_acc_ct1 = d_C1_buf_ct1.get_access<sycl::access::mode::read_write>(cgh); auto d_C2_acc_ct2 = d_C2_buf_ct2.get_access<sycl::access::mode::read_write>(cgh); auto d_C3_acc_ct3 = d_C3_buf_ct3.get_access<sycl::access::mode::read_write>(cgh); auto d_C4_acc_ct4 = d_C4_buf_ct4.get_access<sycl::access::mode::read_write>(cgh); auto d_Imin_acc_ct5 = d_Imin_buf_ct5.get_access<sycl::access::mode::read_write>(cgh); auto d_Jmin_acc_ct6 = d_Jmin_buf_ct6.get_access<sycl::access::mode::read_write>(cgh); auto d_Imax_acc_ct7 = d_Imax_buf_ct7.get_access<sycl::access::mode::read_write>(cgh); auto d_Jmax_acc_ct8 = d_Jmax_buf_ct8.get_access<sycl::access::mode::read_write>(cgh); cgh.parallel_for( sycl::nd_range<3>(sycl::range<3>(1, 1, 1), sycl::range<3>(1, 1, 1)), [=](sycl::nd_item<3> item_ct1) { kernel4((float *)(&d_node_acc_ct0[0]), (const float *)(&d_C1_acc_ct1[0]), (const float *)(&d_C2_acc_ct2[0]), (const float *)(&d_C3_acc_ct3[0]), (const float *)(&d_C4_acc_ct4[0]), (int *)(&d_Imin_acc_ct5[0]), (int *)(&d_Jmin_acc_ct6[0]), (int *)(&d_Imax_acc_ct7[0]), (int *)(&d_Jmax_acc_ct8[0]), NLat, NLon, Par.sshClipThreshold); }); }); } dpct::dpct_memcpy(&Imin, d_Imin, sizeof(int), dpct::device_to_host); dpct::dpct_memcpy(&Imax, d_Imax, sizeof(int), dpct::device_to_host); dpct::dpct_memcpy(&Jmin, d_Jmin, sizeof(int), dpct::device_to_host); dpct::dpct_memcpy(&Jmax, d_Jmax, sizeof(int), dpct::device_to_host); clock_gettime(CLOCK_MONOTONIC, &inter); elapsed = diff(start, inter) * 1000; if( Par.outProgress ) { if( lastProgress >= Par.outProgress ) { printf( "Model time = %s, elapsed: %ld msec\n", utlTimeSplitString(Par.time), elapsed ); Log.print( "Model time = %s, elapsed: %ld msec", utlTimeSplitString(Par.time), elapsed ); lastProgress = 0; } } fflush(stdout); if( Par.outPropagation ) { if( lastPropagation >= Par.outPropagation ) { Nrec2DOutput++; fp = fopen( IndexFile, "at" ); fprintf( fp, "%3.3d %s %d %d %d %d\n", Nrec2DOutput, utlTimeSplitString(Par.time), Imin, Imax, Jmin, Jmax ); fclose( fp ); lastPropagation = 0; } } } // main loop dpct::dpct_memcpy(node, d_node, sizeof(float) * NLat * NLon * MAX_VARS_PER_NODE, dpct::device_to_host); dpct::dpct_free(d_node); dpct::dpct_free(d_C1); dpct::dpct_free(d_C2); dpct::dpct_free(d_C3); dpct::dpct_free(d_C4); dpct::dpct_free(d_R6); dpct::dpct_free(d_Imin); dpct::dpct_free(d_Imax); dpct::dpct_free(d_Jmin); dpct::dpct_free(d_Jmax); clock_gettime(CLOCK_MONOTONIC, &end); Log.print("Finishing main loop"); // Final output Log.print("Final dump..."); if (NPOIs != 0) { // Dump POIs if( Par.poiDt ) { // Time series sprintf( buf, "%s.poi.ssh", Par.modelName ); fp = fopen( buf, "wt" ); fprintf( fp, "Minute" ); for( n=0; n<NPOIs; n++ ) fprintf( fp, " %s", idPOI[n] ); fprintf( fp, "\n" ); for( it=0; (timePOI[it] != -1 && it < NtPOI); it++ ) { fprintf( fp, "%6.2f", (double)timePOI[it]/60 ); for( n=0; n<NPOIs; n++ ) fprintf( fp, " %7.3f", sshPOI[n][it] ); fprintf( fp, "\n" ); } fclose( fp ); } // EAT EWH sprintf( buf, "%s.poi.summary", Par.modelName ); fp = fopen( buf, "wt" ); fprintf( fp, "ID ETA EWH\n" ); for( n=0; n<NPOIs; n++ ) { fprintf( fp, "%s", idPOI[n] ); float dbuf = Node(idxPOI[n], iTime)/60; if( dbuf < 0. ) dbuf = -1.; fprintf( fp, " %6.2f", dbuf ); float ampFactor = 1.; if( flagRunupPOI[n] ) ampFactor = pow( Node(idxPOI[n], iD), 0.25 ); fprintf( fp, " %6.3f\n", (ampFactor * Node(idxPOI[n], iHmax)) ); } fclose( fp ); } //ewDump2D(); nOutI = Imax-Imin+1; lonOutMin = getLon(Imin); lonOutMax = getLon(Imax); nOutJ = Jmax-Jmin+1; latOutMin = getLat(Jmin); latOutMax = getLat(Jmax); // write ssh max sprintf( record, "%s.2D.sshmax", Par.modelName ); fp = fopen( record, "wb" ); fwrite( "DSBB", 4, 1, fp ); fwrite( &nOutI, sizeof(short), 1, fp ); fwrite( &nOutJ, sizeof(short), 1, fp ); fwrite( &lonOutMin, sizeof(double), 1, fp ); fwrite( &lonOutMax, sizeof(double), 1, fp ); fwrite( &latOutMin, sizeof(double), 1, fp ); fwrite( &latOutMax, sizeof(double), 1, fp ); dtmp = 0.; fwrite( &dtmp, sizeof(double), 1, fp ); dtmp = 1.; fwrite( &dtmp, sizeof(double), 1, fp ); for( j=Jmin; j<=Jmax; j++ ) { for( i=Imin; i<=Imax; i++ ) { ftmp = (float)Node(idx(j,i), iHmax); fwrite( &ftmp, sizeof(float), 1, fp ); } } fclose( fp ); // write arrival times sprintf( record, "%s.2D.time", Par.modelName ); fp = fopen( record, "wb" ); fwrite( "DSBB", 4, 1, fp ); fwrite( &nOutI, sizeof(short), 1, fp ); fwrite( &nOutJ, sizeof(short), 1, fp ); fwrite( &lonOutMin, sizeof(double), 1, fp ); fwrite( &lonOutMax, sizeof(double), 1, fp ); fwrite( &latOutMin, sizeof(double), 1, fp ); fwrite( &latOutMax, sizeof(double), 1, fp ); dtmp = 0.; fwrite( &dtmp, sizeof(double), 1, fp ); dtmp = 1.; fwrite( &dtmp, sizeof(double), 1, fp ); for( j=Jmin; j<=Jmax; j++ ) { for( i=Imin; i<=Imax; i++ ) { ftmp = (float)Node(idx(j,i), iTime) / 60; // -1/60 //printf("%f\n", ftmp); fwrite( &ftmp, sizeof(float), 1, fp ); } } fclose( fp ); free( node ); free( R6 ); free( C1 ); free( C2 ); free( C3 ); free( C4 ); printf_v("Runtime: %.3lf\n", diff(start, end) * 1000.0); return 0; } //======================================================================== int commandLineHelp( void ) { printf( "Usage: easywave -grid ... -source ... -time ... [optional parameters]\n" ); printf( "-grid ... bathymetry in GoldenSoftware(C) GRD format (text or binary)\n" ); printf( "-source ... input wave either als GRD-file or file with Okada faults\n" ); printf( "-time ... simulation time in [min]\n" ); printf( "Optional parameters:\n" ); printf( "-step ... simulation time step, default- estimated from bathymetry\n" ); printf( "-coriolis use Coriolis force, default- no\n" ); printf( "-poi ... POIs file\n" ); printf( "-label ... model name, default- 'eWave'\n" ); printf( "-progress ... show simulation progress each ... minutes, default- 10\n" ); printf( "-propagation ... write wave propagation grid each ... minutes, default- 5\n" ); printf( "-dump ... make solution dump each ... physical seconds, default- 0\n" ); printf( "-nolog deactivate logging\n" ); printf( "-poi_dt_out ... output time step for mariograms in [sec], default- 30\n" ); printf( "-poi_search_dist ... in [km], default- 10\n" ); printf( "-poi_min_depth ... in [m], default- 1\n" ); printf( "-poi_max_depth ... in [m], default- 10 000\n" ); printf( "-poi_report enable POIs loading report, default- disabled\n" ); printf( "-ssh0_rel ... relative threshold for initial wave, default- 0.01\n" ); printf( "-ssh0_abs ... absolute threshold for initial wave in [m], default- 0\n" ); printf( "-ssh_arrival ... threshold for arrival times in [m], default- 0.001\n" ); printf( " negative value considered as relative threshold\n" ); printf( "-gpu start GPU version of EasyWave (requires a CUDA capable device)\n" ); printf( "-verbose generate verbose output on stdout\n" ); printf( "\nExample:\n" ); printf( "\t easyWave -grid gebcoIndonesia.grd -source fault.inp -time 120\n\n" ); return -1; }
/* * Copyright (C) 2017-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/device/device.h" #include "shared/source/device_binary_format/elf/elf.h" #include "shared/source/device_binary_format/elf/elf_decoder.h" #include "shared/source/device_binary_format/elf/ocl_elf.h" #include "shared/source/helpers/file_io.h" #include "shared/source/helpers/string.h" #include "shared/test/unit_test/device_binary_format/patchtokens_tests.h" #include "shared/test/unit_test/helpers/test_files.h" #include "shared/test/unit_test/mocks/mock_device.h" #include "opencl/test/unit_test/mocks/mock_cl_device.h" #include "opencl/test/unit_test/mocks/mock_program.h" #include "compiler_options.h" #include "gtest/gtest.h" #include <cstring> using namespace NEO; class ProcessElfBinaryTests : public ::testing::Test { public: void SetUp() override { device = std::make_unique<MockClDevice>(MockDevice::createWithNewExecutionEnvironment<MockDevice>(nullptr, rootDeviceIndex)); program = std::make_unique<MockProgram>(*device->getExecutionEnvironment(), nullptr, false, &device->getDevice()); } std::unique_ptr<MockProgram> program; std::unique_ptr<ClDevice> device; const uint32_t rootDeviceIndex = 1; }; TEST_F(ProcessElfBinaryTests, GivenNullWhenCreatingProgramFromBinaryThenInvalidBinaryErrorIsReturned) { cl_int retVal = program->createProgramFromBinary(nullptr, 0, rootDeviceIndex); EXPECT_EQ(CL_INVALID_BINARY, retVal); } TEST_F(ProcessElfBinaryTests, GivenInvalidBinaryWhenCreatingProgramFromBinaryThenInvalidBinaryErrorIsReturned) { char pBinary[] = "thisistotallyinvalid\0"; size_t binarySize = strnlen_s(pBinary, 21); cl_int retVal = program->createProgramFromBinary(pBinary, binarySize, rootDeviceIndex); EXPECT_EQ(CL_INVALID_BINARY, retVal); } TEST_F(ProcessElfBinaryTests, GivenValidBinaryWhenCreatingProgramFromBinaryThenSuccessIsReturned) { std::string filePath; retrieveBinaryKernelFilename(filePath, "CopyBuffer_simd16_", ".bin"); size_t binarySize = 0; auto pBinary = loadDataFromFile(filePath.c_str(), binarySize); cl_int retVal = program->createProgramFromBinary(pBinary.get(), binarySize, rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(0, memcmp(pBinary.get(), program->buildInfos[rootDeviceIndex].packedDeviceBinary.get(), binarySize)); } TEST_F(ProcessElfBinaryTests, GivenValidSpirBinaryWhenCreatingProgramFromBinaryThenSuccessIsReturned) { //clCreateProgramWithIL => SPIR-V stored as source code const uint32_t spirvBinary[2] = {0x03022307, 0x07230203}; size_t spirvBinarySize = sizeof(spirvBinary); //clCompileProgram => SPIR-V stored as IR binary program->isSpirV = true; program->irBinary = makeCopy(spirvBinary, spirvBinarySize); program->irBinarySize = spirvBinarySize; program->programBinaryType = CL_PROGRAM_BINARY_TYPE_LIBRARY; EXPECT_NE(nullptr, program->irBinary); EXPECT_NE(0u, program->irBinarySize); EXPECT_TRUE(program->getIsSpirV()); //clGetProgramInfo => SPIR-V stored as ELF binary cl_int retVal = program->packDeviceBinary(rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, program->buildInfos[rootDeviceIndex].packedDeviceBinary); EXPECT_NE(0u, program->buildInfos[rootDeviceIndex].packedDeviceBinarySize); //use ELF reader to parse and validate ELF binary std::string decodeErrors; std::string decodeWarnings; auto elf = NEO::Elf::decodeElf(ArrayRef<const uint8_t>(reinterpret_cast<const uint8_t *>(program->buildInfos[rootDeviceIndex].packedDeviceBinary.get()), program->buildInfos[rootDeviceIndex].packedDeviceBinarySize), decodeErrors, decodeWarnings); auto header = elf.elfFileHeader; ASSERT_NE(nullptr, header); //check if ELF binary contains section SECTION_HEADER_TYPE_SPIRV bool hasSpirvSection = false; for (const auto &elfSectionHeader : elf.sectionHeaders) { if (elfSectionHeader.header->type == NEO::Elf::SHT_OPENCL_SPIRV) { hasSpirvSection = true; break; } } EXPECT_TRUE(hasSpirvSection); //clCreateProgramWithBinary => new program should recognize SPIR-V binary program->isSpirV = false; auto elfBinary = makeCopy(program->buildInfos[rootDeviceIndex].packedDeviceBinary.get(), program->buildInfos[rootDeviceIndex].packedDeviceBinarySize); retVal = program->createProgramFromBinary(elfBinary.get(), program->buildInfos[rootDeviceIndex].packedDeviceBinarySize, rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_TRUE(program->getIsSpirV()); } unsigned int BinaryTypeValues[] = { CL_PROGRAM_BINARY_TYPE_EXECUTABLE, CL_PROGRAM_BINARY_TYPE_LIBRARY, CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT}; class ProcessElfBinaryTestsWithBinaryType : public ::testing::TestWithParam<unsigned int> { public: void SetUp() override { device = std::make_unique<MockClDevice>(MockDevice::createWithNewExecutionEnvironment<MockDevice>(nullptr, rootDeviceIndex)); program = std::make_unique<MockProgram>(*device->getExecutionEnvironment(), nullptr, false, &device->getDevice()); } std::unique_ptr<MockProgram> program; std::unique_ptr<ClDevice> device; const uint32_t rootDeviceIndex = 1; }; TEST_P(ProcessElfBinaryTestsWithBinaryType, GivenBinaryTypeWhenResolveProgramThenProgramIsProperlyResolved) { std::string filePath; retrieveBinaryKernelFilename(filePath, "CopyBuffer_simd16_", ".bin"); size_t binarySize = 0; auto pBinary = loadDataFromFile(filePath.c_str(), binarySize); cl_int retVal = program->createProgramFromBinary(pBinary.get(), binarySize, rootDeviceIndex); auto options = program->options; auto genBinary = makeCopy(program->buildInfos[rootDeviceIndex].unpackedDeviceBinary.get(), program->buildInfos[rootDeviceIndex].unpackedDeviceBinarySize); auto genBinarySize = program->buildInfos[rootDeviceIndex].unpackedDeviceBinarySize; auto irBinary = makeCopy(program->irBinary.get(), program->irBinarySize); auto irBinarySize = program->irBinarySize; EXPECT_EQ(CL_SUCCESS, retVal); ASSERT_EQ(binarySize, program->buildInfos[rootDeviceIndex].packedDeviceBinarySize); EXPECT_EQ(0, memcmp(pBinary.get(), program->buildInfos[rootDeviceIndex].packedDeviceBinary.get(), binarySize)); // delete program's elf reference to force a resolve program->buildInfos[rootDeviceIndex].packedDeviceBinary.reset(); program->buildInfos[rootDeviceIndex].packedDeviceBinarySize = 0U; program->programBinaryType = GetParam(); retVal = program->packDeviceBinary(rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); ASSERT_NE(nullptr, program->buildInfos[rootDeviceIndex].packedDeviceBinary); std::string decodeErrors; std::string decodeWarnings; auto elf = NEO::Elf::decodeElf(ArrayRef<const uint8_t>(reinterpret_cast<const uint8_t *>(program->buildInfos[rootDeviceIndex].packedDeviceBinary.get()), program->buildInfos[rootDeviceIndex].packedDeviceBinarySize), decodeErrors, decodeWarnings); ASSERT_NE(nullptr, elf.elfFileHeader); ArrayRef<const uint8_t> decodedIr; ArrayRef<const uint8_t> decodedDeviceBinary; ArrayRef<const uint8_t> decodedOptions; for (auto &section : elf.sectionHeaders) { switch (section.header->type) { default: break; case NEO::Elf::SHT_OPENCL_LLVM_BINARY: decodedIr = section.data; break; case NEO::Elf::SHT_OPENCL_SPIRV: decodedIr = section.data; break; case NEO::Elf::SHT_OPENCL_DEV_BINARY: decodedDeviceBinary = section.data; break; case NEO::Elf::SHT_OPENCL_OPTIONS: decodedDeviceBinary = section.data; break; } } ASSERT_EQ(options.size(), decodedOptions.size()); ASSERT_EQ(genBinarySize, decodedDeviceBinary.size()); ASSERT_EQ(irBinarySize, decodedIr.size()); EXPECT_EQ(0, memcmp(genBinary.get(), decodedDeviceBinary.begin(), genBinarySize)); EXPECT_EQ(0, memcmp(irBinary.get(), decodedIr.begin(), irBinarySize)); } INSTANTIATE_TEST_CASE_P(ResolveBinaryTests, ProcessElfBinaryTestsWithBinaryType, ::testing::ValuesIn(BinaryTypeValues)); TEST_F(ProcessElfBinaryTests, GivenMultipleCallsWhenCreatingProgramFromBinaryThenEachProgramIsCorrect) { std::string filePath; retrieveBinaryKernelFilename(filePath, "CopyBuffer_simd16_", ".bin"); size_t binarySize = 0; auto pBinary = loadDataFromFile(filePath.c_str(), binarySize); cl_int retVal = program->createProgramFromBinary(pBinary.get(), binarySize, rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(0, memcmp(pBinary.get(), program->buildInfos[rootDeviceIndex].packedDeviceBinary.get(), binarySize)); std::string filePath2; retrieveBinaryKernelFilename(filePath2, "simple_arg_int_", ".bin"); pBinary = loadDataFromFile(filePath2.c_str(), binarySize); retVal = program->createProgramFromBinary(pBinary.get(), binarySize, rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(0, memcmp(pBinary.get(), program->buildInfos[rootDeviceIndex].packedDeviceBinary.get(), binarySize)); } TEST_F(ProcessElfBinaryTests, GivenEmptyBuildOptionsWhenCreatingProgramFromBinaryThenSuccessIsReturned) { std::string filePath; retrieveBinaryKernelFilename(filePath, "simple_kernels_", ".bin"); size_t binarySize = 0; auto pBinary = loadDataFromFile(filePath.c_str(), binarySize); cl_int retVal = program->createProgramFromBinary(pBinary.get(), binarySize, rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); const auto &options = program->getOptions(); size_t optionsSize = strlen(options.c_str()) + 1; EXPECT_EQ(0, memcmp("", options.c_str(), optionsSize)); } TEST_F(ProcessElfBinaryTests, GivenNonEmptyBuildOptionsWhenCreatingProgramFromBinaryThenSuccessIsReturned) { std::string filePath; retrieveBinaryKernelFilename(filePath, "simple_kernels_opts_", ".bin"); size_t binarySize = 0; auto pBinary = loadDataFromFile(filePath.c_str(), binarySize); cl_int retVal = program->createProgramFromBinary(pBinary.get(), binarySize, rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); const auto &options = program->getOptions(); std::string buildOptionsNotEmpty = CompilerOptions::concatenate(CompilerOptions::optDisable, "-DDEF_WAS_SPECIFIED=1"); EXPECT_STREQ(buildOptionsNotEmpty.c_str(), options.c_str()); } TEST_F(ProcessElfBinaryTests, GivenBinaryWhenIncompatiblePatchtokenVerionThenProramCreationFails) { PatchTokensTestData::ValidEmptyProgram programTokens; { NEO::Elf::ElfEncoder<> elfEncoder; elfEncoder.getElfFileHeader().type = NEO::Elf::ET_OPENCL_EXECUTABLE; elfEncoder.appendSection(NEO::Elf::SHT_OPENCL_DEV_BINARY, NEO::Elf::SectionNamesOpenCl::deviceBinary, programTokens.storage); auto elfBinary = elfEncoder.encode(); cl_int retVal = program->createProgramFromBinary(elfBinary.data(), elfBinary.size(), rootDeviceIndex); EXPECT_EQ(CL_SUCCESS, retVal); } { programTokens.headerMutable->Version -= 1; NEO::Elf::ElfEncoder<> elfEncoder; elfEncoder.getElfFileHeader().type = NEO::Elf::ET_OPENCL_EXECUTABLE; elfEncoder.appendSection(NEO::Elf::SHT_OPENCL_DEV_BINARY, NEO::Elf::SectionNamesOpenCl::deviceBinary, programTokens.storage); auto elfBinary = elfEncoder.encode(); cl_int retVal = program->createProgramFromBinary(elfBinary.data(), elfBinary.size(), rootDeviceIndex); EXPECT_EQ(CL_INVALID_BINARY, retVal); } }
/// @file /// @brief QV/C++ port to ARM Cortex-M, ARM-CLANG toolset /// @cond ///*************************************************************************** /// Last updated for version 6.9.1 /// Last updated on 2020-09-23 /// /// Q u a n t u m L e a P s /// ------------------------ /// Modern Embedded Software /// /// Copyright (C) 2005-2020 Quantum Leaps. All rights reserved. /// /// This program is open source software: you can redistribute it and/or /// modify it under the terms of the GNU General Public License as published /// by the Free Software Foundation, either version 3 of the License, or /// (at your option) any later version. /// /// Alternatively, this program may be distributed and modified under the /// terms of Quantum Leaps commercial licenses, which expressly supersede /// the GNU General Public License and are specifically designed for /// licensees interested in retaining the proprietary status of their code. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program. If not, see <www.gnu.org/licenses>. /// /// Contact information: /// <www.state-machine.com/licensing> /// <info@state-machine.com> ///*************************************************************************** /// @endcond #ifndef QV_PORT_HPP #define QV_PORT_HPP #if (__ARM_ARCH == 6) // Cortex-M0/M0+/M1 (v6-M, v6S-M)? // macro to put the CPU to sleep inside QV::onIdle() #define QV_CPU_SLEEP() do { \ __asm volatile ("wfi"); \ QF_INT_ENABLE(); \ } while (false) #define QV_ARM_ERRATUM_838869() ((void)0) #else // Cortex-M3/M4/M7(v7-M) // macro to put the CPU to sleep inside QV::onIdle() #define QV_CPU_SLEEP() do { \ QF_PRIMASK_DISABLE(); \ QF_INT_ENABLE(); \ __asm volatile ("wfi"); \ QF_PRIMASK_ENABLE(); \ } while (false) // initialization of the QV kernel for Cortex-M3/M4/M4F #define QV_INIT() QV_init() extern "C" void QV_init(void); // The following macro implements the recommended workaround for the // ARM Erratum 838869. Specifically, for Cortex-M3/M4/M7 the DSB // (memory barrier) instruction needs to be added before exiting an ISR. // This macro should be inserted at the end of ISRs. // #define QV_ARM_ERRATUM_838869() \ __asm volatile ("dsb 0xf" ::: "memory") #endif #include "qv.hpp" // QV platform-independent public interface #endif // QV_PORT_HPP
/*! \file csv.hpp \brief Text input and output archives */ /* Copyright (c) 2014, Randolph Voorhies, Shane Grant 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 of conditions 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 materials provided with the distribution. * Neither the name of cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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. */ #ifndef CEREAL_ARCHIVES_CSV_HPP_ #define CEREAL_ARCHIVES_CSV_HPP_ #include "cereal/cereal.hpp" #include <charconv> #include <sstream> #include <type_traits> namespace cereal { // ###################################################################### //! An output archive designed to save data in a csv representation /*! This archive outputs data to a stream in a csv, space seperated, representation with as little extra metadata as possible. When using a csv archive and a file stream, you must use the std::ios::out format flag to avoid having your data altered inadvertently. \ingroup Archives */ class CSVOutputArchive : public OutputArchive<CSVOutputArchive, AllowEmptyClassElision> { public: //! Construct, outputting to the provided stream /*! @param stream The stream to output to. Can be a stringstream, a file stream, or even cout! */ CSVOutputArchive(std::ostream & stream) : OutputArchive<CSVOutputArchive, AllowEmptyClassElision>(this), itsStream(stream) { } ~CSVOutputArchive() CEREAL_NOEXCEPT = default; //! Writes size bytes of data to the output stream template<class T> void saveCsv( T const & t ) { if constexpr ( std::is_arithmetic<T>::value ) { char begin [ 64 ] { 0 }; std::size_t size = 0; if constexpr ( std::is_integral<T>::value ) { auto [ end, ec ] = std::to_chars ( begin, begin + 64, t, 10 ); *end++ = ' '; size = static_cast<std::size_t> ( end - begin ); } else if constexpr ( std::is_floating_point<T>::value ) { auto [ end, ec ] = std::to_chars ( begin, begin + 64, t, std::chars_format::fixed ); *end++ = ' '; size = static_cast<std::size_t> ( end - begin ); } const std::size_t writtenSize = static_cast< std::size_t >( itsStream.rdbuf ( )->sputn ( reinterpret_cast<const char*> ( begin ), size ) ); if ( writtenSize != size ) throw Exception ( "Failed to write " + std::to_string ( size ) + " bytes to output stream! Wrote " + std::to_string ( writtenSize ) ); } else if constexpr ( std::is_same<T, std::string>::value ) { itsStream << t << ' '; } } private: std::ostream & itsStream; }; // ###################################################################### //! An input archive designed to load data saved using CSVOutputArchive /* This archive does nothing to ensure that the endianness of the saved and loaded data is the same. If you need to have portability over architectures with different endianness, use PortableCsvOutputArchive. When using a csv archive and a file stream, you must use the std::ios::in format flag to avoid having your data altered inadvertently. \ingroup Archives */ class CSVInputArchive : public InputArchive<CSVInputArchive, AllowEmptyClassElision> { public: //! Construct, loading from the provided stream CSVInputArchive(std::istream & stream) : InputArchive<CSVInputArchive, AllowEmptyClassElision>(this), itsStream(stream) { } ~CSVInputArchive() CEREAL_NOEXCEPT = default; //! Reads size bytes of data from the input stream template<class T> void loadCsv( T & t ) { char begin [ 64 ] { 0 }; char * end = begin; while ( true ) { *end = static_cast<char> ( itsStream.rdbuf ( )->sbumpc ( ) ); if ( -1 == *end ) { break; } if ( ' ' == *end ) { break; } ++end; } if constexpr ( std::is_integral<T>::value ) { std::from_chars ( begin, end, t, 10 ); } else if constexpr ( std::is_floating_point<T>::value ) { std::from_chars ( begin, end, t, std::chars_format::fixed ); } else if constexpr ( std::is_same<T, std::string>::value ) { t = std::string { begin, end }; } } private: std::istream & itsStream; }; // ###################################################################### // Common CsvArchive serialization functions //! Saving for POD types to csv template<class T> inline typename std::enable_if<std::disjunction<std::is_arithmetic<T>, std::is_same<T, std::string>>::value, void>::type CEREAL_SAVE_FUNCTION_NAME(CSVOutputArchive & ar, T const & t) { ar.saveCsv(t); } //! Loading for POD types from csv template<class T> inline typename std::enable_if<std::disjunction<std::is_arithmetic<T>, std::is_same<T, std::string>>::value, void>::type CEREAL_LOAD_FUNCTION_NAME(CSVInputArchive & ar, T & t) { ar.loadCsv(t); } //! Serializing NVP types to csv template <class Archive, class T> inline CEREAL_ARCHIVE_RESTRICT(CSVInputArchive, CSVOutputArchive) CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, NameValuePair<T> & t ) { ar( t.value ); } //! Serializing SizeTags to csv template <class Archive, class T> inline CEREAL_ARCHIVE_RESTRICT(CSVInputArchive, CSVOutputArchive) CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, SizeTag<T> & t ) { ar( t.size ); } /* template <class T> struct BinaryData { //! Internally store the pointer as a void *, keeping const if created with //! a const pointer using PT = typename std::conditional<std::is_const<typename std::remove_pointer<T>::type>::value, const void *, void *>::type; BinaryData( T && d, uint64_t s ) : data(std::forward<T>(d)), size(s) {} PT data; //!< pointer to beginning of data uint64_t size; //!< size in bytes }; */ /* //! Saving binary data template <class T> inline void CEREAL_SAVE_FUNCTION_NAME(CSVOutputArchive & ar, CsvData<T> const & bd) { ar.saveCsv( bd.data, static_cast<std::size_t>( bd.size ) ); } //! Loading binary data template <class T> inline void CEREAL_LOAD_FUNCTION_NAME(CSVInputArchive & ar, CsvData<T> & bd) { ar.loadCsv(bd.data, static_cast<std::size_t>(bd.size)); } */ } // namespace cereal // register archives for polymorphic support CEREAL_REGISTER_ARCHIVE(cereal::CSVOutputArchive) CEREAL_REGISTER_ARCHIVE(cereal::CSVInputArchive) // tie input and output archives together CEREAL_SETUP_ARCHIVE_TRAITS(cereal::CSVInputArchive, cereal::CSVOutputArchive) #endif // CEREAL_ARCHIVES_CSV_HPP_
/* * MIT License * * Copyright (c) 2020-2021 Jannis Weis * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "com_github_weisj_darklaf_platform_windows_JNIThemeInfoWindows.h" #include "Registry.h" #include <string> #include <thread> #include <atomic> #include <windows.h> #include <winuser.h> constexpr auto DARK_MODE_PATH = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; constexpr auto DARK_MODE_KEY = "AppsUseLightTheme"; constexpr auto FONT_SCALE_PATH = "Software\\Microsoft\\Accessibility"; constexpr auto FONT_SCALE_KEY = "TextScaleFactor"; constexpr auto HIGH_CONTRAST_PATH = "Control Panel\\Accessibility\\HighContrast"; constexpr auto HIGH_CONTRAST_THEME_KEY = "High Contrast Scheme"; constexpr auto HIGH_CONTRAST_LIGHT_THEME = "High Contrast White"; constexpr auto ACCENT_COLOR_PATH = "SOFTWARE\\Microsoft\\Windows\\DWM"; constexpr auto ACCENT_COLOR_KEY = "ColorizationColor"; constexpr auto DARK_MODE_DEFAULT_VALUE = false; constexpr auto HIGH_CONTRAST_DEFAULT_VALUE = false; constexpr auto FONT_SCALE_DEFAULT_VALUE = 100; constexpr auto ACCENT_COLOR_DEFAULT_VALUE = 0; static bool IsHighContrastMode() { HIGHCONTRAST info = { 0, 0, 0 }; info.cbSize = sizeof(HIGHCONTRAST); BOOL ok = SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &info, 0); if (ok) { return info.dwFlags & HCF_HIGHCONTRASTON; } return HIGH_CONTRAST_DEFAULT_VALUE; } static bool IsDarkMode() { try { bool appsUseDark = (0 == RegGetDword(HKEY_CURRENT_USER, DARK_MODE_PATH, DARK_MODE_KEY)); bool isHighContrast = IsHighContrastMode(); if (!isHighContrast) return appsUseDark; std::string themeValue = RegGetString(HKEY_CURRENT_USER, HIGH_CONTRAST_PATH, HIGH_CONTRAST_THEME_KEY); return (strcmp(themeValue.c_str(), HIGH_CONTRAST_LIGHT_THEME) != 0); } catch (LONG) { return DARK_MODE_DEFAULT_VALUE; } } static unsigned int GetTextScaleFactor() { try { return RegGetDword(HKEY_CURRENT_USER, FONT_SCALE_PATH, FONT_SCALE_KEY); } catch (LONG) { return FONT_SCALE_DEFAULT_VALUE; } } static bool RegisterRegistryEvent(const LPCSTR subKey, HANDLE event) { HKEY hKey; REGSAM flags = KEY_NOTIFY; ModifyFlags(flags); DWORD res = RegOpenKeyExA(HKEY_CURRENT_USER, subKey, 0, flags, &hKey); if (res == ERROR_SUCCESS) { LSTATUS status = RegNotifyChangeKeyValue(hKey, FALSE, REG_NOTIFY_CHANGE_LAST_SET, event, TRUE); return status == ERROR_SUCCESS; } else { return FALSE; } } static int GetAccentColor() { try { return RegGetDword(HKEY_CURRENT_USER, ACCENT_COLOR_PATH, ACCENT_COLOR_KEY); } catch (LONG) { return ACCENT_COLOR_DEFAULT_VALUE; } } JNIEXPORT jboolean JNICALL Java_com_github_weisj_darklaf_platform_windows_JNIThemeInfoWindows_isDarkThemeEnabled(JNIEnv*, jclass) { return static_cast<jboolean>(IsDarkMode()); } JNIEXPORT jboolean JNICALL Java_com_github_weisj_darklaf_platform_windows_JNIThemeInfoWindows_isHighContrastEnabled(JNIEnv*, jclass) { return static_cast<jboolean>(IsHighContrastMode()); } JNIEXPORT jlong JNICALL Java_com_github_weisj_darklaf_platform_windows_JNIThemeInfoWindows_getFontScaleFactor(JNIEnv*, jclass) { return static_cast<jlong>(GetTextScaleFactor()); } JNIEXPORT jint JNICALL Java_com_github_weisj_darklaf_platform_windows_JNIThemeInfoWindows_getAccentColor(JNIEnv*, jclass) { return static_cast<jint>(GetAccentColor()); } struct EventHandler { JavaVM *jvm; JNIEnv *env; jobject callback; HANDLE eventHandle; std::thread notificationLoop; std::atomic<bool> running = FALSE; void runCallBack() { jclass runnableClass = env->GetObjectClass(callback); jmethodID runMethodId = env->GetMethodID(runnableClass, "run", "()V"); if (runMethodId) { env->CallVoidMethod(callback, runMethodId); } } bool awaitPreferenceChange() { if (!RegisterRegistryEvent(FONT_SCALE_PATH, eventHandle)) return FALSE; if (!RegisterRegistryEvent(DARK_MODE_PATH, eventHandle)) return FALSE; if (!RegisterRegistryEvent(HIGH_CONTRAST_PATH, eventHandle)) return FALSE; if (!RegisterRegistryEvent(ACCENT_COLOR_PATH, eventHandle)) return FALSE; return WaitForSingleObject(eventHandle, INFINITE) != WAIT_FAILED; } void run() { int getEnvStat = jvm->GetEnv((void**) &env, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { if (jvm->AttachCurrentThread((void**) &env, NULL) != 0) return; } else if (getEnvStat == JNI_EVERSION) { return; } while (running && awaitPreferenceChange()) { if (running) { runCallBack(); if (env->ExceptionCheck()) { env->ExceptionDescribe(); break; } } } jvm->DetachCurrentThread(); } void stop() { running = FALSE; SetEvent(eventHandle); notificationLoop.join(); } EventHandler(JavaVM *jvm_, jobject callback_, HANDLE eventHandle_) { jvm = jvm_; callback = callback_; eventHandle = eventHandle_; running = TRUE; notificationLoop = std::thread(&EventHandler::run, this); } }; JNIEXPORT jlong JNICALL Java_com_github_weisj_darklaf_platform_windows_JNIThemeInfoWindows_createEventHandler(JNIEnv *env, jclass, jobject callback) { JavaVM *jvm; if (env->GetJavaVM(&jvm) == JNI_OK) { jobject callbackRef = env->NewGlobalRef(callback); HANDLE event = CreateEvent(NULL, FALSE, FALSE, NULL); EventHandler* eventHandler = new EventHandler(jvm, callbackRef, event); return reinterpret_cast<jlong>(eventHandler); } return static_cast<jlong>(0); } JNIEXPORT void JNICALL Java_com_github_weisj_darklaf_platform_windows_JNIThemeInfoWindows_deleteEventHandler(JNIEnv *env, jclass, jlong eventHandler) { EventHandler *handler = reinterpret_cast<EventHandler *>(eventHandler); if (handler) { env->DeleteGlobalRef(handler->callback); handler->stop(); delete handler; } }
/**************************************************************************************** * @author: kzvd4729 created: Jul/07/2019 16:03 * solution_verdict: Accepted language: GNU C++14 * run_time: 2994 ms memory_used: 78500 KB * problem: https://codeforces.com/contest/1184/problem/E2 ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e5; int par[N+2],n,pcst[N+2]; vector<pair<int,pair<int,int> > >v; pair<int,pair<int,int> >p; int _find(int x) { if(x==par[x])return x; return par[x]=_find(par[x]); } /**************** LCA ********************/ int Par[N+2],Lev[N+2],Sp[N+2][22],sp[N+2][22]; vector<int>Adj[N+2],cst[N+2]; void Reckon(int n,int p,int h,int cs) { Par[n]=p;Lev[n]=h;pcst[n]=cs; for(int i=0;i<Adj[n].size();i++) { int x=Adj[n][i]; if(x!=p)Reckon(x,n,h+1,cst[n][i]); } } void Build_Sparse(void) { memset(Sp,-1,sizeof(Sp)); for(int i=1;i<=n;i++) { Sp[i][0]=Par[i]; sp[i][0]=pcst[i]; } for(int j=1;j<=20;j++) { for(int i=1;i<=n;i++) { sp[i][j]=sp[i][j-1]; if(Sp[i][j-1]==-1)continue; Sp[i][j]=Sp[Sp[i][j-1]][j-1]; sp[i][j]=max(sp[i][j],sp[Sp[i][j-1]][j-1]); } } } int Lca(int u,int v) { if(Lev[u]<Lev[v])swap(u,v);int d=0,mx=0; for(int i=20;i>=0;i--) { if(Lev[u]-(1<<i)>=Lev[v]) { mx=max(mx,sp[u][i]); u=Sp[u][i]; } } if(u==v)return mx; for(int i=20;i>=0;i--) { if(Sp[u][i]==-1||Sp[v][i]==-1)continue; if(Sp[u][i]==Sp[v][i])continue; mx=max(mx,sp[u][i]);mx=max(mx,sp[v][i]); u=Sp[u][i];v=Sp[v][i]; } mx=max(mx,pcst[u]); mx=max(mx,pcst[v]); return mx; } ////////////////////////////////////////// int main() { ios_base::sync_with_stdio(0);cin.tie(0); int m;cin>>n>>m;vector<pair<int,int> >edge; for(int i=1;i<=m;i++) { int a,b,c;cin>>a>>b>>c; v.push_back({c,{a,b}}); edge.push_back({a,b}); } sort(v.begin(),v.end()); for(int i=1;i<=n;i++)par[i]=i; set<pair<int,int> >st; for(auto x:v) { int r1=_find(x.second.first); int r2=_find(x.second.second); if(r1==r2){st.insert(x.second);continue;} par[r1]=r2; Adj[x.second.first].push_back(x.second.second); cst[x.second.first].push_back(x.first); Adj[x.second.second].push_back(x.second.first); cst[x.second.second].push_back(x.first); } Reckon(1,-1,0,0);Build_Sparse(); for(auto x:edge) { if(st.find(x)==st.end())continue; cout<<Lca(x.first,x.second)<<"\n"; } return 0; }
#include <iostream> #include <fstream> #include <cstdlib> #include <cstring> using namespace std; const int MAX_SIZE = 80; bool word_check(char* riga); bool at_check(char* riga); int main(int argc, char** argv) { if (argc != 3) { cerr << "Invalid number of parameters. Terminating..." << endl; exit(EXIT_FAILURE); } fstream myin, myout; char riga[MAX_SIZE+1]; myin.open(argv[1], ios::in); while(!myin.eof()) { myin >> riga; if (word_check(riga)) { myout << riga << endl; } } } bool word_check(char* riga) { bool res; if ( strlen(riga) > 1 && riga[0] != '.' && riga[strlen(riga)-1] != '.' && at_check(riga)) { for (int i = 0; (i < strlen(riga)) && res != false; i++) { if ((riga[i] >= 'a' && riga[i] <= 'z') && (riga[i] >= 'A' && riga[i] <= 'Z') && (riga[i] >= '0' && riga[i] <= '9') && (riga[i] == '.') && (riga[i] == '_')) res = true; else res = false; } } return res; } bool at_check(char* riga) { bool res; char tmp; for (int i = 0; (riga[i] != '@') && (riga[i] != '\0'); i++) tmp = riga[i]; if (tmp == '@') res = true; else res = false; return res; }
/* * Copyright 2016 WebAssembly Community Group participants * * 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 "src/ir.h" #include <cassert> #include <cstddef> #include <numeric> #include "src/cast.h" namespace { const char* ExprTypeName[] = { "AtomicFence", "AtomicLoad", "AtomicRmw", "AtomicRmwCmpxchg", "AtomicStore", "AtomicNotify", "AtomicWait", "Binary", "Block", "Br", "BrIf", "BrTable", "Call", "CallIndirect", "Compare", "Const", "Convert", "Drop", "GlobalGet", "GlobalSet", "If", "Load", "LocalGet", "LocalSet", "LocalTee", "Loop", "MemoryCopy", "DataDrop", "MemoryFill", "MemoryGrow", "MemoryInit", "MemorySize", "Nop", "RefIsNull", "RefFunc", "RefNull", "Rethrow", "Return", "ReturnCall", "ReturnCallIndirect", "Select", "SimdLaneOp", "SimdLoadLane", "SimdStoreLane", "SimdShuffleOp", "LoadSplat", "LoadZero", "Store", "TableCopy", "ElemDrop", "TableInit", "TableGet", "TableGrow", "TableSize", "TableSet", "TableFill", "Ternary", "Throw", "Try", "Unary", "Unreachable", }; } // end of anonymous namespace namespace wabt { const char* GetExprTypeName(ExprType type) { static_assert(WABT_ENUM_COUNT(ExprType) == WABT_ARRAY_SIZE(ExprTypeName), "Malformed ExprTypeName array"); return ExprTypeName[size_t(type)]; } const char* GetExprTypeName(const Expr& expr) { return GetExprTypeName(expr.type()); } bool FuncSignature::operator==(const FuncSignature& rhs) const { return param_types == rhs.param_types && result_types == rhs.result_types; } const Export* Module::GetExport(string_view name) const { Index index = export_bindings.FindIndex(name); if (index >= exports.size()) { return nullptr; } return exports[index]; } Index Module::GetFuncIndex(const Var& var) const { return func_bindings.FindIndex(var); } Index Module::GetGlobalIndex(const Var& var) const { return global_bindings.FindIndex(var); } Index Module::GetTableIndex(const Var& var) const { return table_bindings.FindIndex(var); } Index Module::GetMemoryIndex(const Var& var) const { return memory_bindings.FindIndex(var); } Index Module::GetFuncTypeIndex(const Var& var) const { return type_bindings.FindIndex(var); } Index Module::GetEventIndex(const Var& var) const { return event_bindings.FindIndex(var); } Index Module::GetDataSegmentIndex(const Var& var) const { return data_segment_bindings.FindIndex(var); } Index Module::GetElemSegmentIndex(const Var& var) const { return elem_segment_bindings.FindIndex(var); } bool Module::IsImport(ExternalKind kind, const Var& var) const { switch (kind) { case ExternalKind::Func: return GetFuncIndex(var) < num_func_imports; case ExternalKind::Global: return GetGlobalIndex(var) < num_global_imports; case ExternalKind::Memory: return GetMemoryIndex(var) < num_memory_imports; case ExternalKind::Table: return GetTableIndex(var) < num_table_imports; case ExternalKind::Event: return GetEventIndex(var) < num_event_imports; default: return false; } } void LocalTypes::Set(const TypeVector& types) { decls_.clear(); if (types.empty()) { return; } Type type = types[0]; Index count = 1; for (Index i = 1; i < types.size(); ++i) { if (types[i] != type) { decls_.emplace_back(type, count); type = types[i]; count = 1; } else { ++count; } } decls_.emplace_back(type, count); } Index LocalTypes::size() const { return std::accumulate( decls_.begin(), decls_.end(), 0, [](Index sum, const Decl& decl) { return sum + decl.second; }); } Type LocalTypes::operator[](Index i) const { Index count = 0; for (auto decl: decls_) { if (i < count + decl.second) { return decl.first; } count += decl.second; } assert(i < count); return Type::Any; } Type Func::GetLocalType(Index index) const { Index num_params = decl.GetNumParams(); if (index < num_params) { return GetParamType(index); } else { index -= num_params; assert(index < local_types.size()); return local_types[index]; } } Type Func::GetLocalType(const Var& var) const { return GetLocalType(GetLocalIndex(var)); } Index Func::GetLocalIndex(const Var& var) const { if (var.is_index()) { return var.index(); } return bindings.FindIndex(var); } const Func* Module::GetFunc(const Var& var) const { return const_cast<Module*>(this)->GetFunc(var); } Func* Module::GetFunc(const Var& var) { Index index = func_bindings.FindIndex(var); if (index >= funcs.size()) { return nullptr; } return funcs[index]; } const Global* Module::GetGlobal(const Var& var) const { return const_cast<Module*>(this)->GetGlobal(var); } Global* Module::GetGlobal(const Var& var) { Index index = global_bindings.FindIndex(var); if (index >= globals.size()) { return nullptr; } return globals[index]; } const Table* Module::GetTable(const Var& var) const { return const_cast<Module*>(this)->GetTable(var); } Table* Module::GetTable(const Var& var) { Index index = table_bindings.FindIndex(var); if (index >= tables.size()) { return nullptr; } return tables[index]; } const Memory* Module::GetMemory(const Var& var) const { return const_cast<Module*>(this)->GetMemory(var); } Memory* Module::GetMemory(const Var& var) { Index index = memory_bindings.FindIndex(var); if (index >= memories.size()) { return nullptr; } return memories[index]; } Event* Module::GetEvent(const Var& var) const { Index index = GetEventIndex(var); if (index >= events.size()) { return nullptr; } return events[index]; } const DataSegment* Module::GetDataSegment(const Var& var) const { return const_cast<Module*>(this)->GetDataSegment(var); } DataSegment* Module::GetDataSegment(const Var& var) { Index index = data_segment_bindings.FindIndex(var); if (index >= data_segments.size()) { return nullptr; } return data_segments[index]; } const ElemSegment* Module::GetElemSegment(const Var& var) const { return const_cast<Module*>(this)->GetElemSegment(var); } ElemSegment* Module::GetElemSegment(const Var& var) { Index index = elem_segment_bindings.FindIndex(var); if (index >= elem_segments.size()) { return nullptr; } return elem_segments[index]; } const FuncType* Module::GetFuncType(const Var& var) const { return const_cast<Module*>(this)->GetFuncType(var); } FuncType* Module::GetFuncType(const Var& var) { Index index = type_bindings.FindIndex(var); if (index >= types.size()) { return nullptr; } return dyn_cast<FuncType>(types[index]); } Index Module::GetFuncTypeIndex(const FuncSignature& sig) const { for (size_t i = 0; i < types.size(); ++i) { if (auto* func_type = dyn_cast<FuncType>(types[i])) { if (func_type->sig == sig) { return i; } } } return kInvalidIndex; } Index Module::GetFuncTypeIndex(const FuncDeclaration& decl) const { if (decl.has_func_type) { return GetFuncTypeIndex(decl.type_var); } else { return GetFuncTypeIndex(decl.sig); } } void Module::AppendField(std::unique_ptr<DataSegmentModuleField> field) { DataSegment& data_segment = field->data_segment; if (!data_segment.name.empty()) { data_segment_bindings.emplace(data_segment.name, Binding(field->loc, data_segments.size())); } data_segments.push_back(&data_segment); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<ElemSegmentModuleField> field) { ElemSegment& elem_segment = field->elem_segment; if (!elem_segment.name.empty()) { elem_segment_bindings.emplace(elem_segment.name, Binding(field->loc, elem_segments.size())); } elem_segments.push_back(&elem_segment); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<EventModuleField> field) { Event& event = field->event; if (!event.name.empty()) { event_bindings.emplace(event.name, Binding(field->loc, events.size())); } events.push_back(&event); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<ExportModuleField> field) { // Exported names are allowed to be empty. Export& export_ = field->export_; export_bindings.emplace(export_.name, Binding(field->loc, exports.size())); exports.push_back(&export_); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<FuncModuleField> field) { Func& func = field->func; if (!func.name.empty()) { func_bindings.emplace(func.name, Binding(field->loc, funcs.size())); } funcs.push_back(&func); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<TypeModuleField> field) { TypeEntry& type = *field->type; if (!type.name.empty()) { type_bindings.emplace(type.name, Binding(field->loc, types.size())); } types.push_back(&type); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<GlobalModuleField> field) { Global& global = field->global; if (!global.name.empty()) { global_bindings.emplace(global.name, Binding(field->loc, globals.size())); } globals.push_back(&global); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<ImportModuleField> field) { Import* import = field->import.get(); const std::string* name = nullptr; BindingHash* bindings = nullptr; Index index = kInvalidIndex; switch (import->kind()) { case ExternalKind::Func: { Func& func = cast<FuncImport>(import)->func; name = &func.name; bindings = &func_bindings; index = funcs.size(); funcs.push_back(&func); ++num_func_imports; break; } case ExternalKind::Table: { Table& table = cast<TableImport>(import)->table; name = &table.name; bindings = &table_bindings; index = tables.size(); tables.push_back(&table); ++num_table_imports; break; } case ExternalKind::Memory: { Memory& memory = cast<MemoryImport>(import)->memory; name = &memory.name; bindings = &memory_bindings; index = memories.size(); memories.push_back(&memory); ++num_memory_imports; break; } case ExternalKind::Global: { Global& global = cast<GlobalImport>(import)->global; name = &global.name; bindings = &global_bindings; index = globals.size(); globals.push_back(&global); ++num_global_imports; break; } case ExternalKind::Event: { Event& event = cast<EventImport>(import)->event; name = &event.name; bindings = &event_bindings; index = events.size(); events.push_back(&event); ++num_event_imports; break; } } assert(name && bindings && index != kInvalidIndex); if (!name->empty()) { bindings->emplace(*name, Binding(field->loc, index)); } imports.push_back(import); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<MemoryModuleField> field) { Memory& memory = field->memory; if (!memory.name.empty()) { memory_bindings.emplace(memory.name, Binding(field->loc, memories.size())); } memories.push_back(&memory); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<StartModuleField> field) { starts.push_back(&field->start); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<TableModuleField> field) { Table& table = field->table; if (!table.name.empty()) { table_bindings.emplace(table.name, Binding(field->loc, tables.size())); } tables.push_back(&table); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<ModuleField> field) { switch (field->type()) { case ModuleFieldType::Func: AppendField(cast<FuncModuleField>(std::move(field))); break; case ModuleFieldType::Global: AppendField(cast<GlobalModuleField>(std::move(field))); break; case ModuleFieldType::Import: AppendField(cast<ImportModuleField>(std::move(field))); break; case ModuleFieldType::Export: AppendField(cast<ExportModuleField>(std::move(field))); break; case ModuleFieldType::Type: AppendField(cast<TypeModuleField>(std::move(field))); break; case ModuleFieldType::Table: AppendField(cast<TableModuleField>(std::move(field))); break; case ModuleFieldType::ElemSegment: AppendField(cast<ElemSegmentModuleField>(std::move(field))); break; case ModuleFieldType::Memory: AppendField(cast<MemoryModuleField>(std::move(field))); break; case ModuleFieldType::DataSegment: AppendField(cast<DataSegmentModuleField>(std::move(field))); break; case ModuleFieldType::Start: AppendField(cast<StartModuleField>(std::move(field))); break; case ModuleFieldType::Event: AppendField(cast<EventModuleField>(std::move(field))); break; } } void Module::AppendFields(ModuleFieldList* fields) { while (!fields->empty()) AppendField(std::unique_ptr<ModuleField>(fields->extract_front())); } const Module* Script::GetFirstModule() const { return const_cast<Script*>(this)->GetFirstModule(); } Module* Script::GetFirstModule() { for (const std::unique_ptr<Command>& command : commands) { if (auto* module_command = dyn_cast<ModuleCommand>(command.get())) { return &module_command->module; } } return nullptr; } const Module* Script::GetModule(const Var& var) const { Index index = module_bindings.FindIndex(var); if (index >= commands.size()) { return nullptr; } auto* command = cast<ModuleCommand>(commands[index].get()); return &command->module; } void MakeTypeBindingReverseMapping( size_t num_types, const BindingHash& bindings, std::vector<std::string>* out_reverse_mapping) { out_reverse_mapping->clear(); out_reverse_mapping->resize(num_types); for (const auto& pair : bindings) { assert(static_cast<size_t>(pair.second.index) < out_reverse_mapping->size()); (*out_reverse_mapping)[pair.second.index] = pair.first; } } Var::Var(Index index, const Location& loc) : loc(loc), type_(VarType::Index), index_(index) {} Var::Var(string_view name, const Location& loc) : loc(loc), type_(VarType::Name), name_(name) {} Var::Var(Var&& rhs) : Var(kInvalidIndex) { *this = std::move(rhs); } Var::Var(const Var& rhs) : Var(kInvalidIndex) { *this = rhs; } Var& Var::operator=(Var&& rhs) { loc = rhs.loc; if (rhs.is_index()) { set_index(rhs.index_); } else { set_name(rhs.name_); } return *this; } Var& Var::operator=(const Var& rhs) { loc = rhs.loc; if (rhs.is_index()) { set_index(rhs.index_); } else { set_name(rhs.name_); } return *this; } Var::~Var() { Destroy(); } void Var::set_index(Index index) { Destroy(); type_ = VarType::Index; index_ = index; } void Var::set_name(std::string&& name) { Destroy(); type_ = VarType::Name; Construct(name_, std::move(name)); } void Var::set_name(string_view name) { set_name(name.to_string()); } void Var::Destroy() { if (is_name()) { Destruct(name_); } } uint8_t ElemSegment::GetFlags(const Module* module) const { uint8_t flags = 0; bool all_ref_func = elem_type == Type::FuncRef; switch (kind) { case SegmentKind::Active: { Index table_index = module->GetTableIndex(table_var); if (table_index != 0) { flags |= SegExplicitIndex; } break; } case SegmentKind::Passive: flags |= SegPassive; break; case SegmentKind::Declared: flags |= SegDeclared; break; } all_ref_func = all_ref_func && std::all_of(elem_exprs.begin(), elem_exprs.end(), [](const ElemExpr& elem_expr) { return elem_expr.kind == ElemExprKind::RefFunc; }); if (!all_ref_func) { flags |= SegUseElemExprs; } return flags; } uint8_t DataSegment::GetFlags(const Module* module) const { uint8_t flags = 0; if (kind == SegmentKind::Passive) { flags |= SegPassive; } Index memory_index = module->GetMemoryIndex(memory_var); if (memory_index != 0) { flags |= SegExplicitIndex; } return flags; } } // namespace wabt
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: google/analytics/data/v1beta/analytics_data_api.proto #include "google/analytics/data/v1beta/analytics_data_api.pb.h" #include "google/analytics/data/v1beta/analytics_data_api.grpc.pb.h" #include <functional> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/channel_interface.h> #include <grpcpp/impl/codegen/client_unary_call.h> #include <grpcpp/impl/codegen/client_callback.h> #include <grpcpp/impl/codegen/message_allocator.h> #include <grpcpp/impl/codegen/method_handler.h> #include <grpcpp/impl/codegen/rpc_service_method.h> #include <grpcpp/impl/codegen/server_callback.h> #include <grpcpp/impl/codegen/server_callback_handlers.h> #include <grpcpp/impl/codegen/server_context.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace google { namespace analytics { namespace data { namespace v1beta { static const char* BetaAnalyticsData_method_names[] = { "/google.analytics.data.v1beta.BetaAnalyticsData/RunReport", "/google.analytics.data.v1beta.BetaAnalyticsData/RunPivotReport", "/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunReports", "/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunPivotReports", "/google.analytics.data.v1beta.BetaAnalyticsData/GetMetadata", "/google.analytics.data.v1beta.BetaAnalyticsData/RunRealtimeReport", }; std::unique_ptr< BetaAnalyticsData::Stub> BetaAnalyticsData::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< BetaAnalyticsData::Stub> stub(new BetaAnalyticsData::Stub(channel, options)); return stub; } BetaAnalyticsData::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) : channel_(channel), rpcmethod_RunReport_(BetaAnalyticsData_method_names[0], options.suffix_for_stats(),::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_RunPivotReport_(BetaAnalyticsData_method_names[1], options.suffix_for_stats(),::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_BatchRunReports_(BetaAnalyticsData_method_names[2], options.suffix_for_stats(),::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_BatchRunPivotReports_(BetaAnalyticsData_method_names[3], options.suffix_for_stats(),::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_GetMetadata_(BetaAnalyticsData_method_names[4], options.suffix_for_stats(),::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_RunRealtimeReport_(BetaAnalyticsData_method_names[5], options.suffix_for_stats(),::grpc::internal::RpcMethod::NORMAL_RPC, channel) {} ::grpc::Status BetaAnalyticsData::Stub::RunReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunReportRequest& request, ::google::analytics::data::v1beta::RunReportResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::google::analytics::data::v1beta::RunReportRequest, ::google::analytics::data::v1beta::RunReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_RunReport_, context, request, response); } void BetaAnalyticsData::Stub::async::RunReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunReportRequest* request, ::google::analytics::data::v1beta::RunReportResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::google::analytics::data::v1beta::RunReportRequest, ::google::analytics::data::v1beta::RunReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_RunReport_, context, request, response, std::move(f)); } void BetaAnalyticsData::Stub::async::RunReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunReportRequest* request, ::google::analytics::data::v1beta::RunReportResponse* response, ::grpc::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_RunReport_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::RunReportResponse>* BetaAnalyticsData::Stub::PrepareAsyncRunReportRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunReportRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::google::analytics::data::v1beta::RunReportResponse, ::google::analytics::data::v1beta::RunReportRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_RunReport_, context, request); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::RunReportResponse>* BetaAnalyticsData::Stub::AsyncRunReportRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunReportRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncRunReportRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status BetaAnalyticsData::Stub::RunPivotReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunPivotReportRequest& request, ::google::analytics::data::v1beta::RunPivotReportResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::google::analytics::data::v1beta::RunPivotReportRequest, ::google::analytics::data::v1beta::RunPivotReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_RunPivotReport_, context, request, response); } void BetaAnalyticsData::Stub::async::RunPivotReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunPivotReportRequest* request, ::google::analytics::data::v1beta::RunPivotReportResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::google::analytics::data::v1beta::RunPivotReportRequest, ::google::analytics::data::v1beta::RunPivotReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_RunPivotReport_, context, request, response, std::move(f)); } void BetaAnalyticsData::Stub::async::RunPivotReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunPivotReportRequest* request, ::google::analytics::data::v1beta::RunPivotReportResponse* response, ::grpc::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_RunPivotReport_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::RunPivotReportResponse>* BetaAnalyticsData::Stub::PrepareAsyncRunPivotReportRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunPivotReportRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::google::analytics::data::v1beta::RunPivotReportResponse, ::google::analytics::data::v1beta::RunPivotReportRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_RunPivotReport_, context, request); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::RunPivotReportResponse>* BetaAnalyticsData::Stub::AsyncRunPivotReportRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunPivotReportRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncRunPivotReportRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status BetaAnalyticsData::Stub::BatchRunReports(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunReportsRequest& request, ::google::analytics::data::v1beta::BatchRunReportsResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::google::analytics::data::v1beta::BatchRunReportsRequest, ::google::analytics::data::v1beta::BatchRunReportsResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_BatchRunReports_, context, request, response); } void BetaAnalyticsData::Stub::async::BatchRunReports(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunReportsRequest* request, ::google::analytics::data::v1beta::BatchRunReportsResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::google::analytics::data::v1beta::BatchRunReportsRequest, ::google::analytics::data::v1beta::BatchRunReportsResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_BatchRunReports_, context, request, response, std::move(f)); } void BetaAnalyticsData::Stub::async::BatchRunReports(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunReportsRequest* request, ::google::analytics::data::v1beta::BatchRunReportsResponse* response, ::grpc::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_BatchRunReports_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::BatchRunReportsResponse>* BetaAnalyticsData::Stub::PrepareAsyncBatchRunReportsRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunReportsRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::google::analytics::data::v1beta::BatchRunReportsResponse, ::google::analytics::data::v1beta::BatchRunReportsRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_BatchRunReports_, context, request); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::BatchRunReportsResponse>* BetaAnalyticsData::Stub::AsyncBatchRunReportsRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunReportsRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncBatchRunReportsRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status BetaAnalyticsData::Stub::BatchRunPivotReports(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunPivotReportsRequest& request, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::google::analytics::data::v1beta::BatchRunPivotReportsRequest, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_BatchRunPivotReports_, context, request, response); } void BetaAnalyticsData::Stub::async::BatchRunPivotReports(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunPivotReportsRequest* request, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::google::analytics::data::v1beta::BatchRunPivotReportsRequest, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_BatchRunPivotReports_, context, request, response, std::move(f)); } void BetaAnalyticsData::Stub::async::BatchRunPivotReports(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunPivotReportsRequest* request, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse* response, ::grpc::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_BatchRunPivotReports_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::BatchRunPivotReportsResponse>* BetaAnalyticsData::Stub::PrepareAsyncBatchRunPivotReportsRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunPivotReportsRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::google::analytics::data::v1beta::BatchRunPivotReportsResponse, ::google::analytics::data::v1beta::BatchRunPivotReportsRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_BatchRunPivotReports_, context, request); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::BatchRunPivotReportsResponse>* BetaAnalyticsData::Stub::AsyncBatchRunPivotReportsRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::BatchRunPivotReportsRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncBatchRunPivotReportsRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status BetaAnalyticsData::Stub::GetMetadata(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::GetMetadataRequest& request, ::google::analytics::data::v1beta::Metadata* response) { return ::grpc::internal::BlockingUnaryCall< ::google::analytics::data::v1beta::GetMetadataRequest, ::google::analytics::data::v1beta::Metadata, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_GetMetadata_, context, request, response); } void BetaAnalyticsData::Stub::async::GetMetadata(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::GetMetadataRequest* request, ::google::analytics::data::v1beta::Metadata* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::google::analytics::data::v1beta::GetMetadataRequest, ::google::analytics::data::v1beta::Metadata, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_GetMetadata_, context, request, response, std::move(f)); } void BetaAnalyticsData::Stub::async::GetMetadata(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::GetMetadataRequest* request, ::google::analytics::data::v1beta::Metadata* response, ::grpc::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_GetMetadata_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::Metadata>* BetaAnalyticsData::Stub::PrepareAsyncGetMetadataRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::GetMetadataRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::google::analytics::data::v1beta::Metadata, ::google::analytics::data::v1beta::GetMetadataRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_GetMetadata_, context, request); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::Metadata>* BetaAnalyticsData::Stub::AsyncGetMetadataRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::GetMetadataRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncGetMetadataRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status BetaAnalyticsData::Stub::RunRealtimeReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunRealtimeReportRequest& request, ::google::analytics::data::v1beta::RunRealtimeReportResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::google::analytics::data::v1beta::RunRealtimeReportRequest, ::google::analytics::data::v1beta::RunRealtimeReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_RunRealtimeReport_, context, request, response); } void BetaAnalyticsData::Stub::async::RunRealtimeReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunRealtimeReportRequest* request, ::google::analytics::data::v1beta::RunRealtimeReportResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::google::analytics::data::v1beta::RunRealtimeReportRequest, ::google::analytics::data::v1beta::RunRealtimeReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_RunRealtimeReport_, context, request, response, std::move(f)); } void BetaAnalyticsData::Stub::async::RunRealtimeReport(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunRealtimeReportRequest* request, ::google::analytics::data::v1beta::RunRealtimeReportResponse* response, ::grpc::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_RunRealtimeReport_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::RunRealtimeReportResponse>* BetaAnalyticsData::Stub::PrepareAsyncRunRealtimeReportRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunRealtimeReportRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::google::analytics::data::v1beta::RunRealtimeReportResponse, ::google::analytics::data::v1beta::RunRealtimeReportRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_RunRealtimeReport_, context, request); } ::grpc::ClientAsyncResponseReader< ::google::analytics::data::v1beta::RunRealtimeReportResponse>* BetaAnalyticsData::Stub::AsyncRunRealtimeReportRaw(::grpc::ClientContext* context, const ::google::analytics::data::v1beta::RunRealtimeReportRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncRunRealtimeReportRaw(context, request, cq); result->StartCall(); return result; } BetaAnalyticsData::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( BetaAnalyticsData_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< BetaAnalyticsData::Service, ::google::analytics::data::v1beta::RunReportRequest, ::google::analytics::data::v1beta::RunReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](BetaAnalyticsData::Service* service, ::grpc::ServerContext* ctx, const ::google::analytics::data::v1beta::RunReportRequest* req, ::google::analytics::data::v1beta::RunReportResponse* resp) { return service->RunReport(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( BetaAnalyticsData_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< BetaAnalyticsData::Service, ::google::analytics::data::v1beta::RunPivotReportRequest, ::google::analytics::data::v1beta::RunPivotReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](BetaAnalyticsData::Service* service, ::grpc::ServerContext* ctx, const ::google::analytics::data::v1beta::RunPivotReportRequest* req, ::google::analytics::data::v1beta::RunPivotReportResponse* resp) { return service->RunPivotReport(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( BetaAnalyticsData_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< BetaAnalyticsData::Service, ::google::analytics::data::v1beta::BatchRunReportsRequest, ::google::analytics::data::v1beta::BatchRunReportsResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](BetaAnalyticsData::Service* service, ::grpc::ServerContext* ctx, const ::google::analytics::data::v1beta::BatchRunReportsRequest* req, ::google::analytics::data::v1beta::BatchRunReportsResponse* resp) { return service->BatchRunReports(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( BetaAnalyticsData_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< BetaAnalyticsData::Service, ::google::analytics::data::v1beta::BatchRunPivotReportsRequest, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](BetaAnalyticsData::Service* service, ::grpc::ServerContext* ctx, const ::google::analytics::data::v1beta::BatchRunPivotReportsRequest* req, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse* resp) { return service->BatchRunPivotReports(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( BetaAnalyticsData_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< BetaAnalyticsData::Service, ::google::analytics::data::v1beta::GetMetadataRequest, ::google::analytics::data::v1beta::Metadata, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](BetaAnalyticsData::Service* service, ::grpc::ServerContext* ctx, const ::google::analytics::data::v1beta::GetMetadataRequest* req, ::google::analytics::data::v1beta::Metadata* resp) { return service->GetMetadata(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( BetaAnalyticsData_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< BetaAnalyticsData::Service, ::google::analytics::data::v1beta::RunRealtimeReportRequest, ::google::analytics::data::v1beta::RunRealtimeReportResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](BetaAnalyticsData::Service* service, ::grpc::ServerContext* ctx, const ::google::analytics::data::v1beta::RunRealtimeReportRequest* req, ::google::analytics::data::v1beta::RunRealtimeReportResponse* resp) { return service->RunRealtimeReport(ctx, req, resp); }, this))); } BetaAnalyticsData::Service::~Service() { } ::grpc::Status BetaAnalyticsData::Service::RunReport(::grpc::ServerContext* context, const ::google::analytics::data::v1beta::RunReportRequest* request, ::google::analytics::data::v1beta::RunReportResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status BetaAnalyticsData::Service::RunPivotReport(::grpc::ServerContext* context, const ::google::analytics::data::v1beta::RunPivotReportRequest* request, ::google::analytics::data::v1beta::RunPivotReportResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status BetaAnalyticsData::Service::BatchRunReports(::grpc::ServerContext* context, const ::google::analytics::data::v1beta::BatchRunReportsRequest* request, ::google::analytics::data::v1beta::BatchRunReportsResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status BetaAnalyticsData::Service::BatchRunPivotReports(::grpc::ServerContext* context, const ::google::analytics::data::v1beta::BatchRunPivotReportsRequest* request, ::google::analytics::data::v1beta::BatchRunPivotReportsResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status BetaAnalyticsData::Service::GetMetadata(::grpc::ServerContext* context, const ::google::analytics::data::v1beta::GetMetadataRequest* request, ::google::analytics::data::v1beta::Metadata* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status BetaAnalyticsData::Service::RunRealtimeReport(::grpc::ServerContext* context, const ::google::analytics::data::v1beta::RunRealtimeReportRequest* request, ::google::analytics::data::v1beta::RunRealtimeReportResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace google } // namespace analytics } // namespace data } // namespace v1beta
#include "BioSequences.h" //how to use the module //g++ BioSequenceTest.cpp -L. -lbiosequences_core -lboost_filesystem -lboost_system int main() { BioSequences bs; string db_fa = "/home/xuan/biosequence/BioSequence/t2.fa"; int i = bs.guessFormat(db_fa); int j = bs.getNumSeqs(db_fa); cout << "i = " << i << endl; cout << "j = " << j << endl; BioAlphabet ba_DNA = bs.getBioAlphabetInstance("DNA"); BioAlphabet ba_Dna = bs.getBioAlphabetInstance("Dna"); BioAlphabet ba_protein = bs.getBioAlphabetInstance("protein"); BioAlphabet ba_Protein = bs.getBioAlphabetInstance("Protein"); char **seqs = new char* [j]; int *seq_length = new int [j]; int k = bs.loadingFasta(ba_Dna,db_fa,seqs,seq_length); int p = bs.loadingFasta(ba_protein,db_fa,seqs,seq_length); cout <<"k = "<<k<<"\t"<<" p = "<<p<<endl; delete seqs, seq_length; return 1; }
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_coding/codecs/vp8/vp8_factory.h" #include "webrtc/modules/video_coding/codecs/vp8/simulcast_encoder_adapter.h" #include "webrtc/modules/video_coding/codecs/vp8/vp8_impl.h" namespace webrtc { bool VP8EncoderFactoryConfig::use_simulcast_adapter_ = false; class VP8EncoderImplFactory : public VideoEncoderFactory { public: VideoEncoder* Create() override { return new VP8EncoderImpl(); } void Destroy(VideoEncoder* encoder) override { delete encoder; } virtual ~VP8EncoderImplFactory() {} }; VP8Encoder* VP8Encoder::Create() { if (VP8EncoderFactoryConfig::use_simulcast_adapter()) { return new SimulcastEncoderAdapter(new VP8EncoderImplFactory()); } else { return new VP8EncoderImpl(); } } VP8Decoder* VP8Decoder::Create() { return new VP8DecoderImpl(); } } // namespace webrtc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstring> #include "base/strings/utf_string_conversions.h" #include "ppapi/c/dev/ppb_memory_dev.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_image_data.h" #include "ppapi/proxy/pdf_resource.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/ppapi_proxy_test.h" #include "ppapi/proxy/ppb_image_data_proxy.h" #include "ppapi/proxy/serialized_handle.h" #include "ppapi/shared_impl/proxy_lock.h" #include "ppapi/shared_impl/scoped_pp_var.h" #include "ppapi/shared_impl/var.h" #include "ppapi/thunk/thunk.h" namespace ppapi { namespace proxy { namespace { typedef PluginProxyTest PDFResourceTest; } // namespace TEST_F(PDFResourceTest, SearchString) { ProxyAutoLock lock; // Instantiate a resource explicitly so we can specify the locale. auto pdf_resource = base::MakeRefCounted<PDFResource>( Connection(&sink(), &sink(), 0), pp_instance()); pdf_resource->SetLocaleForTest("en-US@collation=search"); std::u16string input; std::u16string term; base::UTF8ToUTF16("abcdefabcdef", 12, &input); base::UTF8ToUTF16("bc", 2, &term); PP_PrivateFindResult* results; uint32_t count = 0; pdf_resource->SearchString( reinterpret_cast<const unsigned short*>(input.c_str()), reinterpret_cast<const unsigned short*>(term.c_str()), true, &results, &count); ASSERT_EQ(2U, count); ASSERT_EQ(1, results[0].start_index); ASSERT_EQ(2, results[0].length); ASSERT_EQ(7, results[1].start_index); ASSERT_EQ(2, results[1].length); const PPB_Memory_Dev* memory_iface = thunk::GetPPB_Memory_Dev_0_1_Thunk(); memory_iface->MemFree(results); } TEST_F(PDFResourceTest, DidStartLoading) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); pdf_iface->DidStartLoading(pp_instance()); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_DidStartLoading::ID, &params, &msg)); } TEST_F(PDFResourceTest, DidStopLoading) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); pdf_iface->DidStopLoading(pp_instance()); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_DidStopLoading::ID, &params, &msg)); } TEST_F(PDFResourceTest, SetContentRestriction) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); int restrictions = 5; pdf_iface->SetContentRestriction(pp_instance(), restrictions); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_SetContentRestriction::ID, &params, &msg)); } TEST_F(PDFResourceTest, HasUnsupportedFeature) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); pdf_iface->HasUnsupportedFeature(pp_instance()); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_HasUnsupportedFeature::ID, &params, &msg)); } TEST_F(PDFResourceTest, Print) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); pdf_iface->Print(pp_instance()); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_Print::ID, &params, &msg)); } TEST_F(PDFResourceTest, SaveAs) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); pdf_iface->SaveAs(pp_instance()); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_SaveAs::ID, &params, &msg)); } TEST_F(PDFResourceTest, SelectionChanged) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); PP_FloatPoint left = PP_MakeFloatPoint(0.0f, 0.0f); PP_FloatPoint right = PP_MakeFloatPoint(1.0f, 1.0f); pdf_iface->SelectionChanged(pp_instance(), &left, 0, &right, 0); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_SelectionChanged::ID, &params, &msg)); } TEST_F(PDFResourceTest, SetPluginCanSave) { const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); pdf_iface->SetPluginCanSave(pp_instance(), true); ResourceMessageCallParams params; IPC::Message msg; ASSERT_TRUE(sink().GetFirstResourceCallMatching( PpapiHostMsg_PDF_SetPluginCanSave::ID, &params, &msg)); } } // namespace proxy } // namespace ppapi
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medJobManager.h> #include <medJobItem.h> medJobManager *medJobManager::s_instance = NULL; class medJobManagerPrivate { public: QList<medJobItem*> itemList; bool m_IsActive; }; medJobManager *medJobManager::instance(void) { if(!s_instance) s_instance = new medJobManager; return s_instance; } medJobManager::medJobManager( void ) : d(new medJobManagerPrivate) { d->m_IsActive = true; } medJobManager::~medJobManager( void ) { delete d; d = NULL; } bool medJobManager::registerJobItem( medJobItem* item, QString jobName) { if(d->m_IsActive) { d->itemList.append(item); connect(this, SIGNAL(cancel(QObject*)), item, SLOT(onCancel(QObject*)) ); emit jobRegistered(item, jobName); return true; } return false; } bool medJobManager::unRegisterJobItem( medJobItem* item ) { int index = d->itemList.indexOf(item); if (index != -1) { disconnect(this, SIGNAL(cancel(QObject*)), item, SLOT(onCancel(QObject*)) ); d->itemList.removeAt(index); return true; } return false; } void medJobManager::dispatchGlobalCancelEvent(bool ignoreNewJobItems) { if (ignoreNewJobItems) d->m_IsActive = false; foreach( medJobItem* item, d->itemList ) emit cancel( item ); }
#include "App.h" #include "Gui.h" int WINAPI WinMain(HINSTANCE instance, HINSTANCE prev, LPSTR args, int cmd) { Gui display("Visualiser: Press 'O' to open PPM file"); App app; app.setupOpenCL(); app.setupMask(); display.onInput([&](int key, int state) { if (key == GLFW_KEY_DOWN && state == GLFW_PRESS) app.updateRadius(-1); if (key == GLFW_KEY_UP && state == GLFW_PRESS) app.updateRadius(1); if (key == GLFW_KEY_1 && state == GLFW_PRESS) app.showSource(); if (key == GLFW_KEY_2 && state == GLFW_PRESS) app.showSecondPass(); if (key == GLFW_KEY_3 && state == GLFW_PRESS) app.showFinalResult(); if (key == GLFW_KEY_O && state == GLFW_PRESS) app.updateFile(); }); display.onPaint([&]() { auto title = app.toString(); app.updateTexture(); if (app.hasImage()) { display.title(title); display.quad(1.0); } }); }
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license * * Copyright (C) 2022 Elisha Riedlinger * * This software is provided 'as-is', without any express or implied warranty. In no event will the * authors be held liable for any damages arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #pragma once #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <d3d9.h> #include "com_ptr.hpp" namespace reshade::d3d9 { class state_block { public: explicit state_block(IDirect3DDevice9 *device); ~state_block(); bool init_state_block(); void release_state_block(); void capture(); void apply_and_release(); private: void release_all_device_objects(); com_ptr<IDirect3DDevice9> _device; com_ptr<IDirect3DStateBlock9> _state_block; UINT _num_simultaneous_rendertargets; D3DVIEWPORT9 _viewport; com_ptr<IDirect3DSurface9> _depth_stencil; com_ptr<IDirect3DSurface9> _render_targets[8]; }; }
/* Copyright 2018 The TensorFlow Authors. 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 <iostream> #include <string> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "tensorflow/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/lite/toco/graph_transformations/lstm_utils.h" #include "tensorflow/lite/toco/model.h" #include "tensorflow/lite/toco/tooling_util.h" namespace toco { ::tensorflow::Status SplitLstmCellInputs::Run(Model* model, std::size_t op_index, bool* modified) { *modified = false; // Find lstm cell. auto op_it = model->operators.begin() + op_index; auto curr_op = op_it->get(); if (curr_op->type != OperatorType::kLstmCell) { return ::tensorflow::Status::OK(); } const auto* curr_lstm_op = static_cast<LstmCellOperator*>(curr_op); // Already an extended LstmCell. Do not need to split cell inputs. if (curr_lstm_op->kernel_type != LstmCellOperator::KERNEL_BASIC || curr_lstm_op->inputs.size() != LstmCellOperator::NUM_INPUTS) { return ::tensorflow::Status::OK(); } // Make sure the WEIGHTS_INPUT and BIASES_INPUT are constant arrays, // that are able to be split into smaller weight and bias tensors. if (!IsConstantParameterArray( *model, curr_op->inputs[LstmCellOperator::WEIGHTS_INPUT]) || !IsConstantParameterArray( *model, curr_op->inputs[LstmCellOperator::BIASES_INPUT])) { return ::tensorflow::Status::OK(); } // Make sure propagate_fixed_sizes has defined the size of the output. if (!model->GetArray(curr_op->outputs[LstmCellOperator::ACTIV_OUTPUT]) .has_shape()) { return ::tensorflow::Status::OK(); } // Emplace a new LstmCell operator with extended inputs (kernel/lstm.cc). auto lstm_cell_op = absl::make_unique<LstmCellOperator>(); lstm_cell_op->kernel_type = LstmCellOperator::KERNEL_FULL; lstm_cell_op->inputs.resize(kExtendedLstmInputCount); int num_input = model->GetArray(curr_op->inputs[LstmCellOperator::DATA_INPUT]) .shape() .dims(1); // n_cell and n_output have the same size when there is no projection. int num_cell = model->GetArray(curr_op->outputs[LstmCellOperator::ACTIV_OUTPUT]) .shape() .dims(1); int num_output = num_cell; // Data input. lstm_cell_op->inputs[kInputTensor] = curr_op->inputs[LstmCellOperator::ACTIV_OUTPUT]; // Previous states. lstm_cell_op->inputs[kInputActivationStateTensor] = curr_op->inputs[LstmCellOperator::PREV_ACTIV_INPUT]; lstm_cell_op->inputs[kInputCellStateTensor] = curr_op->inputs[LstmCellOperator::PREV_STATE_INPUT]; // Get original weight tensor and decompose 1 tensor to 8 sub tensors. Array& kernel = model->GetArray(curr_op->inputs[LstmCellOperator::WEIGHTS_INPUT]); const string base_name(FindLongestCommonPrefix( curr_op->outputs[LstmCellOperator::ACTIV_OUTPUT], curr_op->outputs[LstmCellOperator::STATE_OUTPUT])); // Input weight tensors of size {n_cell, n_input}. CopySubArrayToArray( model, &(lstm_cell_op->inputs[kInputToInputWeightsTensor]), base_name + "weight_i_i", num_cell, num_input, kernel, 0, 0); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kInputToCellWeightsTensor]), base_name + "weight_c_i", num_cell, num_input, kernel, num_cell, 0); CopySubArrayToArray( model, &(lstm_cell_op->inputs[kInputToForgetWeightsTensor]), base_name + "weight_f_i", num_cell, num_input, kernel, num_cell * 2, 0); CopySubArrayToArray( model, &(lstm_cell_op->inputs[kInputToOutputWeightsTensor]), base_name + "weight_o_i", num_cell, num_input, kernel, num_cell * 3, 0); // Recurrent weight tensors of size {n_cell, n_output}. CopySubArrayToArray( model, &(lstm_cell_op->inputs[kRecurrentToInputWeightsTensor]), base_name + "weight_i_r", num_cell, num_output, kernel, 0, num_input); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kRecurrentToCellWeightsTensor]), base_name + "weight_c_r", num_cell, num_output, kernel, num_cell, num_input); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kRecurrentToForgetWeightsTensor]), base_name + "weight_f_r", num_cell, num_output, kernel, num_cell * 2, num_input); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kRecurrentToOutputWeightsTensor]), base_name + "weight_o_r", num_cell, num_output, kernel, num_cell * 3, num_input); // Peephole (optional). CreateOptionalArray(model, &(lstm_cell_op->inputs[kCellToInputWeightsTensor]), base_name + "peephole_c_i"); CreateOptionalArray(model, &(lstm_cell_op->inputs[kCellToForgetWeightsTensor]), base_name + "peephole_c_f"); CreateOptionalArray(model, &(lstm_cell_op->inputs[kCellToOutputWeightsTensor]), base_name + "peephole_c_o"); // Get original bias tensor and decompose 1 tensor to 4 sub tensors Array& bias = model->GetArray(curr_op->inputs[LstmCellOperator::BIASES_INPUT]); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kInputGateBiasTensor]), base_name + "bias_i", num_cell, 1, bias, 0, 0); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kCellGateBiasTensor]), base_name + "bias_c", num_cell, 1, bias, num_cell, 0); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kForgetGateBiasTensor]), base_name + "bias_f", num_cell, 1, bias, num_cell * 2, 0); CopySubArrayToArray(model, &(lstm_cell_op->inputs[kOutputGateBiasTensor]), base_name + "bias_o", num_cell, 1, bias, num_cell * 3, 0); // Projection (optional). CreateOptionalArray(model, &(lstm_cell_op->inputs[kProjectionWeightsTensor]), base_name + "proj_weight"); CreateOptionalArray(model, &(lstm_cell_op->inputs[kProjectionBiasTensor]), base_name + "proj_bias"); // Reorder and resize LstmCell's outputs. lstm_cell_op->outputs.resize( ExtendedLstmCellOutputs::kExtendedLstmOutputCount); lstm_cell_op->outputs[kOutputStateTensor] = curr_op->outputs[LstmCellOperator::ACTIV_TEMP]; lstm_cell_op->outputs[kCellStateTensor] = curr_op->outputs[LstmCellOperator::STATE_OUTPUT]; lstm_cell_op->outputs[kOutputTensor] = curr_op->outputs[LstmCellOperator::ACTIV_OUTPUT]; // Add the op into model. model->operators.emplace(op_it, std::move(lstm_cell_op)); AddMessageF("Creating extended LstmCell replacing previous lstm cell"); DeleteOpAndArrays(model, curr_op); *modified = true; return ::tensorflow::Status::OK(); } } // namespace toco
//////////////////////////////////////////////////////////////////////////// // SSWND.CPP // // Implementation of CScreenSaverWindow // // History: // // Author Date Description // ------ ---- ----------- // jaym 08/26/96 Created // jaym 01/24/97 Added password verification // jaym 04/15/97 Toolbar UI updates // jaym 05/05/97 Removed Toolbar // jaym 05/19/97 Re-added Toolbar ///////////////////////////////////////////////////////////////////////////// #include "precomp.h" #include <regstr.h> #include "regini.h" #include "resource.h" #include "sswnd.h" #define TF_DEBUGQI 0 #define TF_DEBUGQS 0 #define TF_DEBUGREFCOUNT 0 #define TF_NAVIGATION 0 #define TF_NOTIFY 0 #define TF_TIMER 0 #define TF_FUNCENTRY 0 #define TF_CLOSE TF_ALWAYS #define WM_LOADSCREENSAVER (WM_USER+550) ///////////////////////////////////////////////////////////////////////////// // Global variables ///////////////////////////////////////////////////////////////////////////// BOOL g_bPasswordEnabled; extern BOOL g_bPlatformNT; extern TCHAR g_szRegSubKey[]; extern IMalloc * g_pMalloc; extern IMMASSOCPROC g_pfnIMMProc; ///////////////////////////////////////////////////////////////////////////// // Module variables ///////////////////////////////////////////////////////////////////////////// static CScreenSaverWindow * s_pThis = NULL; static HHOOK s_hKeyboardHook = NULL; static HHOOK s_hMouseHook = NULL; #pragma data_seg(DATASEG_READONLY) static const TCHAR s_szScreenSaverKey[] = REGSTR_PATH_SCREENSAVE; static const TCHAR s_szPasswordActiveValue[] = REGSTR_VALUE_USESCRPASSWORD; static const TCHAR s_szPasswordActiveOnNTValue[] = TEXT("ScreenSaverIsSecure"); static const TCHAR s_szPasswordValue[] = REGSTR_VALUE_SCRPASSWORD; static const TCHAR s_szPasswordDLL[] = TEXT("PASSWORD.CPL"); static const TCHAR s_szPasswordFnName[] = TEXT("VerifyScreenSavePwd"); // Password static const TCHAR s_szRegLastURL[] = TEXT("LastURL"); static const TCHAR s_szRegLastNavURL[] = TEXT("LastNavURL"); static const TCHAR s_szSETermEvent[] = TEXT("ActSaverSEEvent"); static const TCHAR s_szTrayUIWindow[] = TEXT("MS_WebcheckMonitor"); static const TCHAR s_szRES[] = TEXT("res://"); static const TCHAR s_szSSEmptyFile[] = TEXT("/ssempty.htm"); static const OLECHAR s_szYes[] = OLESTR("YES"); static const OLECHAR s_szNo[] = OLESTR("NO"); static const OLECHAR s_szDefTransition[] = OLESTR("revealTrans(Duration=5.0, Transition=15)"); // Misc. #pragma data_seg() ///////////////////////////////////////////////////////////////////////////// // Design constants ///////////////////////////////////////////////////////////////////////////// #define MOUSEMOVE_THRESHOLD 10 // In pixels // Number of pixels that the mouse must move to determine a // 'real' mouse move event (for closing the Screen Saver). #define ID_CHANNELCHANGE_TIMER 0x0100 // Channel change/update timer ID #define ID_CONTROLS_TIMER 0x0101 // Scrollbar/Toolbar show/hide timer ID #define ID_CLICKCHECK_TIMER 0x0102 // Hotlink click check timer ID #define ID_RESTART_TIMER 0x0103 // Restart timer ID #define TIME_CONTROLS_TIMEOUT 3000 // ms (3 seconds) // Scrollbar/Toolbar show/hide timeout #define TIME_CLICKCHECK_TIMEOUT 1000 // ms (1 second) // Hotlink click check timeout #define TIME_NAVIGATE_TIMEOUT 10000 // ms (10 seconds) // WebBrowser Navigate timeout #define CX_TOOLBAR 51 #define CY_TOOLBAR 29 // Toolbar dimensions ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow ///////////////////////////////////////////////////////////////////////////// CScreenSaverWindow::CScreenSaverWindow ( ) { m_cRef = 0; m_pToolbar = NULL; m_bModelessEnabled = TRUE; m_bMouseClicked = FALSE; m_bScrollbarVisible = TRUE; m_pScreenSaver = NULL; m_pSSConfig = NULL; m_idChangeTimer = 0; m_idControlsTimer = 0; m_idClickCheckTimer = 0; m_idReloadTimer = 0; m_pPIDLList = NULL; m_pidlDefault = NULL; m_lCurrChannel = CURRENT_CHANNEL_NONE; m_pUnkBrowser = NULL; m_pWebBrowser = NULL; m_pOleObject = NULL; m_pHlinkFrame = NULL; m_pHTMLDocument = NULL; m_dwWebBrowserEvents = 0L; m_dwWebBrowserEvents2 = 0L; m_dwHTMLDocumentEvents = 0L; m_pBindStatusCallback = NULL; m_hPasswordDLL = NULL; m_pfnVerifyPassword = NULL; m_hPrevBrowserIMC = 0; m_lVerifingPassword = FALSE; } CScreenSaverWindow::~CScreenSaverWindow ( ) { // All clean-up is done in OnDestroy and OnNCDestroy. } // // Helper routine to check appropriate registry value to see if screensaver // is password protected. // BOOL IsScreenSaverPasswordProtected() { BOOL bRetValue = FALSE; HKEY hKey; if (RegOpenKey( HKEY_CURRENT_USER, s_szScreenSaverKey, &hKey) == ERROR_SUCCESS) { // // Registry key string is different on Win95 & NT !!! // if (g_bPlatformNT) { CHAR buf[4]; DWORD dwSize = sizeof(buf); if (RegQueryValueEx(hKey, s_szPasswordActiveOnNTValue, NULL, NULL, (BYTE *)buf, &dwSize) == ERROR_SUCCESS) { // // check if "1" is returned in buf // if (dwSize == 2 && buf[0] == '1') { bRetValue = TRUE; } } } else { DWORD dwVal; DWORD dwSize = sizeof(DWORD); if ( (RegQueryValueEx( hKey, s_szPasswordActiveValue, NULL, NULL, (BYTE *)&dwVal, &dwSize) == ERROR_SUCCESS) && (dwVal != 0) ) { bRetValue = TRUE; } } RegCloseKey(hKey); } return bRetValue; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::Create ///////////////////////////////////////////////////////////////////////////// BOOL CScreenSaverWindow::Create ( const RECT & rect, HWND hwndParent, IScreenSaver * pScreenSaver ) { HRESULT hrResult; ASSERT(pScreenSaver != NULL); TraceMsg(TF_ALWAYS, "CScreenSaverWindow::Create(hwndParent=%x)", hwndParent); // // Set the g_bPasswordEnabled flag // g_bPasswordEnabled = IsScreenSaverPasswordProtected(); for (;;) { // Save this pointer for Hook functions. s_pThis = this; // Save IScreenSaver interface pointer. m_pScreenSaver = pScreenSaver; m_pScreenSaver->AddRef(); // Get the Configuration interface pointer. if (FAILED(hrResult = m_pScreenSaver->QueryInterface(IID_IScreenSaverConfig, (void **)&m_pSSConfig))) break; DWORD dwFeatureFlags; EVAL(SUCCEEDED(m_pSSConfig->get_Features(&dwFeatureFlags))); // Create the actual window. if (!CWindow::CreateEx( NULL, ((dwFeatureFlags & FEATURE_NOT_TOPMOST) ? 0 : (WS_EX_TOOLWINDOW | WS_EX_TOPMOST)), WS_POPUP, rect, hwndParent, 0)) { hrResult = E_OUTOFMEMORY; break; } TraceMsg(TF_ALWAYS, "CScreenSaverWindow::Create(m_hWnd=%x)", m_hWnd ); // If we aren't on NT, load the password verification DLL. if (!g_bPlatformNT) LoadPasswordDLL(); // Create PIDL for default HTML page char szModuleName[MAX_PATH]; GetModuleFileName(_pModule->GetModuleInstance(), szModuleName, MAX_PATH); CString strURLDefault; strURLDefault = s_szRES; strURLDefault += PathFindFileName(szModuleName); strURLDefault += s_szSSEmptyFile; EVAL(CreatePIDLFromPath(strURLDefault, &m_pidlDefault)); // Create the toolbar. RECT rectToolbar; rectToolbar.left = rect.right - CX_TOOLBAR; rectToolbar.top = 0; rectToolbar.right = rectToolbar.left + CX_TOOLBAR; rectToolbar.bottom = rectToolbar.top + CY_TOOLBAR; m_pToolbar = new CToolbarWindow; if (NULL == m_pToolbar) { hrResult = E_OUTOFMEMORY; break; } if (!m_pToolbar->Create(rectToolbar, this)) { delete m_pToolbar; m_pToolbar = NULL; hrResult = E_OUTOFMEMORY; break; } // Initialize the channel view list. InitChannelList(); // TODO: Darrenmi add online/offline registration here. // Initialize the web browser. if (!CreateWebBrowser(rect)) { CString strCaption; CString strText; // Display error message. strCaption.LoadString(IDS_SCREENSAVER_DESC); strText.LoadString(IDS_ERROR_REQUIREMENTSNOTMET); MessageBox(hwndParent, strText, strCaption, MB_OK); hrResult = E_OUTOFMEMORY; break; } // Setup the Keyboard and Mouse hooks. SetHooks(); // Show the first channel. DisplayCurrentChannel(); // Start the reload timer. if (!g_bPlatformNT) { DWORD dwRestartTime; EVAL(SUCCEEDED(m_pSSConfig->get_RestartTime(&dwRestartTime))); EVAL((m_idReloadTimer = SetTimer( ID_RESTART_TIMER, dwRestartTime, NULL)) != 0); } hrResult = S_OK; break; } return SUCCEEDED(hrResult); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::ShowControls ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::ShowControls ( BOOL bShow ) { TraceMsg( TF_FUNCENTRY, "ShowControls(%d): m_bScrollbarVisible = %d, Toolbar = %d", bShow, m_bScrollbarVisible, m_pToolbar->IsWindowVisible()); // Kill the current 'controls timer' and restart if needed. if (m_idControlsTimer != 0) { EVAL(KillTimer(m_idControlsTimer)); m_idControlsTimer = 0; } // Screen saver does not need the IME. if (g_pfnIMMProc != NULL) { if (m_hPrevBrowserIMC != 0) { g_pfnIMMProc(m_hwndContainer, m_hPrevBrowserIMC); m_hPrevBrowserIMC = 0; } ASSERT(m_hwndContainer != NULL) m_hPrevBrowserIMC = g_pfnIMMProc(m_hwndContainer, (HIMC)NULL); } IHTMLBodyElement * pHTMLBodyElement = NULL; BOOL bLongContent = FALSE; RECT rectClient; GetClientRect(&rectClient); // Check to see if the content is long enough to warrant scrollbars. if ( SUCCEEDED(GetHTMLBodyElement(&pHTMLBodyElement)) && (pHTMLBodyElement != NULL) ) { IHTMLTextContainer * pTxtEdit = NULL; if ( (SUCCEEDED(pHTMLBodyElement->QueryInterface(IID_IHTMLTextContainer, (void **)&pTxtEdit))) && (pTxtEdit != NULL) ) { long lHeight; EVAL(SUCCEEDED(pTxtEdit->get_scrollHeight(&lHeight))); bLongContent = (lHeight > (rectClient.bottom - rectClient.top)); pTxtEdit->Release(); } } // Don't show scrollbar if we don't need them. if (pHTMLBodyElement != NULL) { if (m_bScrollbarVisible != bShow) { BSTR bstrScroll = SysAllocString(((bShow && bLongContent)? s_szYes : s_szNo)); if (bstrScroll) { pHTMLBodyElement->put_scroll(bstrScroll); SysFreeString(bstrScroll); m_bScrollbarVisible = bShow; } } pHTMLBodyElement->Release(); } // Show the toolbar, too. if ((m_pToolbar != NULL) && (m_pToolbar->IsWindowVisible() != bShow)) { RECT rectToolbar; m_pToolbar->GetWindowRect(&rectToolbar); // Position toolbar appropriately, depending // on visibility of the scrollbar. if (bLongContent) { if (rectToolbar.right == rectClient.right) { OffsetRect(&rectToolbar, -GetSystemMetrics(SM_CXVSCROLL), 0); m_pToolbar->SetWindowPos( NULL, &rectToolbar, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOSIZE); } } else { if (rectToolbar.right != rectClient.right) { OffsetRect(&rectToolbar, GetSystemMetrics(SM_CXVSCROLL), 0); m_pToolbar->SetWindowPos( NULL, &rectToolbar, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOSIZE); } } m_pToolbar->ShowToolbar(bShow); } if ( m_bScrollbarVisible || ((m_pToolbar != NULL) && m_pToolbar->IsWindowVisible()) ) { EVAL((m_idControlsTimer = SetTimer( ID_CONTROLS_TIMER, TIME_CONTROLS_TIMEOUT, NULL)) != 0); } // REVIEW: Should use UIActivate? [jaym] POINT pt = { 0 }; m_hwndContainer = WindowFromPoint(pt); SetFocus(m_hwndContainer); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::ShowPropertiesDlg ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::ShowPropertiesDlg ( HWND hwndParent ) { // Save the 'current' channel. SaveState(); EnableModeless(FALSE); m_pSSConfig->ShowDialog(hwndParent); EnableModeless(TRUE); // Reinitialize the internal channel list. InitChannelList(); // Show the first channel in the new list. DisplayCurrentChannel(); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnCreate ///////////////////////////////////////////////////////////////////////////// BOOL CScreenSaverWindow::OnCreate ( CREATESTRUCT * pcs ) { return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnDestroy ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::OnDestroy ( ) { TraceMsg(TF_CLOSE, "CScreenSaverWindow::OnDestroy() BEGIN"); ReleaseHooks(); if (m_idChangeTimer != 0) EVAL(KillTimer(m_idChangeTimer)); if (m_idControlsTimer != 0) EVAL(KillTimer(m_idControlsTimer)); if (m_idClickCheckTimer != 0) EVAL(KillTimer(m_idClickCheckTimer)); if (m_idReloadTimer != 0) EVAL(KillTimer(m_idReloadTimer)); if (m_pToolbar != NULL) delete m_pToolbar; if (m_hPrevBrowserIMC != 0) { ASSERT(m_hwndContainer != NULL); g_pfnIMMProc(m_hwndContainer, m_hPrevBrowserIMC); } // TODO: Darrenmi add online/offline deregistration here. ConnectToConnectionPoint( SAFECAST(this, IDispatch *), DIID_DWebBrowserEvents, FALSE, m_pUnkBrowser, &m_dwWebBrowserEvents, NULL); ConnectToConnectionPoint( SAFECAST(this, IDispatch *), DIID_DWebBrowserEvents2, FALSE, m_pUnkBrowser, &m_dwWebBrowserEvents2, NULL); if (m_pHTMLDocument != NULL) { // Disconnect current connection to HTMLDocumentEvents ConnectToConnectionPoint( SAFECAST(this, IDispatch *), DIID_HTMLDocumentEvents, FALSE, m_pHTMLDocument, &m_dwHTMLDocumentEvents, NULL); m_pHTMLDocument->Release(); } OleSetContainedObject((IUnknown *)m_pOleObject, FALSE); if (m_pHlinkFrame != NULL) m_pHlinkFrame->Release(); if (m_pOleObject != NULL) { m_pOleObject->DoVerb( OLEIVERB_HIDE, NULL, SAFECAST(this, IOleClientSite *), 0, m_hWnd, NULL); m_pOleObject->SetClientSite(NULL); m_pOleObject->Close(OLECLOSE_NOSAVE); m_pOleObject->Release(); } if (m_pWebBrowser != NULL) { m_pWebBrowser->Stop(); m_pWebBrowser->Release(); } if (m_pBindStatusCallback != NULL) EVAL(m_pBindStatusCallback->Release() == 0); if (m_hPasswordDLL != NULL) UnloadPasswordDLL(); if (m_pPIDLList != NULL) delete m_pPIDLList; if (m_pidlDefault != NULL) g_pMalloc->Free(m_pidlDefault); if (m_pUnkBrowser != NULL) m_pUnkBrowser->Release(); if (m_pSSConfig != NULL) m_pSSConfig->Release(); m_pScreenSaver->put_Running(FALSE); if (m_pScreenSaver != NULL) m_pScreenSaver->Release(); CWindow::OnDestroy(); PostQuitMessage(0); TraceMsg(TF_CLOSE, "CScreenSaverWindow::OnDestroy() END"); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnEraseBkgnd ///////////////////////////////////////////////////////////////////////////// BOOL CScreenSaverWindow::OnEraseBkgnd ( HDC hDC ) { return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnTimer ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::OnTimer ( UINT nIDTimer ) { if ( // Ignore if there is a dialog up or we are disabled. !m_bModelessEnabled || // Ignore if the user is selecting or scrolling. (GetAsyncKeyState((GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON)) & 0x8000) ) { return; } switch (nIDTimer) { case ID_CONTROLS_TIMER: { TraceMsg(TF_TIMER, "CScreenSaverWindow::OnTimer(ID_CONTROLS_TIMER)"); ShowControls(FALSE); break; } case ID_CHANNELCHANGE_TIMER: { TraceMsg(TF_TIMER, "CScreenSaverWindow::OnTimer(ID_CHANNELCHANGE_TIMER)"); OnChannelChangeTimer(); break; } case ID_CLICKCHECK_TIMER: { TraceMsg(TF_TIMER, "CScreenSaverWindow::OnTimer(ID_CLICKCHECK_TIMER)"); ASSERT(m_idClickCheckTimer != 0); ASSERT(m_bMouseClicked); EVAL(KillTimer(m_idClickCheckTimer)); m_idClickCheckTimer = 0; Quit(); break; } case ID_RESTART_TIMER: { HWND hwndTrayUI; TraceMsg(TF_TIMER, "CScreenSaverWindow::OnTimer(ID_RELOAD_TIMER)"); // Send message which will be handled in // WebCheck to restart the screen saver. if ((hwndTrayUI = FindWindow(s_szTrayUIWindow, s_szTrayUIWindow)) != NULL) { ::PostMessage(hwndTrayUI, WM_LOADSCREENSAVER, 0, 0); EVAL(KillTimer(m_idReloadTimer)); m_idReloadTimer = 0; Quit(TRUE); } break; } default: ASSERT(FALSE); } } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnUserMessage ///////////////////////////////////////////////////////////////////////////// LRESULT CScreenSaverWindow::OnUserMessage ( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch (uMsg) { case WM_ABORTNAVIGATE: return NavigateToDefault(); case WM_DEATHTOSAVER: DestroyWindow(m_hWnd); break; default: break; } return -1; } //////////////////////////////////////////////////////////////////////////// // // #define PARAM_PROCESSED 0 #define PARAM_HEADERS 1 #define PARAM_POST_DATA 2 #define PARAM_FRAME_NAME 3 #define PARAM_FLAGS 4 #define PARAM_URL 5 // // // //////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnBeforeNavigate ///////////////////////////////////////////////////////////////////////////// #define NUM_PARAM_NEWWINDOW 6 HRESULT CScreenSaverWindow::OnNewWindow ( DISPPARAMS * pDispParams, VARIANT * pVarResult ) { HRESULT hrResult; for (;;) { if (pDispParams == NULL) { hrResult = DISP_E_PARAMNOTOPTIONAL; break; } if (pDispParams->cArgs != NUM_PARAM_NEWWINDOW) { hrResult = DISP_E_BADPARAMCOUNT; break; } // Check for password. if (VerifyPassword()) { CString strNavigateURL; ASSERT(pDispParams->rgvarg[PARAM_URL].vt == VT_BSTR); strNavigateURL = pDispParams->rgvarg[PARAM_URL].bstrVal; TraceMsg(TF_NAVIGATION, "Navigate URL = '%s'\r\n", (LPCTSTR)strNavigateURL); if (LaunchBrowser(strNavigateURL)) { // Save our state and quit the Screen Saver // if we successfully launched the browser. TraceMsg(TF_CLOSE, "Attempting to close screen saver"); Quit(TRUE); } else MessageBeep(MB_ICONEXCLAMATION); } // Set the cancel flag to TRUE to disallow // shdocvw from launching a new window ASSERT(pDispParams->rgvarg[PARAM_PROCESSED].vt == (VT_BYREF | VT_BOOL)); *(pDispParams->rgvarg[PARAM_PROCESSED].pboolVal) = VARIANT_TRUE; hrResult = S_OK; break; } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnBeforeNavigate ///////////////////////////////////////////////////////////////////////////// #define NUM_PARAM_BEFORENAV 6 #define PARAM_PROCESSED 0 #define PARAM_HEADERS 1 #define PARAM_POST_DATA 2 #define PARAM_FRAME_NAME 3 #define PARAM_FLAGS 4 #define PARAM_URL 5 HRESULT CScreenSaverWindow::OnBeforeNavigate ( DISPPARAMS * pDispParams, VARIANT * pVarResult ) { HRESULT hrResult; for (;;) { if (pDispParams == NULL) { hrResult = DISP_E_PARAMNOTOPTIONAL; break; } if (pDispParams->cArgs != NUM_PARAM_BEFORENAV) { hrResult = DISP_E_BADPARAMCOUNT; break; } DWORD dwFeatureFlags; EVAL(SUCCEEDED(m_pSSConfig->get_Features(&dwFeatureFlags))); // We'll skip everything until a mouse click happens if (m_bMouseClicked && !(dwFeatureFlags & FEATURE_IGNORE_MOUSE_CLICKS)) { ASSERT(m_idClickCheckTimer != 0); EVAL(KillTimer(m_idClickCheckTimer)); m_idClickCheckTimer = 0; // Check for password. if (VerifyPassword()) { CString strNavigateURL; ASSERT(pDispParams->rgvarg[PARAM_URL].vt == VT_BSTR); strNavigateURL = pDispParams->rgvarg[PARAM_URL].bstrVal; TraceMsg(TF_NAVIGATION, "Navigate URL = '%s'\r\n", (LPCTSTR)strNavigateURL); if (LaunchBrowser(strNavigateURL)) { // Save our state and quit the Screen Saver // if we successfully launched the browser. TraceMsg(TF_CLOSE, "Attempting to close screen saver"); Quit(TRUE); } else MessageBeep(MB_ICONEXCLAMATION); } // Set the cancel flag to TRUE to disallow // navigation in the Screen Saver itself. ASSERT(pDispParams->rgvarg[PARAM_PROCESSED].vt == (VT_BYREF | VT_BOOL)); *(pDispParams->rgvarg[PARAM_PROCESSED].pboolVal) = VARIANT_TRUE; } hrResult = S_OK; break; } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnDocumentComplete ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::OnDocumentComplete ( BSTR bstrURL ) { if (m_pHTMLDocument != NULL) { // Disconnect current connection to HTMLDocumentEvents ConnectToConnectionPoint( SAFECAST(this, IDispatch *), DIID_HTMLDocumentEvents, FALSE, m_pHTMLDocument, &m_dwHTMLDocumentEvents, NULL); m_pHTMLDocument->Release(); m_pHTMLDocument = NULL; } // Connect to new document HTMLDocumentEvents connection if ( SUCCEEDED(m_pWebBrowser->get_Document(&m_pHTMLDocument)) && (m_pHTMLDocument != NULL) ) { ConnectToConnectionPoint( SAFECAST(this, IDispatch *), DIID_HTMLDocumentEvents, TRUE, m_pHTMLDocument, &m_dwHTMLDocumentEvents, NULL); } else TraceMsg(TF_NAVIGATION, "OnDocumentComplete: Unable to get_Document()!"); // Set the current URL property. SUCCEEDED(m_pScreenSaver->put_CurrentURL(bstrURL)); #ifdef _DEBUG CString strURL = bstrURL; TraceMsg(TF_NAVIGATION, "OnDocumentComplete: Current URL is \"%s\"", (LPCTSTR)strURL); #endif // _DEBUG // Hide the scrollbar and any other controls ShowControls(FALSE); // Start the channel change timer again. ResetChangeTimer(); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnTitleChange ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::OnTitleChange ( BSTR bstrTitle ) { TraceMsg(TF_FUNCENTRY, "OnTitleChange()"); CString strTitle = bstrTitle; SetWindowText(strTitle); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::CreateWebBrowser ///////////////////////////////////////////////////////////////////////////// BOOL CScreenSaverWindow::CreateWebBrowser ( const RECT & rect ) { HRESULT hrResult; ASSERT(m_hWnd); for (;;) { CLSID clsidBrowser; if ( FAILED(CLSIDFromProgID(OLESTR("Shell.Explorer"), &clsidBrowser)) || FAILED(hrResult = CoCreateInstance( clsidBrowser, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, IID_IUnknown, (void **)&m_pUnkBrowser)) ) { TraceMsg(TF_ERROR, "Failed to create Web Browser object."); break; } if (FAILED(hrResult = m_pUnkBrowser->QueryInterface(IID_IWebBrowser2, (void **)&m_pWebBrowser))) { TraceMsg(TF_ERROR, "Web browser doesn't support IWebBrowser2!"); break; } if ( FAILED(hrResult = m_pUnkBrowser->QueryInterface(IID_IOleObject, (void **)&m_pOleObject)) || FAILED(hrResult = m_pOleObject->SetClientSite(SAFECAST(this, IOleClientSite *))) ) { TraceMsg(TF_ERROR, "Failure attempting to setup IOleObject!"); break; } IPersistStreamInit * pPersistStreamInit; if (SUCCEEDED(hrResult = m_pOleObject->QueryInterface(IID_IPersistStreamInit, (void **)&pPersistStreamInit))) { pPersistStreamInit->InitNew(); pPersistStreamInit->Release(); } OleSetContainedObject((IUnknown *)m_pOleObject, TRUE); ConnectToConnectionPoint( SAFECAST(this, IDispatch *), DIID_DWebBrowserEvents, TRUE, m_pUnkBrowser, &m_dwWebBrowserEvents, NULL); ConnectToConnectionPoint( SAFECAST(this, IDispatch *), DIID_DWebBrowserEvents2, TRUE, m_pUnkBrowser, &m_dwWebBrowserEvents2, NULL); // Make sure we are known as the browser EVAL(SUCCEEDED(m_pWebBrowser->put_RegisterAsBrowser(VARIANT_TRUE))); // We don't need to handle drops in the screen saver. EVAL(SUCCEEDED(m_pWebBrowser->put_RegisterAsDropTarget(VARIANT_FALSE))); // Make sure no dialogs are displayed for error conditions. EVAL(SUCCEEDED(m_pWebBrowser->put_Silent(VARIANT_TRUE))); // Make sure we get benefits of running theater mode. // (in particular the flat scrollbar) EVAL(SUCCEEDED(m_pWebBrowser->put_TheaterMode(VARIANT_TRUE))); // Get the Target frame and don't allow, // resizing, and turn off the 3D border. ITargetEmbedding * pTargetEmbedding; if (SUCCEEDED(hrResult = m_pUnkBrowser->QueryInterface( IID_ITargetEmbedding, (void **)&pTargetEmbedding))) { ITargetFrame * pTargetFrame; // Save the ITargetFrame interface pointer. if (SUCCEEDED(hrResult = pTargetEmbedding->GetTargetFrame(&pTargetFrame))) { DWORD dwFrameOpts; if (SUCCEEDED(pTargetFrame->GetFrameOptions(&dwFrameOpts))) { dwFrameOpts |= (FRAMEOPTIONS_NORESIZE | FRAMEOPTIONS_NO3DBORDER); EVAL(SUCCEEDED(pTargetFrame->SetFrameOptions(dwFrameOpts))); } // Save the HLINK frame for navigation and setup purposes. hrResult = pTargetFrame->QueryInterface(IID_IHlinkFrame, (void **)&m_pHlinkFrame); pTargetFrame->Release(); } pTargetEmbedding->Release(); } if (FAILED(hrResult)) { TraceMsg(TF_ERROR, "Error attempting to initialize TargetEmbedding."); break; } // Make sure we are running in the current mode. DWORD dwFlags; VARIANT_BOOL bOffline = (InternetGetConnectedState(&dwFlags, 0) ? VARIANT_FALSE : VARIANT_TRUE); #ifdef _DEBUG TraceMsg(TF_NAVIGATION, "Currently %s", ((bOffline == VARIANT_TRUE) ? TEXT("OFFLINE") : TEXT("ONLINE"))); #endif // _DEBUG EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(bOffline))); m_pBindStatusCallback = new CSSNavigateBSC( SAFECAST(this, CScreenSaverWindow *), TIME_NAVIGATE_TIMEOUT); if (NULL == m_pBindStatusCallback) { hrResult = E_OUTOFMEMORY; break; } // Display the Web Browser OC. ShowWindow(SW_SHOWNORMAL); m_pOleObject->DoVerb( OLEIVERB_SHOW, NULL, SAFECAST(this, IOleClientSite *), 0, m_hWnd, &rect); break; } return SUCCEEDED(hrResult); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetHTMLBodyElement ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::GetHTMLBodyElement ( IHTMLBodyElement ** ppHTMLBodyElement ) { IDispatch * pDispatch = NULL; IHTMLDocument2 * pHTMLDocument = NULL; IHTMLElement * pHTMLElement = NULL; HRESULT hrResult; for (;;) { *ppHTMLBodyElement = NULL; if ( FAILED(m_pWebBrowser->get_Document(&pDispatch)) || (pDispatch == NULL) ) { hrResult = E_FAIL; break; } if (FAILED(hrResult = pDispatch->QueryInterface( IID_IHTMLDocument2, (void **)&pHTMLDocument))) { break; } if ( SUCCEEDED(hrResult = pHTMLDocument->get_body(&pHTMLElement)) && (pHTMLElement != NULL) ) { hrResult = pHTMLElement->QueryInterface(IID_IHTMLBodyElement, (void **)ppHTMLBodyElement); } break; } if (pHTMLElement != NULL) pHTMLElement->Release(); if (pHTMLDocument != NULL) pHTMLDocument->Release(); if (pDispatch != NULL) pDispatch->Release(); return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::DisplayCurrentChannel ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::DisplayCurrentChannel ( ) { HRESULT hrResult; if (m_lCurrChannel == CURRENT_CHANNEL_NONE) hrResult = DisplayNextChannel(); else { if (FAILED(hrResult = DisplayChannel(m_lCurrChannel))) { TraceMsg(TF_NAVIGATION, "Unable to display channel, trying next one."); hrResult = DisplayNextChannel(); } } // If everything blows up, show the default page. if (FAILED(hrResult)) { TraceMsg(TF_NAVIGATION, "No channels are able to display. Using default."); hrResult = NavigateToDefault(); } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::DisplayNextChannel ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::DisplayNextChannel ( ) { long lStartChannel = m_lCurrChannel; long lNextChannel = m_lCurrChannel; HRESULT hrResult; for (;;) { lNextChannel = FindNextChannel(lNextChannel); // Bail if we have gone all the way around the list. if (lNextChannel == lStartChannel) { TraceMsg(TF_NAVIGATION, "No new channel available...Continuing current channel."); hrResult = E_FAIL; break; } if (lNextChannel == CURRENT_CHANNEL_NONE) continue; // Continue until we loop around or have navigated successfully. if (SUCCEEDED(hrResult = DisplayChannel(lNextChannel))) break; } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::DisplayChannel ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::DisplayChannel ( long lChannel ) { LPITEMIDLIST pidlChannel = m_pPIDLList->Item(lChannel); ASSERT(pidlChannel != NULL); m_bMouseClicked = FALSE; HRESULT hrResult = NavigateToPIDL(pidlChannel); m_lCurrChannel = lChannel; return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::NavigateToPIDL ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::NavigateToPIDL ( LPITEMIDLIST pidl ) { HRESULT hrResult = E_FAIL; for (;;) { CString strURL; TCHAR * pszURL = strURL.GetBuffer(INTERNET_MAX_URL_LENGTH); BOOL bResult = GetPIDLDisplayName( NULL, pidl, pszURL, INTERNET_MAX_URL_LENGTH, SHGDN_FORPARSING); strURL.ReleaseBuffer(); if (!bResult) break; BSTR bstrURL; if ((bstrURL = strURL.AllocSysString()) != NULL) { EVAL(SUCCEEDED(hrResult = NavigateToBSTR(bstrURL))); SysFreeString(bstrURL); } break; } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::NavigateToBSTR ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::NavigateToBSTR ( BSTR bstrURL ) { IMoniker * pURLMoniker = NULL; IBindCtx * pBindCtx = NULL; IHlink * pHlink = NULL; HRESULT hrResult; for (;;) { if (bstrURL == NULL) { hrResult = E_INVALIDARG; break; } DWORD dwFeatureFlags; EVAL(SUCCEEDED(m_pSSConfig->get_Features(&dwFeatureFlags))); if (dwFeatureFlags & FEATURE_USE_CACHED_CONTENT_FIRST) { if (FAILED(hrResult = SetConnectedState(bstrURL))) break; } else { if (FAILED(hrResult = IsURLAvailable(bstrURL))) break; } if ( FAILED(hrResult = CreateURLMoniker(NULL, bstrURL, &pURLMoniker)) || FAILED(hrResult = CreateBindCtx(0, &pBindCtx)) || FAILED(hrResult = HlinkCreateFromMoniker( pURLMoniker, NULL, NULL, NULL, 0, NULL, IID_IHlink, (void **)&pHlink)) || FAILED(hrResult = m_pHlinkFrame->Navigate( HLNF_CREATENOHISTORY, pBindCtx, SAFECAST(m_pBindStatusCallback, IBindStatusCallback *), pHlink)) ) { break; } #ifdef _DEBUG VARIANT_BOOL bOffline; EVAL(SUCCEEDED(m_pWebBrowser->get_Offline(&bOffline))); CString strURL = bstrURL; TraceMsg(TF_NAVIGATION, "%s: Started navigation to '%s'", (bOffline ? TEXT("OFFLINE") : TEXT("ONLINE")), (LPCTSTR)strURL); #endif // _DEBUG break; } // Cleanup if (pHlink != NULL) pHlink->Release(); if (pBindCtx != NULL) pBindCtx->Release(); if (pURLMoniker != NULL) pURLMoniker->Release(); return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::NavigateToDefault ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::NavigateToDefault ( ) { HRESULT hrResult = E_FAIL; for (;;) { BSTR bstrCurrentURL; if ( FAILED(m_pScreenSaver->get_CurrentURL(&bstrCurrentURL)) || (bstrCurrentURL == NULL) ) { break; } CString strDefaultURL; TCHAR * pszURL = strDefaultURL.GetBuffer(INTERNET_MAX_URL_LENGTH); EVAL(GetPIDLDisplayName(NULL, m_pidlDefault, pszURL, INTERNET_MAX_URL_LENGTH, SHGDN_FORPARSING)); strDefaultURL.ReleaseBuffer(); CString strCurrentURL = bstrCurrentURL; if (StrCmpI(strCurrentURL, strDefaultURL) == 0) { ResetChangeTimer(); hrResult = S_OK; } SysFreeString(bstrCurrentURL); break; } if (FAILED(hrResult)) hrResult = NavigateToPIDL(m_pidlDefault); return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SetConnectedState ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::SetConnectedState ( BSTR bstrURL ) { if (bstrURL == NULL) return E_INVALIDARG; CString strURL = bstrURL; if ((LPTSTR)strURL == NULL) return E_OUTOFMEMORY; // Check for 'res://' URL BOOL bResURL = (StrCmpNI(strURL, s_szRES, lstrlen(s_szRES)) == 0); long lMode; EVAL(SUCCEEDED(m_pScreenSaver->get_Mode(&lMode))); HRESULT hrResult; // Check the cache for the URL first. Assume /u URLs want to hit the net. if ( (lMode != SSMODE_SINGLEURL) && // Ignore cache check for 'res://' URLs !bResURL && GetUrlCacheEntryInfoEx(strURL, NULL, NULL, NULL, NULL, NULL, 0) ) { // Go offline and use cache content. TraceMsg(TF_NAVIGATION, "Going offline"); EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(VARIANT_TRUE))); hrResult = S_OK; } else { DWORD dwConnectState; // Try the internet if we have a direct connection. Ignore dialup. if ( InternetGetConnectedState(&dwConnectState, 0) && ( (dwConnectState & INTERNET_CONNECTION_LAN) || (dwConnectState & INTERNET_CONNECTION_PROXY) ) ) { if (!bResURL) { TraceMsg( TF_NAVIGATION, "Content for '%s' not in cache! Going online", (LPCTSTR)strURL); EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(VARIANT_FALSE))); } else { TraceMsg(TF_NAVIGATION, "Going offline for res:// URL"); // Go offline for res:// URLs they should be local. EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(VARIANT_TRUE))); } hrResult = S_OK; } else hrResult = E_FAIL; } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::IsURLAvailable ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::IsURLAvailable ( BSTR bstrURL ) { if (bstrURL == NULL) return E_INVALIDARG; CString strURL = bstrURL; if ((LPTSTR)strURL == NULL) return E_OUTOFMEMORY; HRESULT hrResult = S_OK; for (;;) { // Ignore cache check for 'res://' URLs if (StrCmpNI(strURL, s_szRES, lstrlen(s_szRES)) == 0) break; long lMode; EVAL(SUCCEEDED(m_pScreenSaver->get_Mode(&lMode))); DWORD dwConnectState; if ( // Assume /u URLs want to hit the net. (lMode == SSMODE_SINGLEURL) || // If we are online it should be available, too. InternetGetConnectedState(&dwConnectState, 0) ) { TraceMsg(TF_NAVIGATION, "Going ONLINE for internet content"); EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(VARIANT_FALSE))); break; } // Check the cache for the URL if it is there, go offline. if (GetUrlCacheEntryInfoEx(strURL, NULL, NULL, NULL, NULL, NULL, 0)) { TraceMsg(TF_NAVIGATION, "Going OFFLINE for cached content"); EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(VARIANT_TRUE))); break; } hrResult = E_FAIL; break; } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::ResetChangeTimer ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::ResetChangeTimer ( BOOL bExtendedTime ) { if (m_idChangeTimer != 0) { EVAL(KillTimer(m_idChangeTimer)); m_idChangeTimer = 0; } int iChannelTime; EVAL(SUCCEEDED(m_pSSConfig->get_ChannelTime(&iChannelTime))); EVAL((m_idChangeTimer = SetTimer( ID_CHANNELCHANGE_TIMER, (iChannelTime * 1000) + (bExtendedTime ? TIME_NAVIGATE_TIMEOUT : 0), NULL)) != 0); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::FindNextChannel ///////////////////////////////////////////////////////////////////////////// long CScreenSaverWindow::FindNextChannel ( long lChannelStart ) { if (m_pPIDLList->Count() > 0) { if (lChannelStart == CURRENT_CHANNEL_NONE) lChannelStart = 0; else { lChannelStart++; if (lChannelStart >= m_pPIDLList->Count()) lChannelStart = CURRENT_CHANNEL_NONE; } } return lChannelStart; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::LaunchBrowser ///////////////////////////////////////////////////////////////////////////// BOOL CScreenSaverWindow::LaunchBrowser ( CString & strURL ) { BOOL bResult = FALSE; for (;;) { PARSEDURL pu = { 0 }; pu.cbSize = sizeof(PARSEDURL); if (FAILED(ParseURL(strURL, &pu))) break; if ( (pu.nScheme == URL_SCHEME_INVALID) || (pu.nScheme == URL_SCHEME_UNKNOWN) || (pu.nScheme == URL_SCHEME_VBSCRIPT) || (pu.nScheme == URL_SCHEME_JAVASCRIPT) ) { // Don't allow navigation to scripts. // They may need page context. TraceMsg(TF_NAVIGATION, "Ignoring %s -- Can't launch", (LPCTSTR)strURL); break; } // // If we are running on NT and password protection is enabled then // we disable launching browsers. This is because there is no way // to detect on the other side that the password verification succeeded // if (g_bPlatformNT && g_bPasswordEnabled) { bResult = TRUE; break; } if (pu.nScheme == URL_SCHEME_FILE) { // Make sure that URL is completely escaped. char * szURL = strURL.GetBuffer(INTERNET_MAX_URL_LENGTH); DWORD cchSize = INTERNET_MAX_URL_LENGTH; UrlEscape(szURL, szURL, &cchSize, 0); strURL.ReleaseBuffer(); } if (g_bPlatformNT) { // Write URL to registry and trigger event. WriteRegValue( HKEY_CURRENT_USER, g_szRegSubKey, s_szRegLastNavURL, REG_SZ, (LPBYTE)(char *)strURL, strURL.GetLength()); HANDLE hTermEvent; if ((hTermEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, s_szSETermEvent)) != NULL) { bResult = SetEvent(hTermEvent); CloseHandle(hTermEvent); } } else { BSTR bstrURL = strURL.AllocSysString(); if (bstrURL != NULL) { bResult = SUCCEEDED(HlinkNavigateString(NULL, bstrURL)); SysFreeString(bstrURL); } } break; } return bResult; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::UserIsInteractive ///////////////////////////////////////////////////////////////////////////// BOOL CScreenSaverWindow::UserIsInteractive ( ) { if (g_bPlatformNT) return TRUE; // REVIEW: This is a big hack. We need to // find a better way to do this [jaym] HWND hwndCurr = ::GetWindow(m_hWnd, GW_HWNDFIRST); while (hwndCurr != NULL) { if (::GetWindowTextLength(hwndCurr) > 0) { TCHAR szWindowText[40]; ::GetWindowText(hwndCurr, szWindowText, ARRAYSIZE(szWindowText)); TraceMsg(TF_ALWAYS, "Window '%s'", szWindowText); if (StrCmpI(szWindowText, TEXT("DDE Server Window")) == 0) return TRUE; } hwndCurr = ::GetWindow(hwndCurr, GW_HWNDNEXT); } TraceMsg(TF_ALWAYS, "USER IS NOT INTERACTIVE!"); return FALSE; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnChannelChangeTimer ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::OnChannelChangeTimer ( ) { ASSERT(m_idChangeTimer != 0); EVAL(KillTimer(m_idChangeTimer)); m_idChangeTimer = 0; if (FAILED(DisplayNextChannel())) ResetChangeTimer(); else { // Just in case we don't get OnDocumentComplete()... ResetChangeTimer(TRUE); } } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::VerifyPassword ///////////////////////////////////////////////////////////////////////////// BOOL CScreenSaverWindow::VerifyPassword ( ) { BOOL fOK = FALSE; // Check to see if we are already in here. If m_lVerifyingPassword // is zero on entry then it will be set to 1 and the return from // InterlockedExchange will be 0. When we are done we call // InterlockedExchange to reset the value to 0. if (InterlockedExchange(&m_lVerifingPassword, TRUE) == FALSE) { EnableModeless(FALSE); if (g_bPlatformNT) { // REVIEW: Verify password for NT users. Or, alternatively // figure out how to lock the workstation before the screensaver // activates. // LogonUser fOK = TRUE; } else { // Also disable the browser window HWND hBrowserWnd = NULL; ASSERT(m_pWebBrowser); if(m_pWebBrowser) { IOleWindow *pOleWindow = NULL; if(SUCCEEDED(m_pWebBrowser->QueryInterface(IID_IOleWindow, (void**)&pOleWindow))) { ASSERT(pOleWindow); pOleWindow->GetWindow(&hBrowserWnd); pOleWindow->Release(); } } if (m_pfnVerifyPassword != NULL) fOK = m_pfnVerifyPassword(hBrowserWnd ? hBrowserWnd : m_hWnd); else { // Passwords disabled or unable to load // handler DLL always allow exit. fOK = TRUE; } } EnableModeless(TRUE); InterlockedExchange(&m_lVerifingPassword, FALSE); } return fOK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::InitChannelList ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::InitChannelList ( ) { if (m_pPIDLList == NULL) m_pPIDLList = new CPIDLList; if (m_pPIDLList == NULL) return; if (UserIsInteractive()) { long lMode; EVAL(SUCCEEDED(m_pScreenSaver->get_Mode(&lMode))); if (lMode == SSMODE_SINGLEURL) { BSTR bstrURL; if ( SUCCEEDED(m_pScreenSaver->get_CurrentURL(&bstrURL)) && (bstrURL != NULL) && (SysStringLen(bstrURL) != 0) ) { CString strURL = bstrURL; m_pPIDLList->Add(strURL); } SysFreeString(bstrURL); } else { DWORD dwFeatureFlags; EVAL(SUCCEEDED(m_pSSConfig->get_Features(&dwFeatureFlags))); m_pPIDLList->Build(m_pSSConfig, (dwFeatureFlags & FEATURE_USE_CDF_TOPLEVEL_URL)); } } else TraceMsg(TF_WARNING, "USER IS NOT LOGGED ON!"); // If there are no current Screen Saver channels, show the // info. HTML message about setting up Screen Saver channels. if (m_pPIDLList->Count() == 0) { TraceMsg(TF_NAVIGATION, "No URLs in list -- adding default HTML"); EVAL(m_pPIDLList->Add(CopyPIDL(m_pidlDefault))); } else { ASSERT(m_pPIDLList->Count() > 0); LoadState(); } TraceMsg(TF_NAVIGATION, "%d URLs in list", m_pPIDLList->Count()); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::LoadState ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::LoadState ( ) { CString strLastURL; ASSERT(m_pPIDLList != NULL); if (m_pPIDLList->Count() > 0) { char * pszLastURL = strLastURL.GetBuffer(INTERNET_MAX_URL_LENGTH); ReadRegString( HKEY_CURRENT_USER, g_szRegSubKey, s_szRegLastURL, TEXT(""), pszLastURL, INTERNET_MAX_URL_LENGTH); strLastURL.ReleaseBuffer(); if (strLastURL.GetLength() > 0) { LPITEMIDLIST pidl; if (CreatePIDLFromPath(strLastURL, &pidl) && pidl) { m_lCurrChannel = m_pPIDLList->Find(pidl); g_pMalloc->Free(pidl); } } } } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SaveState ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::SaveState ( ) { CString strLastURL; // Save the current URL being displayed. if ( (m_pPIDLList != NULL) && (m_lCurrChannel != CURRENT_CHANNEL_NONE) ) { LPITEMIDLIST pidl = m_pPIDLList->Item(m_lCurrChannel); char * pszLastURL = strLastURL.GetBuffer(INTERNET_MAX_URL_LENGTH); EVAL(GetPIDLDisplayName(NULL, pidl, pszLastURL, INTERNET_MAX_URL_LENGTH, SHGDN_FORPARSING)); strLastURL.ReleaseBuffer(); } WriteRegValue( HKEY_CURRENT_USER, g_szRegSubKey, s_szRegLastURL, REG_SZ, (LPBYTE)(char *)strLastURL, strLastURL.GetLength()); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::LoadPasswordDLL ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::LoadPasswordDLL ( ) { if (m_hPasswordDLL != NULL) UnloadPasswordDLL(); // Look to see if password turned on, otherwise // don't bother to load password handler DLL. if (g_bPasswordEnabled) { // Try to load the DLL that contains password proc. if ((m_hPasswordDLL = LoadLibrary(s_szPasswordDLL)) != NULL) { m_pfnVerifyPassword = (VERIFYPWDPROC)GetProcAddress( m_hPasswordDLL, s_szPasswordFnName); if (m_pfnVerifyPassword == NULL) UnloadPasswordDLL(); } } } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::UnloadPasswordDLL ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::UnloadPasswordDLL ( ) { if (m_hPasswordDLL != NULL) { FreeLibrary(m_hPasswordDLL); m_hPasswordDLL = NULL; m_pfnVerifyPassword = NULL; } } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SetHooks ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::SetHooks ( ) { ASSERT(s_hKeyboardHook == NULL); ASSERT(s_hMouseHook == NULL); s_hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD, KeyboardHookProc, _pModule->GetModuleInstance(), GetCurrentThreadId()); s_hMouseHook = SetWindowsHookEx( WH_MOUSE, MouseHookProc, _pModule->GetModuleInstance(), GetCurrentThreadId()); ASSERT(s_hKeyboardHook != NULL); ASSERT(s_hMouseHook != NULL); } ///////////////////////////////////////////////////////////////////////////// // KeyboardHookProc ///////////////////////////////////////////////////////////////////////////// LRESULT CALLBACK KeyboardHookProc ( int nCode, WPARAM wParam, LPARAM lParam ) { if ( (nCode != HC_NOREMOVE) && (s_pThis->ModelessEnabled()) ) { // Make sure the user is keyboarding in the Screen Saver. if (s_pThis->m_hWnd != GetForegroundWindow()) { // Ignore ; } else { switch (wParam) { // Ignore if the user is pressing ALT case VK_MENU: // Ignore IMM messages (just in case!) case VK_PROCESSKEY: break; // Check for scrolling case VK_PRIOR: case VK_NEXT: case VK_END: case VK_HOME: case VK_LEFT: case VK_UP: case VK_RIGHT: case VK_DOWN: { static BOOL bUp = TRUE; if (bUp) s_pThis->ShowControls(TRUE); bUp = !bUp; break; } // Hotkey to go to next channel. case VK_ADD: { s_pThis->OnChannelChangeTimer(); break; } default: { // Ignore F-keys for easier debugging. if ((wParam >= VK_F1) && (wParam <= VK_F12)) { DWORD dwFeatureFlags; s_pThis->GetFeatures(&dwFeatureFlags); if (dwFeatureFlags & FEATURE_IGNORE_FKEYS) break; } s_pThis->Quit(); break; } } } } return CallNextHookEx(s_hKeyboardHook, nCode, wParam, lParam); } ///////////////////////////////////////////////////////////////////////////// // MouseHookProc ///////////////////////////////////////////////////////////////////////////// LRESULT CALLBACK MouseHookProc ( int nCode, WPARAM wParam, LPARAM lParam ) { if ( (nCode != HC_NOREMOVE) && (s_pThis->ModelessEnabled()) && // Make sure the user is mousing in the Screen Saver window. (s_pThis->m_hWnd == GetForegroundWindow()) ) { switch (wParam) { case WM_NCRBUTTONDOWN: case WM_RBUTTONDOWN: case WM_NCMBUTTONDOWN: case WM_MBUTTONDOWN: { DWORD dwFeatureFlags; s_pThis->GetFeatures(&dwFeatureFlags); if (!(dwFeatureFlags & FEATURE_IGNORE_MOUSE_CLICKS)) s_pThis->Quit(); break; } case WM_MOUSEMOVE: { static BOOL bMouseMoved = FALSE; static POINT ptLast; TraceMsg(TF_ALWAYS, "MouseHookProc(WM_MOUSEMOVE)"); // Check to see if the mouse pointer really moved. if (!bMouseMoved) { GetCursorPos(&ptLast); bMouseMoved = TRUE; } else { POINT ptCursor; POINT ptCheck; GetCursorPos(&ptCheck); if (ptCursor.x = ptCheck.x - ptLast.x) { if (ptCursor.x < 0) ptCursor.x *= -1; } if (ptCursor.y = ptCheck.y - ptLast.y) { if (ptCursor.y < 0) ptCursor.y *= -1; } if ((ptCursor.x + ptCursor.y) > MOUSEMOVE_THRESHOLD) { // Make sure the user is pressing ALT // if we are in ALT+mouse mode. if ( s_pThis->ALTMouseMode() && !(GetAsyncKeyState(VK_MENU) & 0x8000) ) { s_pThis->Quit(); } else { // Display the scrollbar while the // user is moving the mouse pointer s_pThis->ShowControls(TRUE); } ptLast = ptCheck; } } break; } default: break; } } return CallNextHookEx(s_hMouseHook, nCode, wParam, lParam); } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::ReleaseHooks ///////////////////////////////////////////////////////////////////////////// void CScreenSaverWindow::ReleaseHooks ( ) { if (s_hKeyboardHook != NULL) { EVAL(UnhookWindowsHookEx(s_hKeyboardHook)); s_hKeyboardHook = NULL; } if (s_hMouseHook != NULL) { EVAL(UnhookWindowsHookEx(s_hMouseHook)); s_hMouseHook = NULL; } } ///////////////////////////////////////////////////////////////////////////// // Interfaces ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // IUnknown interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::AddRef ///////////////////////////////////////////////////////////////////////////// ULONG CScreenSaverWindow::AddRef ( ) { m_cRef++; TraceMsg(TF_DEBUGREFCOUNT, "CScreenSaverWindow::AddRef, m_cRef = %d", m_cRef); return m_cRef; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::Release ///////////////////////////////////////////////////////////////////////////// ULONG CScreenSaverWindow::Release ( ) { m_cRef--; TraceMsg(TF_DEBUGREFCOUNT, "CScreenSaverWindow::Release, m_cRef = %d", m_cRef); if (m_cRef < 0) { ASSERT(FALSE); return 0; } return m_cRef; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::QueryInterface ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::QueryInterface ( REFIID riid, LPVOID * ppvObj ) { IUnknown * pUnk; *ppvObj = NULL; if (InlineIsEqualGUID(riid, IID_IUnknown)) pUnk = SAFECAST(this, IDispatch *); #if 0 else if (InlineIsEqualGUID(riid, IID_IServiceProvider)) pUnk = SAFECAST(this, IServiceProvider *); #endif else if (InlineIsEqualGUID(riid, IID_IOleClientSite)) pUnk = SAFECAST(this, IOleClientSite *); else if (InlineIsEqualGUID(riid, IID_IOleInPlaceSite)) pUnk = SAFECAST(this, IOleInPlaceSite *); else if (InlineIsEqualGUID(riid, IID_IOleInPlaceFrame)) pUnk = SAFECAST(this, IOleInPlaceFrame *); else if (InlineIsEqualGUID(riid, IID_IOleContainer)) pUnk = SAFECAST(this , IOleContainer *); else if (InlineIsEqualGUID(riid, IID_IOleCommandTarget)) pUnk = SAFECAST(this, IOleCommandTarget *); else if (InlineIsEqualGUID(riid, IID_IBindStatusCallback)) pUnk = SAFECAST(m_pBindStatusCallback, IBindStatusCallback *); else if ( InlineIsEqualGUID(riid, IID_IDispatch) || InlineIsEqualGUID(riid, DIID_DWebBrowserEvents) || InlineIsEqualGUID(riid, DIID_HTMLDocumentEvents) ) { pUnk = SAFECAST(this, IDispatch *); } else { #ifdef _DEBUG TCHAR szName[128]; TraceMsg( TF_DEBUGQI, "CScreenSaverWindow::QueryInterface(%s) -- FAILED", DebugIIDName(riid, szName)); #endif // _DEBUG return E_NOINTERFACE; } pUnk->AddRef(); *ppvObj = (void *)pUnk; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // IServiceProvider interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::QueryService ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::QueryService ( REFGUID guidService, REFIID riid, void ** ppvObj ) { IUnknown * pUnk; HRESULT hrResult = S_OK; *ppvObj = NULL; if (InlineIsEqualGUID(guidService, SID_STopLevelBrowser)) { if (InlineIsEqualGUID(riid, IID_IServiceProvider)) pUnk = SAFECAST(this, IServiceProvider *); else if (InlineIsEqualGUID(riid, IID_IOleCommandTarget)) pUnk = SAFECAST(this, IOleCommandTarget *); else hrResult = E_NOINTERFACE; } else if (InlineIsEqualGUID(guidService, IID_IHlinkFrame)) { if (InlineIsEqualGUID(riid, IID_IBindStatusCallback)) pUnk = SAFECAST(m_pBindStatusCallback, IBindStatusCallback *); } else hrResult = E_NOINTERFACE; if (SUCCEEDED(hrResult)) { pUnk->AddRef(); *ppvObj = (void *)pUnk; } #ifdef _DEBUG else { TCHAR szServiceName[128]; DebugCLSIDName(guidService, szServiceName); TCHAR szRIIDName[128]; DebugCLSIDName(riid, szRIIDName); TraceMsg( TF_DEBUGQS, "CScreenSaverWindow::QueryService(%s, %s) - FAILED", szServiceName, szRIIDName); } #endif // _DEBUG return hrResult; } ///////////////////////////////////////////////////////////////////////////// // IOleClientSite interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SaveObject ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::SaveObject ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::SaveObject()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetMoniker ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::GetMoniker ( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker ** ppmk ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::GetMoniker()"); return E_INVALIDARG; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetContainer ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::GetContainer ( IOleContainer ** ppContainer ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::GetContainer()"); *ppContainer = SAFECAST(this, IOleContainer *); (*ppContainer)->AddRef(); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::ShowObject ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::ShowObject ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::ShowObject()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnShowWindow ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::OnShowWindow ( BOOL fShow ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::OnShowWindow()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::RequestNewObjectLayout ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::RequestNewObjectLayout ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::RequestNewObjectLayout()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // IOleWindow interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetWindow ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::GetWindow ( HWND * phWnd ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::GetWindow()"); ASSERT(m_hWnd != NULL); *phWnd = m_hWnd; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::ContextSensitiveHelp ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::ContextSensitiveHelp ( BOOL fEnterMode ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::ContextSensitiveHelp()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // IOleInPlaceSite ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::CanInPlaceActivate ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::CanInPlaceActivate ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::CanInPlaceActivate()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnInPlaceActivate ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::OnInPlaceActivate ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::OnInPlaceActivate()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnUIActivate ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::OnUIActivate ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::OnUIActivate()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetWindowContext ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::GetWindowContext ( IOleInPlaceFrame ** ppFrame, IOleInPlaceUIWindow ** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::GetWindowContext()"); *ppFrame = (IOleInPlaceFrame *)this; (*ppFrame)->AddRef(); // NULL means same ptr as ppFrame. *ppDoc = NULL; GetClientRect(lprcClipRect); *lprcPosRect = *lprcClipRect; lpFrameInfo->cb = sizeof(OLEINPLACEFRAMEINFO); lpFrameInfo->fMDIApp = FALSE; lpFrameInfo->hwndFrame = m_hWnd; lpFrameInfo->haccel = 0; lpFrameInfo->cAccelEntries = 0; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::Scroll ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::Scroll ( SIZE scrollExtent ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::Scroll()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnUIDeactivate ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::OnUIDeactivate ( BOOL fUndoable ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::OnUIDeactivate()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnInPlaceDeactivate ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::OnInPlaceDeactivate ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::OnInPlaceDeactivate()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::DiscardUndoState ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::DiscardUndoState ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::DiscardUndoState()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::DeactivateAndUndo ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::DeactivateAndUndo ( ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::DeactivateAndUndo()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnPosRectChange ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::OnPosRectChange ( LPCRECT lprcPosRect ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::OnPosRectChange()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // IOleInPlaceUIWindow interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetBorder ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::GetBorder ( LPRECT lprectBorder ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::GetBorder()"); GetClientRect(lprectBorder); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::RequestBorderSpace ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::RequestBorderSpace ( LPCBORDERWIDTHS pbw ) { RECT rcClient; HRESULT hres = S_OK; TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::RequestBorderSpace()"); GetClientRect(&rcClient); if (pbw->left + pbw->right > rcClient.right/2) hres = INPLACE_E_NOTOOLSPACE; else if (pbw->top + pbw->bottom > rcClient.bottom/2) hres = INPLACE_E_NOTOOLSPACE; return hres; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SetBorderSpace ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::SetBorderSpace ( LPCBORDERWIDTHS pbw ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::SetBorderSpace()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SetActiveObject ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::SetActiveObject ( IOleInPlaceActiveObject * pActiveObject, LPCOLESTR pszObjName ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::SetActiveObject()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // IOleInPlaceFrame interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::InsertMenus ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::InsertMenus ( HMENU hmenuShared, LPOLEMENUGROUPWIDTHS lpMenuWidths ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::InsertMenus()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SetMenu ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::SetMenu ( HMENU hmenuShared, HOLEMENU holemenu, HWND hwndActiveObject ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::SetMenu()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::RemoveMenus ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::RemoveMenus ( HMENU hmenuShared ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::RemoveMenus()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::SetStatusText ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::SetStatusText ( LPCOLESTR pszStatusText ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::SetStatusText()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::EnableModeless ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::EnableModeless ( BOOL fEnable ) { #ifdef _DEBUG TraceMsg( TF_FUNCENTRY, "CScreenSaverWindow::EnableModeless(%s)\r\n", (fEnable ? TEXT("TRUE") : TEXT("FALSE"))); #endif // _DEBUG m_bModelessEnabled = fEnable; EnableWindow(m_bModelessEnabled); if ( (m_pToolbar != NULL) && IsWindow(m_pToolbar->m_hWnd) ) { m_pToolbar->EnableWindow(m_bModelessEnabled); } return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::TranslateAccelerator ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::TranslateAccelerator ( LPMSG lpmsg, WORD wID ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::TranslateAccelerator()"); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // IOleContainer interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::ParseDisplayName ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::ParseDisplayName ( IBindCtx * pbc, LPOLESTR pszDisplayName, ULONG * pchEaten, IMoniker ** ppmkOut ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::ParseDisplayName()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::EnumObjects ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::EnumObjects ( DWORD grfFlags, IEnumUnknown ** ppenum ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::EnumObjects()"); return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::LockContainer ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::LockContainer ( BOOL fLock ) { TraceMsg(TF_FUNCENTRY, "CScreenSaverWindow::LockContianer(%d)", fLock); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // IOleCommandTarget interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::QueryStatus ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::QueryStatus ( const GUID * pguidCmdGroup, ULONG cCmds, OLECMD prgCmds[], OLECMDTEXT * pCmdText ) { if (prgCmds == NULL) return E_POINTER; return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::Exec ///////////////////////////////////////////////////////////////////////////// HRESULT CScreenSaverWindow::Exec ( const GUID * pguidCmdGroup, DWORD nCmdID, DWORD nCmdExecOpt, VARIANTARG * pvaIn, VARIANTARG * pvaOut ) { if (pguidCmdGroup == NULL) return OLECMDERR_E_NOTSUPPORTED; if (!InlineIsEqualGUID(*pguidCmdGroup, CGID_ShellDocView)) return OLECMDERR_E_UNKNOWNGROUP; HRESULT hrResult; switch (nCmdID) { case SHDVID_GETTRANSITION: { // Make sure the feature is enabled DWORD dwFeatureFlags; EVAL(SUCCEEDED(m_pSSConfig->get_Features(&dwFeatureFlags))); if (!(dwFeatureFlags & FEATURE_DEFAULT_TRANSITIONS)) { hrResult = OLECMDERR_E_NOTSUPPORTED; break; } switch (nCmdExecOpt) { case OLECMDEXECOPT_DODEFAULT: { // Validate In/Out args. if ((pvaIn == NULL) || (pvaOut == NULL)) return E_UNEXPECTED; V_VT(&pvaOut[0]) = VT_I4; V_I4(&pvaOut[0]) = 0; V_VT(&pvaOut[1]) = VT_BSTR; V_BSTR(&pvaOut[1]) = SysAllocString(s_szDefTransition); if (NULL == V_BSTR(&pvaOut[1])) hrResult = E_OUTOFMEMORY; else hrResult = S_OK; break; } case OLECMDEXECOPT_SHOWHELP: { hrResult = OLECMDERR_E_NOHELP; break; } default: { hrResult = OLECMDERR_E_NOTSUPPORTED; break; } } break; } default: { hrResult = OLECMDERR_E_NOTSUPPORTED; break; } } return hrResult; } ///////////////////////////////////////////////////////////////////////////// // IDispatch interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetTypeInfoCount ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::GetTypeInfoCount ( UINT * pctInfo ) { *pctInfo = NULL; return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetTypeInfo ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::GetTypeInfo ( UINT itinfo, LCID lcid, ITypeInfo ** pptInfo ) { *pptInfo = NULL; return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::GetIDsOfNames ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::GetIDsOfNames ( REFIID riid, OLECHAR ** rgszNames, UINT cNames, LCID lcid, DISPID * rgDispID ) { *rgszNames = NULL; *rgDispID = NULL; return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::Invoke ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP CScreenSaverWindow::Invoke ( DISPID dispIDMember, REFIID riid, LCID lcid, unsigned short wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr) { VARIANT varResult; HRESULT hrResult = S_OK; for (;;) { if (!InlineIsEqualGUID(riid, IID_NULL)) { hrResult = E_INVALIDARG; break; } // We don't handle the return value of any events if // events have them. We should, however, initialize an // empty return value just so it's not garbage. if (pVarResult == NULL) pVarResult = &varResult; VariantInit(pVarResult); V_VT(pVarResult) = VT_EMPTY; // Only method and get calls are valid. if (wFlags & ~(DISPATCH_METHOD | DISPATCH_PROPERTYGET)) { hrResult = DISP_E_MEMBERNOTFOUND; break; } // Process the event by looking for dispIDMember in the // list maintained in the tenant that maps event IDs to // actions. If we find the ID, then we execute the action, // otherwise we do nothing. switch (dispIDMember) { case DISPID_AMBIENT_DLCONTROL: { TraceMsg(TF_NAVIGATION, "NAV: Returning DLCTL ambient"); VARIANT_BOOL bPlaySounds; EVAL(SUCCEEDED(m_pSSConfig->get_PlaySounds(&bPlaySounds))); VARIANT_BOOL bOffline; EVAL(SUCCEEDED(m_pWebBrowser->get_Offline(&bOffline))); V_VT(pVarResult) = VT_I4; V_I4(pVarResult) = DLCTL_SILENT | ((bOffline == VARIANT_TRUE) ? DLCTL_OFFLINE : 0) | DLCTL_DLIMAGES | DLCTL_VIDEOS | ((bPlaySounds == VARIANT_TRUE) ? DLCTL_BGSOUNDS : 0); break; } case DISPID_BEFORENAVIGATE: case DISPID_FRAMEBEFORENAVIGATE: { TraceMsg(TF_NAVIGATION, "NAV: OnBeforeNavigate(Frame = %d)", (dispIDMember == DISPID_FRAMEBEFORENAVIGATE)); m_bScrollbarVisible = TRUE; hrResult = OnBeforeNavigate(pDispParams, pVarResult); break; } case DISPID_NEWWINDOW: case DISPID_FRAMENEWWINDOW: { TraceMsg(TF_NAVIGATION, "NAV: OnNewWindow(Frame = %d)", (dispIDMember == DISPID_FRAMEBEFORENAVIGATE)); m_bScrollbarVisible = TRUE; hrResult = OnNewWindow(pDispParams, pVarResult); break; } case DISPID_DOCUMENTCOMPLETE: { TraceMsg(TF_NAVIGATION, "NAV: DocumentComplete()"); if (pDispParams == NULL) { hrResult = DISP_E_PARAMNOTOPTIONAL; break; } ASSERT(V_VT(&pDispParams->rgvarg[0]) == (VT_VARIANT | VT_BYREF)); ASSERT(V_VT(V_VARIANTREF(&pDispParams->rgvarg[0])) == VT_BSTR); OnDocumentComplete(V_BSTR(V_VARIANTREF(&pDispParams->rgvarg[0]))); break; } case DISPID_TITLECHANGE: { if (pDispParams == NULL) { hrResult = DISP_E_PARAMNOTOPTIONAL; break; } if (pDispParams->cArgs != 1) { hrResult = DISP_E_BADPARAMCOUNT; break; } ASSERT(V_VT(&pDispParams->rgvarg[0]) == VT_BSTR); hrResult = OnTitleChange(V_BSTR(&pDispParams->rgvarg[0])); break; } case DISPID_HTMLDOCUMENTEVENTS_ONCLICK: { DWORD dwFeatureFlags; EVAL(SUCCEEDED(m_pSSConfig->get_Features(&dwFeatureFlags))); if (!(dwFeatureFlags & FEATURE_IGNORE_MOUSE_CLICKS)) { m_bMouseClicked = TRUE; // Kill the current click check timer and restart if needed. if (m_idClickCheckTimer != 0) { EVAL(KillTimer(m_idClickCheckTimer)); m_idClickCheckTimer = 0; } EVAL((m_idClickCheckTimer = SetTimer( ID_CLICKCHECK_TIMER, TIME_CLICKCHECK_TIMEOUT, NULL)) != 0); } break; } default: hrResult = DISP_E_MEMBERNOTFOUND; break; } break; } return hrResult; } #if 0 // Darrenmi will wire this into the IOleCommandTarget interface ///////////////////////////////////////////////////////////////////////////// // INotificationSink interface ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CScreenSaverWindow::OnNotification ///////////////////////////////////////////////////////////////////////////// STDMETHODIMP THIS_CLASS::OnNotification ( LPNOTIFICATION pNotification, LPNOTIFICATIONREPORT pNotfctnReport, DWORD dwReserved ) { ASSERT(pNotification != NULL); TraceMsg(TF_NOTIFY, "OnNotification()"); NOTIFICATIONTYPE nt; if (SUCCEEDED(pNotification->GetNotificationInfo( &nt, NULL, NULL, NULL, 0))) { if (InlineIsEqualGUID(nt, NOTIFICATIONTYPE_INET_OFFLINE)) { TraceMsg(TF_NOTIFY, "Going OFFLINE"); EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(VARIANT_TRUE))); } else if (InlineIsEqualGUID(nt, NOTIFICATIONTYPE_INET_ONLINE)) { TraceMsg(TF_NOTIFY, "Going ONLINE"); EVAL(SUCCEEDED(m_pWebBrowser->put_Offline(VARIANT_FALSE))); } else ASSERT(FALSE); } else ASSERT(FALSE); return S_OK; } #endif
#include <iostream> #include <string> #include <vector> #include <stdio.h> #include <fstream> // #include <IEGA/string_manip.hpp> #include "gstd.hpp" #include <sstream> #include <bitset> #include <map> #include <cmath> #include <ctgmath> //CXCOMPILE make #define NUM_WORD 8 #define COUT_ERROR cout << "ERROR [f='" << readfile << "'][L=" << to_string(line_num) << "]: " using namespace gstd; using namespace std; #define FLAG_X 'X' #define FLAG_SET 'S' #define FLAG_CLR 'C' typedef struct{ string name; int instruction_no; int data_bits; char flag; map <int, map<int, map<int, bool> > > ctrls; }operation; typedef struct{ string name; int word; int pin; bool active_low; bool default_to_on; }control_line; /* Clears the operation's data fields */ void clear_operation(operation& x){ x.name = ""; x.instruction_no = -1; x.data_bits = -1; x.ctrls.clear(); } /* Finds the control line at pin X word Y and returns its default value. True indicates default = ON, False indicates default = OFF. If no control is found, retuns val_not_found value. */ bool get_control_default(std::vector<control_line> controls, int word, int pin, bool val_not_found=false){ for (size_t c = 0 ; c < controls.size() ; c++){ if (controls[c].word == word && controls[c].pin == pin){ return controls[c].default_to_on; } } return val_not_found; } /* Finds the control line at pin X word Y and returns its active low setting. True indicates it IS active low, false indicates it is not. If no control is found, retuns val_not_found value. */ bool get_active_low(std::vector<control_line> controls, int word, int pin, bool val_not_found=false){ for (size_t c = 0 ; c < controls.size() ; c++){ if (controls[c].word == word && controls[c].pin == pin){ return controls[c].active_low; } } return val_not_found; } /* */ void fill_defaults(operation& nextOp, std::vector<control_line>& controls){ map<int, map<int, map<int, bool> > >::iterator phase_it; map<int, map<int, bool> >::iterator word_it; map<int, bool>::iterator pin_it; //For each phase for (phase_it = nextOp.ctrls.begin() ; phase_it != nextOp.ctrls.end() ; phase_it++){ //For each word // for (word_it = phase_it->second.begin() ; word_it != phase_it->second.end() ; word_it++){ for (int word = 0 ; word < NUM_WORD ; word++){ if (nextOp.ctrls[phase_it->first].find(word) == nextOp.ctrls[phase_it->first].end()){ map<int, bool> temp_map; nextOp.ctrls[phase_it->first][word] = temp_map; } //For each pin for (int p = 0 ; p < 8 ; p++){ //If not listed, add default value // if (word_it->second.find(p) == word_it->second.end()){ //Pin not listed, take value from defaults // nextOp.ctrls[phase_it->first][word_it->first][p] = get_control_default(controls, word_it->first, p); // } if (nextOp.ctrls[phase_it->first][word].find(p) == nextOp.ctrls[phase_it->first][word].end()){ //Pin not listed, take value from defaults nextOp.ctrls[phase_it->first][word][p] = get_control_default(controls, word, p); } } } } } /* Accepts a control line name and a list of controls and sets the control line's word and pin in the variables word and pin. Returns true if found. */ bool get_word_pin(std::string ctrl_line, std::vector<control_line> controls, int& word, int& pin){ std::map<int, std::map<int, bool> > intMap; for (size_t i = 0 ; i < controls.size() ; i++){ if (controls[i].name == ctrl_line){ word = controls[i].word; pin = controls[i].pin; return true; } } return false; } bool read_CW(string readfile, std::vector<control_line>& controls){ controls.clear(); map<std::string, operation> ops; vector<string> words; size_t line_num = 0; //read through file ifstream file(readfile.c_str()); if (file.is_open()) { string line; control_line nextCtrl; while (getline(file, line)) { line_num++; trim_whitespace(line); //Remove whitespace from line if (line.length() == 0) continue; //Continue if blank if (line.length() >= 2 && line.substr(0, 2) == "//") continue; //Skip comments //Parse words gstd::ensure_whitespace(line, "*=@:!"); words = gstd::parse(line, " \t"); //Ensure words exist if (words.size() < 1){ continue; } //Check for fewer than min characters if (words.size() < 5){ COUT_ERROR << "Too few words." << endl; return false; } //Check for missing colon if (words[2] != ":"){ COUT_ERROR << "3rd token (" << words[2] << ") must be colon." << endl; return false; } //Get name nextCtrl.name = words[0]; //Get word try{ nextCtrl.word = stoi(words[1]); }catch(std::invalid_argument){ COUT_ERROR << "Failed to convert " << words[1] << " to int for word num" << endl; return false; } //Get pin try{ nextCtrl.pin = stoi(words[3]); }catch(std::invalid_argument){ COUT_ERROR << "Failed to convert " << words[3] << " to int for pin num" << endl; return false; } //Get default state if (words[4] == "ON"){ nextCtrl.default_to_on = true; }else if (words[4] == "OFF"){ nextCtrl.default_to_on = false; }else{ COUT_ERROR << "Invalid value. Word 5 (" << words[5] << ") is neither ON/OFF. " << endl; } //Set active low if (words.size() == 6 && words[5] == "!"){ nextCtrl.active_low = true; }else{ nextCtrl.active_low = false; } controls.push_back(nextCtrl); } file.close(); }else{ cout << "ERROR: Failed to read '" << readfile << "'." << endl; return false; } return true; } /* Reads an operation file (.OPF) and returns a map of operations. */ bool read_OPF(string readfile, std::vector<control_line> controls, map<std::string, operation>& output){ output.clear(); map<std::string, operation> ops; vector<string> words; size_t line_num = 0; //read through file ifstream file(readfile.c_str()); if (file.is_open()) { string line; operation nextOp; while (getline(file, line)) { line_num++; trim_whitespace(line); //Remove whitespace from line if (line.length() == 0) continue; //Continue if blank // if (line.length() >= 2 && line.substr(0, 2) == "//") continue; //Skip comments //Trim everything after double forward slash (comment), INCLUDING those in quotes! bool skip_line = false; for (size_t i = 0 ; i < line.length()-1 ; i++){ if (line.substr(i, 2) == "//"){ if (i == 0){ skip_line = true; break; }else{ line = line.substr(0, i-1); break; } } } if (skip_line) continue; //Parse words gstd::ensure_whitespace(line, "*=@:"); words = gstd::parse(line, " \t"); //Ensure words exist if (words.size() < 1){ continue; } if (words[0] == "*"){ //If initialized, add last op to map if (nextOp.name != ""){ fill_defaults(nextOp, controls); ops[nextOp.name] = nextOp; } //Clear old operation clear_operation(nextOp); //Ensure correct number of words if (words.size() < 4){ COUT_ERROR << "contains more/less than 4 tokens" << endl; return false; } //Read in fields nextOp.name = words[1]; try{ nextOp.instruction_no = stoi(words[2]); }catch(std::invalid_argument){ COUT_ERROR << " Failed to convert " << words[2] << " to integer" << endl; return false; } try{ nextOp.data_bits = stoi(words[3]); }catch(std::invalid_argument){ COUT_ERROR << " Failed to convert " << words[3] << " to integer" << endl; return false; } //Set flag state if (words.size() == 5){ if (words[4] == "^0"){ nextOp.flag = FLAG_CLR; }else if(words[4] == "^1"){ nextOp.flag = FLAG_SET; }else{ COUT_ERROR << "Invlaid token '" << words[4] << "' for flag specifier (^0/^1)." << endl; } }else{ nextOp.flag = FLAG_X; } }else{ //Check for fewer than min characters if (words.size() < 2){ COUT_ERROR << "Too few characters." << endl; return false; } //Check for missing colon if (words[1] != ":"){ COUT_ERROR << "2nd token (" << words[1] << ") on phase description line must be colon." << endl; return false; } //Get phase int phase; try{ phase = stoi(words[0]); }catch(std::invalid_argument){ COUT_ERROR << "Failed to convert " << words[0] << " to int for phase" << endl; return false; } //For each listed value bool nextIsValue = false; bool mayBeValue = false; string ctrl_name; bool value; bool addToList = false; for (size_t i = 2 ; i < words.size() ; i++){ //Is Equals if (words[i] == "="){ //equals means next is value, if may not be value return false if (!mayBeValue){ COUT_ERROR << "Equals appeared when expecting ctrl_line name" << endl; return false; } //Set that next character is value nextIsValue = true; }else if(nextIsValue){ //is value if (to_upper(words[i]) == "ON"){ value = true; }else if (to_upper(words[i]) == "OFF"){ value = false; }else{ COUT_ERROR << "Failed to interpret '" << words[i] << "' as bool. " << endl; return false; } mayBeValue = false; nextIsValue = false; }else{ //Is ctrl name //Add to master list if possible if (addToList){ int word, pin; if (!get_word_pin(ctrl_name, controls, word, pin)){ COUT_ERROR << "Failed to find control line '" << ctrl_name << "'." << endl; return false; } nextOp.ctrls[phase][word][pin] = value; } //Start new control line data ctrl_name = words[i]; value = true; addToList = true; mayBeValue = true; } } if (addToList){ int word, pin; if (!get_word_pin(ctrl_name, controls, word, pin)){ COUT_ERROR << "Failed to find control line '" << ctrl_name << "'." << endl; } nextOp.ctrls[phase][word][pin] = value; } } } //If initialized, add last op to map if (nextOp.name != ""){ fill_defaults(nextOp, controls); ops[nextOp.name] = nextOp; } file.close(); }else{ cout << "ERROR: Failed to read '" << readfile << "'." << endl; return false; } //Save data to output variable output = ops; return true; } /* Prints a vector of controL-line structs. */ void print_controls(vector<control_line> controls){ for (size_t i = 0 ; i < controls.size() ; i++){ cout << "************** " << controls[i].name << " *************" << endl; cout << "\tWord: " << to_string(controls[i].word) << endl; cout << "\tPin: " << to_string(controls[i].pin) << endl; cout << "\tActive low: " << bool_to_str(controls[i].active_low) << endl; cout << "\tDefault to on: " << bool_to_str(controls[i].default_to_on) << endl; cout << endl; } } /* Prints a map of strings to operations. */ void print_operations(map<string, operation> ops, size_t pin_cols = 4){ map<string, operation>::iterator it; map<int, map<int, map<int, bool> > >::iterator phase_it; map<int, map<int, bool> >::iterator word_it; map<int, bool>::iterator pin_it; //For each operation for ( it = ops.begin(); it != ops.end(); it++){ //Print title cout << "******************** " << it->first << " **********************" << endl; //For each phase for (phase_it = it->second.ctrls.begin() ; phase_it != it->second.ctrls.end() ; phase_it++){ cout << "\tPhase " << to_string(phase_it->first) << ": " <<endl; //For each word for (word_it = phase_it->second.begin() ; word_it != phase_it->second.end() ; word_it++){ cout << "\t\tWord " << to_string(word_it->first) << ": " << endl; size_t count = 0; cout << "\t\t\t"; for (pin_it = word_it->second.begin() ; pin_it != word_it->second.end() ; pin_it++){ //Start newline ever 'x' columns if (count%pin_cols == 0 && count != 1){ cout << endl; cout << "\t\t\t"; } count++; //Print pin data cout << "[" << pin_it->first << "]:" << bool_to_str(pin_it->second) << "\t"; } cout << endl; } } } } /* Maps (LSB -> MSB): Instruction: 4, 5, 6, 7, 12, 14 Phase: 11, 9, 8, 13 Flag: 10 Word: 0, 1, 2, 3 */ int get_address(int phase, int flag, int instruction, int word){ int phase_weights[4] = {11, 9, 8, 13}; int instr_weights[6] = {4, 5, 6, 7, 12, 14}; int word_weights[4] = {0, 1, 2, 3}; int flag_weight = 10; vector<bool> bin_phase = gstd::int_to_bin(phase, 4); vector<bool> bin_inst = gstd::int_to_bin(instruction, 6); vector<bool> bin_word = gstd::int_to_bin(word, 4); int shifted_phase = 0; for (size_t i = 0 ; i < 4 ; i++){ if (bin_phase[i]) shifted_phase += round(pow(2, phase_weights[i])); } int shifted_instr = 0; for (size_t i = 0 ; i < 6 ; i++){ if (bin_inst[i]) shifted_instr += round(pow(2, instr_weights[i])); } int shifted_word = 0; for (size_t i = 0 ; i < 4 ; i++){ if (bin_word[i]) shifted_word += round(pow(2, word_weights[i])); } int shifted_flag = 0; if (flag == 1){ shifted_flag = round(pow(2, flag_weight)); } int addr = shifted_phase + shifted_instr + shifted_word + shifted_flag; cout << "P:" << phase << " F:" << flag << " I:" << instruction << " W:" << word << " >> [" << addr << "] " << endl; cout << "\t\t" << bin_to_str(bin_phase) << " " << bin_to_str(bin_inst) << " " << bin_to_str(bin_word) << endl; return addr; } typedef struct{ int addr; int byte; }int_line; bool sort_intline(int_line x, int_line y){ return x.addr < y.addr; } vector<string> generate_bcm(map<string, operation> ops, vector<control_line> controls){ map<string, operation>::iterator it; map<int, map<int, map<int, bool> > >::iterator phase_it; map<int, map<int, bool> >::iterator word_it; map<int, bool>::iterator pin_it; vector<int_line> int_lines; int_line temp_il; int_lines.reserve(ops.size()*4*16); //4 phases, 16 words //For each operation for ( it = ops.begin(); it != ops.end(); it++){ cout << it->first << endl; //For each phase for (phase_it = it->second.ctrls.begin() ; phase_it != it->second.ctrls.end() ; phase_it++){ cout << "\t" << phase_it->first << endl; //For each word for (word_it = phase_it->second.begin() ; word_it != phase_it->second.end() ; word_it++){ cout << "\t\t" << word_it->first << endl; int pin_byte = 0; //For each pin for (pin_it = word_it->second.begin() ; pin_it != word_it->second.end() ; pin_it++){ //Get active low status bool is_active_low = get_active_low(controls, word_it->first, pin_it->first); //Add bit if true if (pin_it->second){ if (!is_active_low){ pin_byte += round(pow(2, pin_it->first)); } }else if (is_active_low){ pin_byte += round(pow(2, pin_it->first)); } } temp_il.byte = pin_byte; //Handle flag clear condition bool used = false; if (it->second.flag == FLAG_X || it->second.flag == FLAG_CLR){ temp_il.addr = get_address(phase_it->first, 0, it->second.instruction_no, word_it->first); int_lines.push_back(temp_il); used = true; } //Handle flag set condition if (it->second.flag == FLAG_X || it->second.flag == FLAG_CLR){ temp_il.addr = get_address(phase_it->first, 1, it->second.instruction_no, word_it->first); int_lines.push_back(temp_il); used = true; } if (!used){ cout << "ERROR: Operation not used!" << endl; } } //End word loop }//End phase loop }// End operation loop //Sort int_lines sort(int_lines.begin(), int_lines.end(), sort_intline); vector<string> lines; lines.reserve(int_lines.size()); string line; for(size_t i = 0 ; i < int_lines.size() ; i++){ line = to_string(int_lines[i].addr) + ":" + to_string(int_lines[i].byte); lines.push_back(line); } return lines; } void print_bcm(vector<string> bcm){ for (size_t i = 0 ; i < bcm.size() ; i++){ cout << bcm[i] << endl; } } bool save_bcm(string filename, vector<string> bcm){ srand(time(NULL)); ofstream file; file.open (filename); if (!file.is_open()){ return false; } for (size_t i = 0 ; i < bcm.size() ; i++){ file << bcm[i] << endl; } file.close(); return true; } int main(int argc, char** argv){ std::vector<control_line> controls; map<string, operation> ops; if (argc < 3){ read_CW("./opfiles/memorydelta.cw", controls); }else{ read_CW(argv[1], controls); cout << "Reading (CW): " << argv[2] << endl; } print_controls(controls); if (argc < 2){ read_OPF("./opfiles/memorydelta.opf", controls, ops); }else{ read_OPF(argv[1], controls, ops); cout << "Reading (OPF): " << argv[1] << endl; } print_operations(ops); std::vector<string> bcm = generate_bcm(ops, controls); cout << endl; print_bcm(bcm); string bcm_out = "./opfiles/memorydelta.bcm"; if (save_bcm(bcm_out, bcm)){ cout << "Successfully saved BCM data to file '" << bcm_out << "'." << endl; }else{ cout << "ERROR: Failed to write file '" << bcm_out << "'!" << endl; } return 0; }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/exo/wm_helper_ash.h" #include "ash/common/accessibility_delegate.h" #include "ash/common/wm/maximize_mode/maximize_mode_controller.h" #include "ash/common/wm_shell.h" #include "ash/shell.h" #include "base/memory/singleton.h" #include "ui/aura/client/focus_client.h" #include "ui/display/manager/display_manager.h" #include "ui/wm/public/activation_client.h" namespace exo { //////////////////////////////////////////////////////////////////////////////// // WMHelperAsh, public: WMHelperAsh::WMHelperAsh() { ash::WmShell::Get()->AddShellObserver(this); ash::Shell::GetInstance()->activation_client()->AddObserver(this); aura::client::FocusClient* focus_client = aura::client::GetFocusClient(ash::Shell::GetPrimaryRootWindow()); focus_client->AddObserver(this); } WMHelperAsh::~WMHelperAsh() { if (!ash::Shell::HasInstance()) return; aura::client::FocusClient* focus_client = aura::client::GetFocusClient(ash::Shell::GetPrimaryRootWindow()); focus_client->RemoveObserver(this); ash::Shell::GetInstance()->activation_client()->RemoveObserver(this); ash::WmShell::Get()->RemoveShellObserver(this); } //////////////////////////////////////////////////////////////////////////////// // WMHelperAsh, private: const display::ManagedDisplayInfo WMHelperAsh::GetDisplayInfo( int64_t display_id) const { return ash::Shell::GetInstance()->display_manager()->GetDisplayInfo( display_id); } aura::Window* WMHelperAsh::GetContainer(int container_id) { return ash::Shell::GetContainer(ash::Shell::GetTargetRootWindow(), container_id); } aura::Window* WMHelperAsh::GetActiveWindow() const { return ash::Shell::GetInstance()->activation_client()->GetActiveWindow(); } aura::Window* WMHelperAsh::GetFocusedWindow() const { aura::client::FocusClient* focus_client = aura::client::GetFocusClient(ash::Shell::GetPrimaryRootWindow()); return focus_client->GetFocusedWindow(); } ui::CursorSetType WMHelperAsh::GetCursorSet() const { return ash::Shell::GetInstance()->cursor_manager()->GetCursorSet(); } void WMHelperAsh::AddPreTargetHandler(ui::EventHandler* handler) { ash::Shell::GetInstance()->AddPreTargetHandler(handler); } void WMHelperAsh::PrependPreTargetHandler(ui::EventHandler* handler) { ash::Shell::GetInstance()->PrependPreTargetHandler(handler); } void WMHelperAsh::RemovePreTargetHandler(ui::EventHandler* handler) { ash::Shell::GetInstance()->RemovePreTargetHandler(handler); } void WMHelperAsh::AddPostTargetHandler(ui::EventHandler* handler) { ash::Shell::GetInstance()->AddPostTargetHandler(handler); } void WMHelperAsh::RemovePostTargetHandler(ui::EventHandler* handler) { ash::Shell::GetInstance()->RemovePostTargetHandler(handler); } bool WMHelperAsh::IsMaximizeModeWindowManagerEnabled() const { return ash::WmShell::Get() ->maximize_mode_controller() ->IsMaximizeModeWindowManagerEnabled(); } bool WMHelperAsh::IsSpokenFeedbackEnabled() const { return ash::WmShell::Get() ->accessibility_delegate() ->IsSpokenFeedbackEnabled(); } void WMHelperAsh::PlayEarcon(int sound_key) const { return ash::WmShell::Get()->accessibility_delegate()->PlayEarcon(sound_key); } void WMHelperAsh::OnWindowActivated( aura::client::ActivationChangeObserver::ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) { NotifyWindowActivated(gained_active, lost_active); } void WMHelperAsh::OnWindowFocused(aura::Window* gained_focus, aura::Window* lost_focus) { NotifyWindowFocused(gained_focus, lost_focus); } void WMHelperAsh::OnCursorVisibilityChanged(bool is_visible) { NotifyCursorVisibilityChanged(is_visible); } void WMHelperAsh::OnCursorSetChanged(ui::CursorSetType cursor_set) { NotifyCursorSetChanged(cursor_set); } void WMHelperAsh::OnAccessibilityModeChanged( ash::AccessibilityNotificationVisibility notify) { NotifyAccessibilityModeChanged(); } void WMHelperAsh::OnMaximizeModeStarted() { NotifyMaximizeModeStarted(); } void WMHelperAsh::OnMaximizeModeEnded() { NotifyMaximizeModeEnded(); } } // namespace exo
#pragma once #include <moodycamel/blockingconcurrentqueue.h> #include <thread> #include "common.hpp" #include "components/types.hpp" #include "events/signal_fwd.hpp" #include "events/signal_receiver.hpp" #include "events/types.hpp" #include "settings.hpp" #include "utils/actions.hpp" #include "utils/file.hpp" #include "x11/types.hpp" POLYBAR_NS // fwd decl {{{ enum class alignment; class bar; class config; class connection; class inotify_watch; class ipc; class logger; class signal_emitter; namespace modules { struct module_interface; } // namespace modules using module_t = shared_ptr<modules::module_interface>; using modulemap_t = std::map<alignment, vector<module_t>>; // }}} class controller : public signal_receiver<SIGN_PRIORITY_CONTROLLER, signals::eventqueue::exit_terminate, signals::eventqueue::exit_reload, signals::eventqueue::notify_change, signals::eventqueue::notify_forcechange, signals::eventqueue::check_state, signals::ipc::action, signals::ipc::command, signals::ipc::hook, signals::ui::ready, signals::ui::button_press, signals::ui::update_background> { public: using make_type = unique_ptr<controller>; static make_type make(unique_ptr<ipc>&& ipc, unique_ptr<inotify_watch>&& config_watch); explicit controller(connection&, signal_emitter&, const logger&, const config&, unique_ptr<bar>&&, unique_ptr<ipc>&&, unique_ptr<inotify_watch>&&); ~controller(); bool run(bool writeback, string snapshot_dst); bool enqueue(event&& evt); bool enqueue(string&& input_data); protected: void read_events(); void process_eventqueue(); void process_inputdata(); bool process_update(bool force); bool on(const signals::eventqueue::notify_change& evt); bool on(const signals::eventqueue::notify_forcechange& evt); bool on(const signals::eventqueue::exit_terminate& evt); bool on(const signals::eventqueue::exit_reload& evt); bool on(const signals::eventqueue::check_state& evt); bool on(const signals::ui::ready& evt); bool on(const signals::ui::button_press& evt); bool on(const signals::ipc::action& evt); bool on(const signals::ipc::command& evt); bool on(const signals::ipc::hook& evt); bool on(const signals::ui::update_background& evt); private: size_t setup_modules(alignment align); bool forward_action(const actions_util::action& cmd); bool try_forward_legacy_action(const string& cmd); connection& m_connection; signal_emitter& m_sig; const logger& m_log; const config& m_conf; unique_ptr<bar> m_bar; unique_ptr<ipc> m_ipc; unique_ptr<inotify_watch> m_confwatch; array<unique_ptr<file_descriptor>, 2> m_queuefd{}; /** * \brief State flag */ std::atomic<bool> m_process_events{false}; /** * \brief Destination path of generated snapshot */ string m_snapshot_dst; /** * \brief Controls weather the output gets printed to stdout */ bool m_writeback{false}; /** * \brief Internal event queue */ moodycamel::BlockingConcurrentQueue<event> m_queue; /** * \brief Loaded modules */ vector<module_t> m_modules; /** * \brief Loaded modules grouped by block */ modulemap_t m_blocks; /** * \brief Maximum number of subsequent events to swallow */ size_t m_swallow_limit{5U}; /** * \brief Time to wait for subsequent events */ std::chrono::milliseconds m_swallow_update{10}; /** * \brief Input data */ string m_inputdata; /** * \brief Thread for the eventqueue loop */ std::thread m_event_thread; /** * \brief Misc threads */ vector<std::thread> m_threads; }; POLYBAR_NS_END
#include <cctype> #include <cstdio> #include <cstdlib> #include <iosfwd> // for stringstream #include <string> #include "input.h" #include "lexer.h" std::stringstream buffer; SourceLocation CurLoc; SourceLocation LexLoc; std::string IdentifierStr; double NumVal; auto getTokName(int Tok) -> std::string { switch (Tok) { case tok_eof: return "eof"; case tok_function: return "function"; case tok_return: return "return"; case tok_extern: return "extern"; case tok_identifier: return "identifier"; case tok_number: return "number"; case tok_if: return "if"; case tok_then: return "then"; case tok_else: return "else"; case tok_for: return "for"; case tok_in: return "in"; case tok_binary: return "binary"; case tok_unary: return "unary"; case tok_var: return "var"; case tok_const: return "const"; } return std::string(1, (char)Tok); } static auto is_identifier_first_char(char c) -> bool { return isalpha(c) || c == '_'; } static auto is_identifier_char(char c) -> bool { return isalnum(c) || c == '_'; } static auto advance() -> int { int LastChar = get_char(); if (LastChar == '\n' || LastChar == '\r') { LexLoc.Line++; LexLoc.Col = 0; } else { LexLoc.Col++; } return LastChar; } /// gettok - Return the next token from standard input. auto gettok() -> int { static int LastChar = ' '; // Skip any whitespace. while (isspace(LastChar)) { LastChar = advance(); } CurLoc = LexLoc; if (is_identifier_first_char(LastChar)) { IdentifierStr = LastChar; while (is_identifier_char((LastChar = advance()))) { IdentifierStr += LastChar; } if (IdentifierStr == "function") { return tok_function; } if (IdentifierStr == "return") { return tok_return; } if (IdentifierStr == "extern") { return tok_extern; } if (IdentifierStr == "if") { return tok_if; } if (IdentifierStr == "else") { return tok_else; } if (IdentifierStr == "for") { return tok_for; } if (IdentifierStr == "in") { return tok_in; } if (IdentifierStr == "binary") { return tok_binary; } if (IdentifierStr == "unary") { return tok_unary; } if (IdentifierStr == "var") { return tok_var; } return tok_identifier; } // Number: [0-9.]+ if (isdigit(LastChar) || LastChar == '.') { std::string NumStr; do { NumStr += LastChar; LastChar = advance(); } while (isdigit(LastChar) || LastChar == '.'); NumVal = strtod(NumStr.c_str(), nullptr); return tok_number; } // Comment until end of line. if (LastChar == '#') { do LastChar = advance(); while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); if (LastChar != EOF) return gettok(); } // Check for end of file. Don't eat the EOF. if (LastChar == EOF) { return tok_eof; } // Otherwise, just return the character as its ascii value. int ThisChar = LastChar; LastChar = advance(); return ThisChar; } /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current /// token the parser is looking at. getNextToken reads another token from the /// lexer and updates CurTok with its results. int CurTok; auto getNextToken() -> int { return CurTok = gettok(); }
#include <ny/ny.hpp> #include <SkBitmap.h> #include <SkCanvas.h> #include <SkImage.h> #include <SkPath.h> #include <SkSurface.h> class MyEventHandler : public ny::EventHandler { public: ny::BufferSurface* buffer; public: MyEventHandler(ny::LoopControl& mainLoop, ny::WindowContext& wc) : lc_(mainLoop), wc_(wc) {} bool handleEvent(const ny::Event& ev) override; protected: ny::LoopControl& lc_; ny::WindowContext& wc_; }; int main() { auto& backend = ny::Backend::choose(); auto ac = backend.createAppContext(); ny::WindowSettings settings; auto wc = ac->createWindowContext(settings); ny::LoopControl control; MyEventHandler handler(control, *wc); wc->eventHandler(handler); wc->refresh(); auto surface = ny::surface(*wc); if(surface.type != ny::SurfaceType::buffer) { ny::error("Failed to create surface buffer integration"); return EXIT_FAILURE; } handler.buffer = surface.buffer.get(); ny::debug("Entering main loop"); ac->dispatchLoop(control); } bool MyEventHandler::handleEvent(const ny::Event& ev) { // ny::debug("Received event with type ", ev.type()); if(ev.type() == ny::eventType::close) { ny::debug("Window closed from server side. Exiting."); lc_.stop(); return true; } else if(ev.type() == ny::eventType::draw) { auto guard = buffer->get(); auto data = guard.get(); //decltype(data): ny::MutableImageData SkImageInfo info = SkImageInfo::Make(data.size.x, data.size.y, kBGRA_8888_SkColorType, kPremul_SkAlphaType); size_t rowBytes = info.minRowBytes(); auto surface = SkSurface::MakeRasterDirect(info, data.data, data.stride); SkCanvas* canvas = surface->getCanvas(); const SkScalar scale = 256.0f; const SkScalar R = 0.45f * scale; const SkScalar TAU = 6.2831853f; SkPath path; for (int i = 0; i < 5; ++i) { SkScalar theta = 2 * i * TAU / 5; if (i == 0) { path.moveTo(R * cos(theta), R * sin(theta)); } else { path.lineTo(R * cos(theta), R * sin(theta)); } } path.close(); SkPaint p; p.setAntiAlias(true); canvas->clear(SK_ColorWHITE); canvas->translate(0.5f * scale, 0.5f * scale); canvas->drawPath(path, p); } else if(ev.type() == ny::eventType::key) { const auto& kev = static_cast<const ny::KeyEvent&>(ev); if(!kev.pressed) return false; if(kev.keycode == ny::Keycode::escape) { ny::debug("Esc key pressed. Exiting."); lc_.stop(); return true; } else if(kev.keycode == ny::Keycode::f) { ny::debug("f key pressed. Fullscreen."); wc_.fullscreen(); return true; } else if(kev.keycode == ny::Keycode::n) { ny::debug("n key pressed. Normal."); wc_.normalState(); return true; } else if(kev.keycode == ny::Keycode::i) { ny::debug("i key pressed. Iconic (minimize)."); wc_.minimize(); return true; } else if(kev.keycode == ny::Keycode::m) { ny::debug("m key pressed. maximize."); wc_.maximize(); return true; } } return false; };
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <sstream> using namespace std; #define PB push_back #define MP make_pair #define lowbit(x) ((x)&(-(x))) #define sqr(x) ((x)*(x)) typedef long long LL; typedef unsigned long long ULL; typedef vector<int> VI; typedef vector<string> VS; typedef pair<int,int> PII; const double pi = acos(-1.0); const double eps = 1e-8; struct Tpoint { double x,y; Tpoint(){} Tpoint(double a,double b){x=a;y=b;} inline double norm(){return sqrt(sqr(x)+sqr(y));} }; inline Tpoint operator +(const Tpoint &a,const Tpoint &b){return Tpoint(a.x+b.x,a.y+b.y);} inline Tpoint operator -(const Tpoint &a,const Tpoint &b){return Tpoint(a.x-b.x,a.y-b.y);} inline Tpoint operator *(const Tpoint &a,const double &b){return Tpoint(a.x*b,a.y*b);} inline Tpoint operator /(const Tpoint &a,const double &b){return Tpoint(a.x/b,a.y/b);} inline double dot(const Tpoint &a,const Tpoint &b){return a.x*b.x+a.y*b.y;} inline double det(const Tpoint &a,const Tpoint &b){return a.x*b.y-a.y*b.x;} //============================================================================================== const int maxn = 105; long long f[maxn][2][2][3]; void calc(int n, string s, string t) { for (int i=1;i<n;++i){ for (int st=0;st<2;++st) for (int la=0;la<2;++la) for (int la2=0;la2<=2;++la2){ //swap s[i],s[i-1] if (la==1 && s[i-1]=='B' && s[i]=='A'){ if (i>1){ f[i+1][st][1][0]+=f[i][st][la][la2]; }else{ f[i+1][0][1][0]+=f[i][st][la][la2]; } } //forbid AB--la=1 la2=0 if (i>=2 && la==s[i-1]-'A' && la2==s[i-2]-'A' && la==1 && la2==0) continue; f[i+1][st][s[i]-'A'][la]+=f[i][st][la][la2]; } } } int main() { string t,s; cin >> t; //for (int i=0;i<100;++i) // t+='A'+rand()%2; //cout << t << endl; bool ok=false; for (int i=0;i<t.size();++i) if (t[i]=='B'){ s=""; for (int j=0;j<t.size();++j) s+=t[(i+j)%t.size()]; ok=true; break; } //for (int i=0;i<100;++i) // t+='A'+rand()%2; //cout << t << endl; if (!ok){ puts("1"); return 0; } int n=s.size(); f[1][s[0]-'A'][s[0]-'A'][2]=1; //for (int i=0;i<100;++i) // t+='A'+rand()%2; //cout << t << endl; calc(n, s, t); long long ans=0; for (int st=0;st<2;++st) for (int la=0;la<2;++la) for (int la2=0;la2<=2;++la2)if (f[n][st][la][la2]){ if (s[0]-'A'==st && s[n-1]-'A'==la){ if (st==0 && la==1){ ans+=f[n][st][la][la2]; } } if (n>=2 && la==s[n-1]-'A' && la2==s[n-2]-'A' && la==1 && la2==0) continue; if (la==s[n-1]-'A' && s[0]-'A'==st && la==0 && st==1) continue; ans+=f[n][st][la][la2]; } cout << ans << endl; return 0; }
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/redshift/model/CreateHsmClientCertificateRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::Redshift::Model; using namespace Aws::Utils; CreateHsmClientCertificateRequest::CreateHsmClientCertificateRequest() : m_hsmClientCertificateIdentifierHasBeenSet(false), m_tagsHasBeenSet(false) { } Aws::String CreateHsmClientCertificateRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=CreateHsmClientCertificate&"; if(m_hsmClientCertificateIdentifierHasBeenSet) { ss << "HsmClientCertificateIdentifier=" << StringUtils::URLEncode(m_hsmClientCertificateIdentifier.c_str()) << "&"; } if(m_tagsHasBeenSet) { unsigned tagsCount = 1; for(auto& item : m_tags) { item.OutputToStream(ss, "Tags.member.", tagsCount, ""); tagsCount++; } } ss << "Version=2012-12-01"; return ss.str(); }
#include <stdlib.h> #include "Game/Components/LinkedEntityComponent.h" #include "Game/Components/PlayerCameraComponent.h" #include "Game/Components/PlayerMovementComponent.h" #include "GameBoard.h" #include "GameEngine/EntitySystem/Components/CollidablePhysicsComponent.h" #include "GameEngine/EntitySystem/Components/LightEntity.h" #include "GameEngine/EntitySystem/Components/SpriteRenderComponent.h" #include "GameEngine/EntitySystem/Components/TextRenderComponent.h" #include "GameEngine/GameEngineMain.h" #include <cassert> #include <fstream> #include <iostream> using namespace Game; GameEngine::TextRenderComponent *CountDownrender; sf::Time m_countDownTimer; sf::Clock m_clock; int countDownTime = 60; bool isGameOver; bool cleanGame; GameBoard::GameBoard() : m_player(nullptr), m_CountDown(nullptr), m_BlockerLeft(nullptr), m_BlockerRight(nullptr) { m_clock.restart(); isGameOver = false; cleanGame = false; LoadMap("level1.txt", 80); CreatePlayer(); CreateCountDown(); CreateBackground(); CreateBlocker(); m_light = new GameEngine::LightEntity(); GameEngine::GameEngineMain::GetInstance()->AddEntity(m_light); m_light->SetPos(sf::Vector2f(70.f, 130.f)); m_light->SetSize(sf::Vector2f(3000.f, 3000.f)); } GameBoard::~GameBoard() {} void GameBoard::Update() { if (!isGameOver) { UpdateCountDown(); } else if (!cleanGame) { GameEngine::GameEngineMain::GetInstance()->RemoveEntity(m_player); GameEngine::GameEngineMain::GetInstance()->RemoveEntity(m_CountDown); } UpdateLight(); cleanGame = true; } void GameBoard::LoadMap(const std::string &filename, const size_t tile_size) { std::ifstream file("Resources/Maps/" + filename); file >> m_width >> m_height; std::string line; for (size_t row = 0; row < m_height; ++row) { file >> line; assert(line.size() == m_width); for (size_t col = 0; col < m_width; ++col) { switch (line[col]) { case 'X': CreateObstacle(tile_size * col, tile_size * row, tile_size, tile_size); break; case '.': break; default: break; } } } } void GameBoard::CreatePlayer() { m_player = new GameEngine::Entity(); GameEngine::GameEngineMain::GetInstance()->AddEntity(m_player); m_player->SetPos(sf::Vector2f(50.f, 50.f)); m_player->SetSize(sf::Vector2f(50.f, 50.f)); GameEngine::SpriteRenderComponent *spriteRender = m_player->AddComponent<GameEngine::SpriteRenderComponent>(); spriteRender->SetFillColor(sf::Color::Transparent); spriteRender->SetTexture(GameEngine::eTexture::PlayerDown); spriteRender->SetTileIndex(0, 0); m_player->AddComponent<PlayerMovementComponent>(); m_player->AddComponent<GameEngine::CollidablePhysicsComponent>(); m_player->AddComponent<PlayerCameraComponent>(); } void GameBoard::CreateBackground() { GameEngine::Entity *background = new GameEngine::Entity; GameEngine::GameEngineMain::GetInstance()->AddEntity(background); background->SetPos(sf::Vector2f(250.f, 250.f)); background->SetSize(sf::Vector2f(768.f, 756.f)); GameEngine::SpriteRenderComponent *spriteRender = background->AddComponent<GameEngine::SpriteRenderComponent>(); spriteRender->SetFillColor(sf::Color::Transparent); spriteRender->SetTexture(GameEngine::eTexture::Background); spriteRender->SetZLevel(-1); LinkedEntityComponent *linkedCmp = background->AddComponent<LinkedEntityComponent>(); linkedCmp->SetFollowedEntity(m_player); linkedCmp->SetFollowedOffset(sf::Vector2f(-50.f, -50.f)); } void GameBoard::CreateCountDown() { GameEngine::Entity *CountDown = new GameEngine::Entity(); CountDownrender = CountDown->AddComponent<GameEngine::TextRenderComponent>(); // get time m_countDownTimer = m_clock.getElapsedTime(); const int time = m_countDownTimer.asSeconds(); // set text CountDownrender->SetFont("Calibri Regular.ttf"); CountDownrender->SetString("Time: " + std::to_string(time)); CountDownrender->SetZLevel(1001); CountDownrender->SetColor(sf::Color::Red); CountDown->SetPos(sf::Vector2f(10.f, 10.f)); CountDown->SetSize(sf::Vector2f(0.f, 0.f)); LinkedEntityComponent *linkedCmp = CountDown->AddComponent<LinkedEntityComponent>(); linkedCmp->SetFollowedEntity(m_player); linkedCmp->SetFollowedOffset(sf::Vector2f(-470.f, -360.f)); GameEngine::GameEngineMain::GetInstance()->AddEntity(CountDown); m_CountDown = CountDown; } void GameBoard::UpdateCountDown() { m_countDownTimer = m_clock.getElapsedTime(); const int time = m_countDownTimer.asSeconds(); CountDownrender->SetString("Time: " + std::to_string(time)); if (time >= countDownTime) { isGameOver = true; Reset(); } if (time % 5 == 0) UpdateBlocker(); } void GameBoard::CreateBlocker() { m_BlockerLeft = new GameEngine::Entity(); m_BlockerRight = new GameEngine::Entity(); GameEngine::GameEngineMain::GetInstance()->AddEntity(m_BlockerLeft); GameEngine::GameEngineMain::GetInstance()->AddEntity(m_BlockerRight); m_BlockerLeft->SetPos(sf::Vector2f(0.f, 0.f)); m_BlockerLeft->SetSize(sf::Vector2f(10.f, 600.f)); m_BlockerRight->SetPos(sf::Vector2f(400.f, 0.f)); m_BlockerRight->SetSize(sf::Vector2f(10.f, 600.f)); GameEngine::RenderComponent *renderLeft = m_BlockerLeft->AddComponent<GameEngine::RenderComponent>(); GameEngine::RenderComponent *renderRight = m_BlockerRight->AddComponent<GameEngine::RenderComponent>(); renderLeft->SetFillColor(sf::Color::Black); renderLeft->SetZLevel(1000); renderRight->SetFillColor(sf::Color::Black); renderRight->SetZLevel(1000); LinkedEntityComponent *LinkedLeft = m_BlockerLeft->AddComponent<LinkedEntityComponent>(); LinkedEntityComponent *LinkedRight = m_BlockerRight->AddComponent<LinkedEntityComponent>(); LinkedLeft->SetFollowedEntity(m_player); LinkedLeft->SetFollowedOffset(sf::Vector2f(250.f, 0.f)); LinkedRight->SetFollowedEntity(m_player); LinkedRight->SetFollowedOffset(sf::Vector2f(-250.f, 0.f)); } void GameBoard::UpdateBlocker() { m_BlockerLeft->SetSize(sf::Vector2f(m_BlockerLeft->GetSize().x + 0.13, m_BlockerLeft->GetSize().y)); m_BlockerRight->SetSize(sf::Vector2f(m_BlockerRight->GetSize().x + 0.13, m_BlockerRight->GetSize().y)); } void GameBoard::Reset() { m_player->SetPos(sf::Vector2f(50.f, 50.f)); m_BlockerLeft->SetSize(sf::Vector2f(10.f, 600.f)); m_BlockerRight->SetSize(sf::Vector2f(10.f, 600.f)); isGameOver = false; m_clock.restart(); } void GameBoard::CreateObstacle(float x, float y, float wid, float len) { GameEngine::Entity *obstacle = new GameEngine::Entity(); GameEngine::GameEngineMain::GetInstance()->AddEntity(obstacle); obstacle->SetPos(sf::Vector2f(x, y)); obstacle->SetSize(sf::Vector2f(wid, len)); GameEngine::SpriteRenderComponent *render = obstacle->AddComponent<GameEngine::SpriteRenderComponent>(); render->SetFillColor(sf::Color::Transparent); render->SetTexture(GameEngine::eTexture::Wall); render->SetZLevel(1); obstacle->AddComponent<GameEngine::CollidableComponent>(); } void GameBoard::UpdateLight() { m_light->SetPos( sf::Vector2f(m_player->GetPos().x + 5, m_player->GetPos().y + 10)); }
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Envelope.h> #include <geos/geom/CoordinateArraySequence.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateFilter.h> #include <geos/util.h> #include <sstream> #include <cassert> #include <algorithm> #include <vector> #include <cmath> namespace geos { namespace geom { // geos::geom CoordinateArraySequence::CoordinateArraySequence(): dimension(0) { } CoordinateArraySequence::CoordinateArraySequence(size_t n, size_t dimension_in): vect(n), dimension(dimension_in) { } CoordinateArraySequence::CoordinateArraySequence(std::vector<Coordinate> && coords, size_t dimension_in): vect(std::move(coords)), dimension(dimension_in) { } CoordinateArraySequence::CoordinateArraySequence( std::vector<Coordinate>* coords, size_t dimension_in) : dimension(dimension_in) { std::unique_ptr<std::vector<Coordinate>> coordp(coords); if(coordp) { vect = std::move(*coords); } } CoordinateArraySequence::CoordinateArraySequence( const CoordinateArraySequence& c) : CoordinateSequence(c), vect(c.vect), dimension(c.getDimension()) { } CoordinateArraySequence::CoordinateArraySequence( const CoordinateSequence& c) : CoordinateSequence(c), vect(c.size()), dimension(c.getDimension()) { for(size_t i = 0, n = vect.size(); i < n; ++i) { vect[i] = c.getAt(i); } } std::unique_ptr<CoordinateSequence> CoordinateArraySequence::clone() const { return detail::make_unique<CoordinateArraySequence>(*this); } void CoordinateArraySequence::setPoints(const std::vector<Coordinate>& v) { vect.assign(v.begin(), v.end()); } std::size_t CoordinateArraySequence::getDimension() const { if(dimension != 0) { return dimension; } if(vect.empty()) { return 3; } if(std::isnan(vect[0].z)) { dimension = 2; } else { dimension = 3; } return dimension; } void CoordinateArraySequence::toVector(std::vector<Coordinate>& out) const { out.insert(out.end(), vect.begin(), vect.end()); } void CoordinateArraySequence::add(const Coordinate& c) { vect.push_back(c); } void CoordinateArraySequence::add(const Coordinate& c, bool allowRepeated) { if(!allowRepeated && ! vect.empty()) { const Coordinate& last = vect.back(); if(last.equals2D(c)) { return; } } vect.push_back(c); } void CoordinateArraySequence::add(const CoordinateSequence* cl, bool allowRepeated, bool direction) { // FIXME: don't rely on negative values for 'j' (the reverse case) const auto npts = cl->size(); if(direction) { for(size_t i = 0; i < npts; ++i) { add(cl->getAt(i), allowRepeated); } } else { for(auto j = npts; j > 0; --j) { add(cl->getAt(j - 1), allowRepeated); } } } /*public*/ void CoordinateArraySequence::add(size_t i, const Coordinate& coord, bool allowRepeated) { // don't add duplicate coordinates if(! allowRepeated) { size_t sz = size(); if(sz > 0) { if(i > 0) { const Coordinate& prev = getAt(i - 1); if(prev.equals2D(coord)) { return; } } if(i < sz) { const Coordinate& next = getAt(i); if(next.equals2D(coord)) { return; } } } } vect.insert(vect.begin() + i, coord); } size_t CoordinateArraySequence::getSize() const { return vect.size(); } const Coordinate& CoordinateArraySequence::getAt(size_t pos) const { return vect[pos]; } void CoordinateArraySequence::getAt(size_t pos, Coordinate& c) const { c = vect[pos]; } void CoordinateArraySequence::setAt(const Coordinate& c, size_t pos) { vect[pos] = c; } void CoordinateArraySequence::expandEnvelope(Envelope& env) const { for(const auto& coord : vect) { env.expandToInclude(coord); } } void CoordinateArraySequence::setOrdinate(size_t index, size_t ordinateIndex, double value) { switch(ordinateIndex) { case CoordinateSequence::X: vect[index].x = value; break; case CoordinateSequence::Y: vect[index].y = value; break; case CoordinateSequence::Z: vect[index].z = value; break; default: { std::stringstream ss; ss << "Unknown ordinate index " << index; throw util::IllegalArgumentException(ss.str()); break; } } } void CoordinateArraySequence::apply_rw(const CoordinateFilter* filter) { for(auto& coord : vect) { filter->filter_rw(&coord); } dimension = 0; // re-check (see http://trac.osgeo.org/geos/ticket/435) } void CoordinateArraySequence::apply_ro(CoordinateFilter* filter) const { for(const auto& coord : vect) { filter->filter_ro(&coord); } } } // namespace geos::geom } //namespace geos
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <dbwrapper.h> #include <uint256.h> #include <random.h> #include <test/test_bytz.h> #include <memory> #include <boost/test/unit_test.hpp> // Test if a string consists entirely of null characters bool is_null_key(const std::vector<unsigned char>& key) { bool isnull = true; for (unsigned int i = 0; i < key.size(); i++) isnull &= (key[i] == '\x00'); return isnull; } BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(dbwrapper) { // Perform tests both obfuscated and non-obfuscated. for (bool obfuscate : {false, true}) { fs::path ph = SetDataDir(std::string("dbwrapper").append(obfuscate ? "_true" : "_false")); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); char key = 'k'; uint256 in = InsecureRand256(); uint256 res; // Ensure that we're doing real obfuscation when obfuscate=true BOOST_CHECK(obfuscate != is_null_key(dbwrapper_private::GetObfuscateKey(dbw))); BOOST_CHECK(dbw.Write(key, in)); BOOST_CHECK(dbw.Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); } } // Test batch operations BOOST_AUTO_TEST_CASE(dbwrapper_batch) { // Perform tests both obfuscated and non-obfuscated. for (bool obfuscate : {false, true}) { fs::path ph = SetDataDir(std::string("dbwrapper_batch").append(obfuscate ? "_true" : "_false")); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); char key = 'i'; uint256 in = InsecureRand256(); char key2 = 'j'; uint256 in2 = InsecureRand256(); char key3 = 'k'; uint256 in3 = InsecureRand256(); uint256 res; CDBBatch batch(dbw); batch.Write(key, in); batch.Write(key2, in2); batch.Write(key3, in3); // Remove key3 before it's even been written batch.Erase(key3); dbw.WriteBatch(batch); BOOST_CHECK(dbw.Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); BOOST_CHECK(dbw.Read(key2, res)); BOOST_CHECK_EQUAL(res.ToString(), in2.ToString()); // key3 should've never been written BOOST_CHECK(dbw.Read(key3, res) == false); } } BOOST_AUTO_TEST_CASE(dbwrapper_iterator) { // Perform tests both obfuscated and non-obfuscated. for (bool obfuscate : {false, true}) { fs::path ph = SetDataDir(std::string("dbwrapper_iterator").append(obfuscate ? "_true" : "_false")); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); // The two keys are intentionally chosen for ordering char key = 'j'; uint256 in = InsecureRand256(); BOOST_CHECK(dbw.Write(key, in)); char key2 = 'k'; uint256 in2 = InsecureRand256(); BOOST_CHECK(dbw.Write(key2, in2)); std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper&>(dbw).NewIterator()); // Be sure to seek past the obfuscation key (if it exists) it->Seek(key); char key_res; uint256 val_res; it->GetKey(key_res); it->GetValue(val_res); BOOST_CHECK_EQUAL(key_res, key); BOOST_CHECK_EQUAL(val_res.ToString(), in.ToString()); it->Next(); it->GetKey(key_res); it->GetValue(val_res); BOOST_CHECK_EQUAL(key_res, key2); BOOST_CHECK_EQUAL(val_res.ToString(), in2.ToString()); it->Next(); BOOST_CHECK_EQUAL(it->Valid(), false); } } // Test that we do not obfuscation if there is existing data. BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate) { // We're going to share this fs::path between two wrappers fs::path ph = SetDataDir("existing_data_no_obfuscate"); create_directories(ph); // Set up a non-obfuscated wrapper to write some initial data. std::unique_ptr<CDBWrapper> dbw = MakeUnique<CDBWrapper>(ph, (1 << 10), false, false, false); char key = 'k'; uint256 in = InsecureRand256(); uint256 res; BOOST_CHECK(dbw->Write(key, in)); BOOST_CHECK(dbw->Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); // Call the destructor to free leveldb LOCK dbw.reset(); // Now, set up another wrapper that wants to obfuscate the same directory CDBWrapper odbw(ph, (1 << 10), false, false, true); // Check that the key/val we wrote with unobfuscated wrapper exists and // is readable. uint256 res2; BOOST_CHECK(odbw.Read(key, res2)); BOOST_CHECK_EQUAL(res2.ToString(), in.ToString()); BOOST_CHECK(!odbw.IsEmpty()); // There should be existing data BOOST_CHECK(is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); // The key should be an empty string uint256 in2 = InsecureRand256(); uint256 res3; // Check that we can write successfully BOOST_CHECK(odbw.Write(key, in2)); BOOST_CHECK(odbw.Read(key, res3)); BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString()); } // Ensure that we start obfuscating during a reindex. BOOST_AUTO_TEST_CASE(existing_data_reindex) { // We're going to share this fs::path between two wrappers fs::path ph = SetDataDir("existing_data_reindex"); create_directories(ph); // Set up a non-obfuscated wrapper to write some initial data. std::unique_ptr<CDBWrapper> dbw = MakeUnique<CDBWrapper>(ph, (1 << 10), false, false, false); char key = 'k'; uint256 in = InsecureRand256(); uint256 res; BOOST_CHECK(dbw->Write(key, in)); BOOST_CHECK(dbw->Read(key, res)); BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); // Call the destructor to free leveldb LOCK dbw.reset(); // Simulate a -reindex by wiping the existing data store CDBWrapper odbw(ph, (1 << 10), false, true, true); // Check that the key/val we wrote with unobfuscated wrapper doesn't exist uint256 res2; BOOST_CHECK(!odbw.Read(key, res2)); BOOST_CHECK(!is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); uint256 in2 = InsecureRand256(); uint256 res3; // Check that we can write successfully BOOST_CHECK(odbw.Write(key, in2)); BOOST_CHECK(odbw.Read(key, res3)); BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString()); } BOOST_AUTO_TEST_CASE(iterator_ordering) { fs::path ph = SetDataDir("iterator_ordering"); CDBWrapper dbw(ph, (1 << 20), true, false, false); for (int x=0x00; x<256; ++x) { uint8_t key = x; uint32_t value = x*x; if (!(x & 1)) BOOST_CHECK(dbw.Write(key, value)); } // Check that creating an iterator creates a snapshot std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper&>(dbw).NewIterator()); for (int x=0x00; x<256; ++x) { uint8_t key = x; uint32_t value = x*x; if (x & 1) BOOST_CHECK(dbw.Write(key, value)); } for (int seek_start : {0x00, 0x80}) { it->Seek((uint8_t)seek_start); for (int x=seek_start; x<255; ++x) { uint8_t key; uint32_t value; BOOST_CHECK(it->Valid()); if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure break; BOOST_CHECK(it->GetKey(key)); if (x & 1) { BOOST_CHECK_EQUAL(key, x + 1); continue; } BOOST_CHECK(it->GetValue(value)); BOOST_CHECK_EQUAL(key, x); BOOST_CHECK_EQUAL(value, x*x); it->Next(); } BOOST_CHECK(!it->Valid()); } } struct StringContentsSerializer { // Used to make two serialized objects the same while letting them have different lengths // This is a terrible idea std::string str; StringContentsSerializer() {} explicit StringContentsSerializer(const std::string& inp) : str(inp) {} StringContentsSerializer& operator+=(const std::string& s) { str += s; return *this; } StringContentsSerializer& operator+=(const StringContentsSerializer& s) { return *this += s.str; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { if (ser_action.ForRead()) { str.clear(); char c = 0; while (true) { try { READWRITE(c); str.push_back(c); } catch (const std::ios_base::failure& e) { break; } } } else { for (size_t i = 0; i < str.size(); i++) READWRITE(str[i]); } } }; BOOST_AUTO_TEST_CASE(iterator_string_ordering) { char buf[10]; fs::path ph = SetDataDir("iterator_string_ordering"); CDBWrapper dbw(ph, (1 << 20), true, false, false); for (int x=0x00; x<10; ++x) { for (int y = 0; y < 10; y++) { snprintf(buf, sizeof(buf), "%d", x); StringContentsSerializer key(buf); for (int z = 0; z < y; z++) key += key; uint32_t value = x*x; BOOST_CHECK(dbw.Write(key, value)); } } std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper&>(dbw).NewIterator()); for (int seek_start : {0, 5}) { snprintf(buf, sizeof(buf), "%d", seek_start); StringContentsSerializer seek_key(buf); it->Seek(seek_key); for (int x=seek_start; x<10; ++x) { for (int y = 0; y < 10; y++) { snprintf(buf, sizeof(buf), "%d", x); std::string exp_key(buf); for (int z = 0; z < y; z++) exp_key += exp_key; StringContentsSerializer key; uint32_t value; BOOST_CHECK(it->Valid()); if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure break; BOOST_CHECK(it->GetKey(key)); BOOST_CHECK(it->GetValue(value)); BOOST_CHECK_EQUAL(key.str, exp_key); BOOST_CHECK_EQUAL(value, x*x); it->Next(); } } BOOST_CHECK(!it->Valid()); } } BOOST_AUTO_TEST_SUITE_END()
/* * Copyright 2021 4Paradigm * * 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. */ // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // #include "log/writable_file.h" #include <errno.h> #include <stdio.h> #include <unistd.h> #include "base/slice.h" #include "log/status.h" using ::openmldb::base::Slice; namespace openmldb { namespace log { static Status IOError(const std::string& context, int err_number) { return Status::IOError(context, strerror(err_number)); } class PosixWritableFile : public WritableFile { public: PosixWritableFile(const std::string& fname, FILE* f) : filename_(fname), file_(f) {} ~PosixWritableFile() { if (file_ != NULL) { // Ignoring any potential errors fclose(file_); } } virtual Status Append(const Slice& data) { #if __linux__ size_t r = fwrite_unlocked(data.data(), 1, data.size(), file_); #else size_t r = fwrite(data.data(), 1, data.size(), file_); #endif if (r != data.size()) { return IOError(filename_, errno); } wsize_ += r; return Status::OK(); } virtual Status Close() { Status result; if (fclose(file_) != 0) { result = IOError(filename_, errno); } file_ = NULL; return result; } virtual Status Flush() { #if __linux__ if (fflush_unlocked(file_) != 0) { return IOError(filename_, errno); } #else if (fflush(file_) != 0) { return IOError(filename_, errno); } #endif return Status::OK(); } virtual Status Sync() { #if __linux__ // Ensure new files referred to by the manifest are in the filesystem. if (fflush_unlocked(file_) != 0 || fdatasync(fileno(file_)) != 0) { return IOError(filename_, errno); } #else // Ensure new files referred to by the manifest are in the filesystem. if (fflush(file_) != 0 || fsync(fileno(file_)) != 0) { return IOError(filename_, errno); } #endif return Status::OK(); } private: std::string filename_; FILE* file_; }; WritableFile* NewWritableFile(const std::string& fname, FILE* f) { return new PosixWritableFile(fname, f); } } // namespace log } // namespace openmldb
/////////////////////////////////////////////////////////////// // BastArtifact.cpp // BastArtefact - артефакт мочалка /////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "BastArtifact.h" #include "xrPhysics/PhysicsShell.h" #include "xrPhysics/ExtendedGeom.h" #include "ParticlesObject.h" CBastArtefact::CBastArtefact(void) : m_pHitedEntity(nullptr) { m_fImpulseThreshold = 10.f; m_fRadius = 10.f; m_fStrikeImpulse = 15.f; m_bStrike = false; m_AttakingEntity = nullptr; m_fEnergy = 0.f; m_fEnergyMax = m_fStrikeImpulse * 100.f; m_fEnergyDecreasePerTime = 1.1f; } CBastArtefact::~CBastArtefact(void) {} //вызывается при столкновении мочалки с чем-то void CBastArtefact::ObjectContactCallback( bool& /**do_colide**/, bool bo1, dContact& c, SGameMtl* /*material_1*/, SGameMtl* /*material_2*/) { dxGeomUserData* l_pUD1 = NULL; dxGeomUserData* l_pUD2 = NULL; l_pUD1 = PHRetrieveGeomUserData(c.geom.g1); l_pUD2 = PHRetrieveGeomUserData(c.geom.g2); if (!l_pUD1 || !l_pUD2) return; //определить кто есть кто, из двух столкнувшихся предметов CBastArtefact* pBastArtefact = l_pUD1 ? smart_cast<CBastArtefact*>(l_pUD1->ph_ref_object) : NULL; if (!pBastArtefact) pBastArtefact = l_pUD2 ? smart_cast<CBastArtefact*>(l_pUD2->ph_ref_object) : NULL; if (!pBastArtefact) return; if (!pBastArtefact->IsAttacking()) return; CEntityAlive* pEntityAlive = NULL; pEntityAlive = l_pUD1 ? smart_cast<CEntityAlive*>(l_pUD1->ph_ref_object) : NULL; if (!pEntityAlive) pEntityAlive = l_pUD2 ? smart_cast<CEntityAlive*>(l_pUD2->ph_ref_object) : NULL; pBastArtefact->BastCollision(pEntityAlive); } void CBastArtefact::BastCollision(CEntityAlive* pEntityAlive) { //попали во что-то живое if (pEntityAlive && pEntityAlive->g_Alive()) { m_AttakingEntity = NULL; m_pHitedEntity = pEntityAlive; if (m_AliveList.size() > 1) { m_bStrike = true; } else { m_bStrike = false; } m_bStrike = true; Fvector vel; vel.set(0, 0, 0); // this->m_pPhysicsShell->set_LinearVel(vel); // this->m_pPhysicsShell->set_AngularVel(vel); } } bool CBastArtefact::net_Spawn(CSE_Abstract* DC) { BOOL result = inherited::net_Spawn(DC); if (!result) return FALSE; m_bStrike = false; m_AttakingEntity = NULL; m_pHitedEntity = NULL; m_AliveList.clear(); return TRUE; } void CBastArtefact::net_Destroy() { inherited::net_Destroy(); m_bStrike = false; m_AttakingEntity = NULL; m_pHitedEntity = NULL; m_AliveList.clear(); } void CBastArtefact::Load(LPCSTR section) { inherited::Load(section); m_fImpulseThreshold = pSettings->r_float(section, "impulse_threshold"); m_fRadius = pSettings->r_float(section, "radius"); m_fStrikeImpulse = pSettings->r_float(section, "strike_impulse"); m_fEnergyMax = pSettings->r_float(section, "energy_max"); m_fEnergyDecreasePerTime = pSettings->r_float(section, "energy_decrease_speed"); m_sParticleName = pSettings->r_string(section, "particle"); } void CBastArtefact::shedule_Update(u32 dt) { inherited::shedule_Update(dt); Fvector P; P.set(Position()); feel_touch_update(P, m_fRadius); } void CBastArtefact::UpdateCLChild() { // Log ("--- A - CBastArtefact",*cName()); // Log ("--- A - CBastArtefact",renderable.xform); //современем энергия по немногу тоже уменьшается if (m_fEnergy > 0) m_fEnergy -= m_fEnergyDecreasePerTime * Device.fTimeDelta; if (getVisible() && m_pPhysicsShell) { if (m_bStrike) { //выбрать жертву, если она еще не выбрана if (!m_AliveList.empty() && m_AttakingEntity == NULL) { CEntityAlive* pEntityToHit = NULL; if (m_AliveList.size() > 1) { do { int rnd = ::Random.randI(m_AliveList.size()); pEntityToHit = m_AliveList[rnd]; } while (pEntityToHit == m_pHitedEntity); } else { pEntityToHit = m_AliveList.front(); } m_AttakingEntity = pEntityToHit; } } if (m_AttakingEntity) { if (m_AttakingEntity->g_Alive() && m_fEnergy > m_fStrikeImpulse) { m_fEnergy -= m_fStrikeImpulse; //бросить артефакт на выбранную цель Fvector dir; m_AttakingEntity->Center(dir); dir.sub(this->Position()); dir.y += ::Random.randF(-0.05f, 0.5f); m_pPhysicsShell->applyImpulse(dir, m_fStrikeImpulse * Device.fTimeDelta * m_pPhysicsShell->getMass()); } else { m_AttakingEntity = NULL; m_bStrike = false; } } if (m_fEnergy > 0 && ::Random.randF(0.f, 1.0f) < (m_fEnergy / (m_fStrikeImpulse * 100.f))) { CParticlesObject* pStaticPG; pStaticPG = CParticlesObject::Create(*m_sParticleName, TRUE); Fmatrix pos; pos.set(XFORM()); Fvector vel; // vel.sub(Position(),ps_Element(0).vPosition); // vel.div((Level().timeServer()-ps_Element(0).dwTime)/1000.f); vel.set(0, 0, 0); pStaticPG->UpdateParent(pos, vel); pStaticPG->Play(false); } } else if (H_Parent()) XFORM().set(H_Parent()->XFORM()); } // void CBastArtefact::Hit(float P, Fvector &dir, // IGameObject* who, s16 element, // Fvector position_in_object_space, // float impulse, // ALife::EHitType hit_type) void CBastArtefact::Hit(SHit* pHDS) { SHit HDS = *pHDS; if (HDS.impulse > m_fImpulseThreshold && !m_AliveList.empty()) { m_bStrike = true; m_AttakingEntity = m_pHitedEntity = NULL; m_fEnergy += m_fStrikeImpulse * HDS.impulse; if (m_fEnergy > m_fEnergyMax) m_fEnergy = m_fEnergyMax; //чтоб выстрел не повлиял на траекторию полета артефакта HDS.impulse = 0; } // inherited::Hit(P, dir, who, element, position_in_object_space, impulse, hit_type); inherited::Hit(&HDS); } //объект можно поднять только в спокойном состоянии bool CBastArtefact::Useful() const { if (m_fEnergy > 0) return false; else return true; } void CBastArtefact::feel_touch_new(IGameObject* O) { CEntityAlive* pEntityAlive = smart_cast<CEntityAlive*>(O); if (pEntityAlive && pEntityAlive->g_Alive()) { m_AliveList.push_back(pEntityAlive); } } void CBastArtefact::feel_touch_delete(IGameObject* O) { CEntityAlive* pEntityAlive = smart_cast<CEntityAlive*>(O); if (pEntityAlive) { m_AliveList.erase(std::find(m_AliveList.begin(), m_AliveList.end(), pEntityAlive)); } } bool CBastArtefact::feel_touch_contact(IGameObject* O) { CEntityAlive* pEntityAlive = smart_cast<CEntityAlive*>(O); if (pEntityAlive && pEntityAlive->g_Alive()) return true; else return false; } void CBastArtefact::setup_physic_shell() { inherited::setup_physic_shell(); m_pPhysicsShell->set_PhysicsRefObject(this); m_pPhysicsShell->set_ObjectContactCallback(ObjectContactCallback); m_pPhysicsShell->set_ContactCallback(NULL); }
#include <dae.h> #include <dae/daeDom.h> #include <1.5/dom/domJoint_limits.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> namespace ColladaDOM150 { daeElementRef domJoint_limits::create(DAE& dae) { domJoint_limitsRef ref = new domJoint_limits(dae); return ref; } daeMetaElement * domJoint_limits::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "joint_limits" ); meta->registerClass(domJoint_limits::create); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 0, 1 ); mea->setName( "min" ); mea->setOffset( daeOffsetOf(domJoint_limits,elemMin) ); mea->setElementType( domMinmax::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "max" ); mea->setOffset( daeOffsetOf(domJoint_limits,elemMax) ); mea->setElementType( domMinmax::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 1 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domJoint_limits)); meta->validate(); return meta; } } // ColladaDOM150
#include "Utils_WS.h" #include "TMath.h" #include <Math/DistFunc.h> #include <Math/QuantFuncMathCore.h> namespace Utils_WS { double pvalueToSignificance(double p) { // return TMath::Sqrt(2.0) * TMath::ErfInverse(1.0 - 2.0 * p); return TMath::NormQuantile(1.0 - p); } double significanceToPvalue(double z) { // return 0.5 * (1.0 - TMath::Erf(z / TMath::Sqrt(2.0))); return 1.0 - ROOT::Math::gaussian_cdf(z); } double q0ToSignificance(double q0) { return TMath::Sqrt(q0); } double nllToQ0(double nllMu0, double nllMuHat, double muHat) { double q0 = (muHat < 0) ? 0 : (2 * (nllMu0 - nllMuHat)); if (q0 < 0.) q0 = 0; return q0; } }
// ----------------------------------------------------------------------------------------- // NVEnc by rigaya // ----------------------------------------------------------------------------------------- // The MIT License // // Copyright (c) 2014-2016 rigaya // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ------------------------------------------------------------------------------------------ #include <stdlib.h> #include <string.h> #include "auo_frm.h" #include "auo_util.h" const int NEW_LINE_THRESHOLD = 125; const int MAKE_NEW_LINE_THRESHOLD = 140; static inline int check_log_type(char *mes) { if (strstr(mes, "warning")) return LOG_WARNING; if (strstr(mes, "error")) return LOG_ERROR; return LOG_INFO; } static inline void add_line_to_cache(LOG_CACHE *cache_line, const char *mes) { if (cache_line->idx >= cache_line->max_line) { //メモリ不足なら再確保 if (NULL != (cache_line->lines = (char **)realloc(cache_line->lines, sizeof(cache_line->lines[0]) * cache_line->max_line * 2))) { memset(&cache_line->lines[cache_line->max_line], 0, sizeof(cache_line->lines[0]) * cache_line->max_line); cache_line->max_line *= 2; } } if (cache_line->lines) { //一行のデータを格納 const int line_len = strlen(mes) + 1; char *line_ptr = (char *)malloc(line_len * sizeof(line_ptr[0])); memcpy(line_ptr, mes, line_len); cache_line->lines[cache_line->idx] = line_ptr; cache_line->idx++; } } void release_log_cache(LOG_CACHE *log_cache) { if (log_cache && log_cache->lines) { for (int i = 0; i < log_cache->idx; i++) if (log_cache->lines[i]) free(log_cache->lines[i]); free(log_cache->lines); log_cache->lines = NULL; log_cache->idx = 0; } } //LOG_CACHEの初期化、成功->0, 失敗->1 int init_log_cache(LOG_CACHE *log_cache) { release_log_cache(log_cache); log_cache->idx = 0; log_cache->max_line = 64; return NULL == (log_cache->lines = (char **)calloc(log_cache->max_line, sizeof(log_cache->lines[0]))); } //長すぎたら適当に折り返す static int write_log_enc_mes_line(char *const mes, LOG_CACHE *cache_line) { const int mes_len = strlen(mes); const int mes_type = check_log_type(mes); char *const fin = mes + mes_len; char *const prefix_ptr = strstr(mes, "]: "); const int prefix_len = (prefix_ptr) ? prefix_ptr - mes + strlen("]: ") : 0; char *p = mes, *q = NULL; BOOL flag_continue = FALSE; do { const int threshold = NEW_LINE_THRESHOLD - (p != mes) * prefix_len; flag_continue = mes_len >= MAKE_NEW_LINE_THRESHOLD && (p + threshold) < fin && (q = strrchr(p, ' ', threshold)) != NULL; if (flag_continue) *q = '\0'; if (p != mes) for (char *const prefix_adjust = p - prefix_len; p > prefix_adjust; p--) *(p-1) = ' '; (cache_line) ? add_line_to_cache(cache_line, p) : write_log_line(mes_type, p, true); p=q+1; } while (flag_continue); return mes_len; } void write_log_enc_mes(char *const msg, DWORD *log_len, int total_drop, int current_frames, LOG_CACHE *cache_line) { char *a, *b, *mes = msg; char * const fin = mes + *log_len; //null文字の位置 *fin = '\0'; while ((a = strchr(mes, '\n')) != NULL) { if ((b = strrchr(mes, '\r', a - mes - 2)) != NULL) mes = b + 1; *a = '\0'; write_log_enc_mes_line(mes, cache_line); mes = a + 1; } if ((a = strrchr(mes, '\r', fin - mes - 1)) != NULL) { b = a - 1; while (*b == ' ' || *b == '\r') b--; *(b+1) = '\0'; if ((b = strrchr(mes, '\r', b - mes - 2)) != NULL) mes = b + 1; set_window_title_enc_mes(mes, total_drop, current_frames); mes = a + 1; } if (mes == msg && *log_len) mes += write_log_enc_mes_line(mes, cache_line); memmove(msg, mes, ((*log_len = fin - mes) + 1) * sizeof(msg[0])); } void write_args(const char *args) { size_t len = strlen(args); char *const c = (char *)malloc((len+1)*sizeof(c[0])); char *const fin = c + len; memcpy(c, args, (len+1)*sizeof(c[0])); char *p = c; for (char *q = NULL; p + NEW_LINE_THRESHOLD < fin && (q = strrchr(p, ' ', NEW_LINE_THRESHOLD)) != NULL; p = q+1) { *q = '\0'; write_log_line(LOG_INFO, p); } write_log_line(LOG_INFO, p); free(c); } void write_log_exe_mes(char *const msg, DWORD *log_len, const char *exename, LOG_CACHE *cache_line) { char *a, *b, *mes = msg; char * const fin = mes + *log_len; //null文字の位置 char * buffer = NULL; DWORD buffer_len = 0; *fin = '\0'; while ((a = strchr(mes, '\n')) != NULL) { if ((b = strrchr(mes, '\r', a - mes - 2)) != NULL) mes = b + 1; *a = '\0'; write_log_enc_mes_line(mes, cache_line); mes = a + 1; } if ((a = strrchr(mes, '\r', fin - mes - 1)) != NULL) { b = a - 1; while (*b == ' ' || *b == '\r') b--; *(b+1) = '\0'; if ((b = strrchr(mes, '\r', b - mes - 2)) != NULL) mes = b + 1; if (exename) { if (buffer_len == 0) buffer_len = *log_len + strlen(exename) + 3; if (buffer != NULL || NULL != (buffer = (char*)malloc(buffer_len * sizeof(buffer[0])))) { sprintf_s(buffer, buffer_len, "%s: %s", exename, mes); set_window_title(buffer); } } mes = a + 1; } if (mes == msg && *log_len) mes += write_log_enc_mes_line(mes, cache_line); memmove(msg, mes, ((*log_len = fin - mes) + 1) * sizeof(msg[0])); if (buffer) free(buffer); }
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkMultiBlockDataSetAlgorithmWrap.h" #include "vtkStructuredGridPartitionerWrap.h" #include "vtkObjectWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkStructuredGridPartitionerWrap::ptpl; VtkStructuredGridPartitionerWrap::VtkStructuredGridPartitionerWrap() { } VtkStructuredGridPartitionerWrap::VtkStructuredGridPartitionerWrap(vtkSmartPointer<vtkStructuredGridPartitioner> _native) { native = _native; } VtkStructuredGridPartitionerWrap::~VtkStructuredGridPartitionerWrap() { } void VtkStructuredGridPartitionerWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkStructuredGridPartitioner").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("StructuredGridPartitioner").ToLocalChecked(), ConstructorGetter); } void VtkStructuredGridPartitionerWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkStructuredGridPartitionerWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkMultiBlockDataSetAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkMultiBlockDataSetAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkStructuredGridPartitionerWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "DuplicateNodesOff", DuplicateNodesOff); Nan::SetPrototypeMethod(tpl, "duplicateNodesOff", DuplicateNodesOff); Nan::SetPrototypeMethod(tpl, "DuplicateNodesOn", DuplicateNodesOn); Nan::SetPrototypeMethod(tpl, "duplicateNodesOn", DuplicateNodesOn); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetDuplicateNodes", GetDuplicateNodes); Nan::SetPrototypeMethod(tpl, "getDuplicateNodes", GetDuplicateNodes); Nan::SetPrototypeMethod(tpl, "GetNumberOfGhostLayers", GetNumberOfGhostLayers); Nan::SetPrototypeMethod(tpl, "getNumberOfGhostLayers", GetNumberOfGhostLayers); Nan::SetPrototypeMethod(tpl, "GetNumberOfPartitions", GetNumberOfPartitions); Nan::SetPrototypeMethod(tpl, "getNumberOfPartitions", GetNumberOfPartitions); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetDuplicateNodes", SetDuplicateNodes); Nan::SetPrototypeMethod(tpl, "setDuplicateNodes", SetDuplicateNodes); Nan::SetPrototypeMethod(tpl, "SetNumberOfGhostLayers", SetNumberOfGhostLayers); Nan::SetPrototypeMethod(tpl, "setNumberOfGhostLayers", SetNumberOfGhostLayers); Nan::SetPrototypeMethod(tpl, "SetNumberOfPartitions", SetNumberOfPartitions); Nan::SetPrototypeMethod(tpl, "setNumberOfPartitions", SetNumberOfPartitions); #ifdef VTK_NODE_PLUS_VTKSTRUCTUREDGRIDPARTITIONERWRAP_INITPTPL VTK_NODE_PLUS_VTKSTRUCTUREDGRIDPARTITIONERWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkStructuredGridPartitionerWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkStructuredGridPartitioner> native = vtkSmartPointer<vtkStructuredGridPartitioner>::New(); VtkStructuredGridPartitionerWrap* obj = new VtkStructuredGridPartitionerWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkStructuredGridPartitionerWrap::DuplicateNodesOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DuplicateNodesOff(); } void VtkStructuredGridPartitionerWrap::DuplicateNodesOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DuplicateNodesOn(); } void VtkStructuredGridPartitionerWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkStructuredGridPartitionerWrap::GetDuplicateNodes(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetDuplicateNodes(); info.GetReturnValue().Set(Nan::New(r)); } void VtkStructuredGridPartitionerWrap::GetNumberOfGhostLayers(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfGhostLayers(); info.GetReturnValue().Set(Nan::New(r)); } void VtkStructuredGridPartitionerWrap::GetNumberOfPartitions(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfPartitions(); info.GetReturnValue().Set(Nan::New(r)); } void VtkStructuredGridPartitionerWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkStructuredGridPartitionerWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); vtkStructuredGridPartitioner * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkStructuredGridPartitionerWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkStructuredGridPartitionerWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkStructuredGridPartitionerWrap *w = new VtkStructuredGridPartitionerWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkStructuredGridPartitionerWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkStructuredGridPartitioner * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkStructuredGridPartitionerWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkStructuredGridPartitionerWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkStructuredGridPartitionerWrap *w = new VtkStructuredGridPartitionerWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkStructuredGridPartitionerWrap::SetDuplicateNodes(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetDuplicateNodes( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkStructuredGridPartitionerWrap::SetNumberOfGhostLayers(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetNumberOfGhostLayers( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkStructuredGridPartitionerWrap::SetNumberOfPartitions(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkStructuredGridPartitionerWrap *wrapper = ObjectWrap::Unwrap<VtkStructuredGridPartitionerWrap>(info.Holder()); vtkStructuredGridPartitioner *native = (vtkStructuredGridPartitioner *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetNumberOfPartitions( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); }
/* * Copyright 2014-present IVK JSC. 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 "BufferFactory.h" #include <decaf/internal/nio/ByteArrayBuffer.h> #include <decaf/internal/nio/CharArrayBuffer.h> #include <decaf/internal/nio/DoubleArrayBuffer.h> #include <decaf/internal/nio/FloatArrayBuffer.h> #include <decaf/internal/nio/IntArrayBuffer.h> #include <decaf/internal/nio/LongArrayBuffer.h> #include <decaf/internal/nio/ShortArrayBuffer.h> using namespace decaf; using namespace decaf::internal; using namespace decaf::internal::nio; using namespace decaf::nio; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// ByteBuffer *BufferFactory::createByteBuffer(int capacity) { try { return new ByteArrayBuffer(capacity); } DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCHALL_THROW(IndexOutOfBoundsException) } //////////////////////////////////////////////////////////////////////////////// ByteBuffer *BufferFactory::createByteBuffer(unsigned char *buffer, int size, int offset, int length) { try { return new ByteArrayBuffer(buffer, size, offset, length, false); } DECAF_CATCH_RETHROW(NullPointerException) DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCH_EXCEPTION_CONVERT(Exception, NullPointerException) DECAF_CATCHALL_THROW(NullPointerException) } //////////////////////////////////////////////////////////////////////////////// ByteBuffer *BufferFactory::createByteBuffer(std::vector<unsigned char> &buffer) { try { return new ByteArrayBuffer(&buffer[0], (int)buffer.size(), 0, (int)buffer.size(), false); } DECAF_CATCH_RETHROW(Exception) DECAF_CATCHALL_THROW(Exception) } //////////////////////////////////////////////////////////////////////////////// CharBuffer *BufferFactory::createCharBuffer(int capacity) { try { return new CharArrayBuffer(capacity); } DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCHALL_THROW(IndexOutOfBoundsException) } //////////////////////////////////////////////////////////////////////////////// CharBuffer *BufferFactory::createCharBuffer(char *buffer, int size, int offset, int length) { try { return new CharArrayBuffer(buffer, size, offset, length, false); } DECAF_CATCH_RETHROW(NullPointerException) DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCH_EXCEPTION_CONVERT(Exception, NullPointerException) DECAF_CATCHALL_THROW(NullPointerException) } //////////////////////////////////////////////////////////////////////////////// CharBuffer *BufferFactory::createCharBuffer(std::vector<char> &buffer) { try { return new CharArrayBuffer(&buffer[0], (int)buffer.size(), 0, (int)buffer.size(), false); } DECAF_CATCH_RETHROW(Exception) DECAF_CATCHALL_THROW(Exception) } //////////////////////////////////////////////////////////////////////////////// DoubleBuffer *BufferFactory::createDoubleBuffer(int capacity) { try { return new DoubleArrayBuffer(capacity); } DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCHALL_THROW(IndexOutOfBoundsException) } //////////////////////////////////////////////////////////////////////////////// DoubleBuffer *BufferFactory::createDoubleBuffer(double *buffer, int size, int offset, int length) { try { return new DoubleArrayBuffer(buffer, size, offset, length, false); } DECAF_CATCH_RETHROW(NullPointerException) DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCH_EXCEPTION_CONVERT(Exception, NullPointerException) DECAF_CATCHALL_THROW(NullPointerException) } //////////////////////////////////////////////////////////////////////////////// DoubleBuffer *BufferFactory::createDoubleBuffer(std::vector<double> &buffer) { try { return new DoubleArrayBuffer(&buffer[0], (int)buffer.size(), 0, (int)buffer.size(), false); } DECAF_CATCH_RETHROW(Exception) DECAF_CATCHALL_THROW(Exception) } //////////////////////////////////////////////////////////////////////////////// FloatBuffer *BufferFactory::createFloatBuffer(int capacity) { try { return new FloatArrayBuffer(capacity); } DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCHALL_THROW(IndexOutOfBoundsException) } //////////////////////////////////////////////////////////////////////////////// FloatBuffer *BufferFactory::createFloatBuffer(float *buffer, int size, int offset, int length) { try { return new FloatArrayBuffer(buffer, size, offset, length, false); } DECAF_CATCH_RETHROW(NullPointerException) DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCH_EXCEPTION_CONVERT(Exception, NullPointerException) DECAF_CATCHALL_THROW(NullPointerException) } //////////////////////////////////////////////////////////////////////////////// FloatBuffer *BufferFactory::createFloatBuffer(std::vector<float> &buffer) { try { return new FloatArrayBuffer(&buffer[0], (int)buffer.size(), 0, (int)buffer.size(), false); } DECAF_CATCH_RETHROW(Exception) DECAF_CATCHALL_THROW(Exception) } //////////////////////////////////////////////////////////////////////////////// LongBuffer *BufferFactory::createLongBuffer(int capacity) { try { return new LongArrayBuffer(capacity); } DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCHALL_THROW(IndexOutOfBoundsException) } //////////////////////////////////////////////////////////////////////////////// LongBuffer *BufferFactory::createLongBuffer(long long *buffer, int size, int offset, int length) { try { return new LongArrayBuffer(buffer, size, offset, length, false); } DECAF_CATCH_RETHROW(NullPointerException) DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCH_EXCEPTION_CONVERT(Exception, NullPointerException) DECAF_CATCHALL_THROW(NullPointerException) } //////////////////////////////////////////////////////////////////////////////// LongBuffer *BufferFactory::createLongBuffer(std::vector<long long> &buffer) { try { return new LongArrayBuffer(&buffer[0], (int)buffer.size(), 0, (int)buffer.size(), false); } DECAF_CATCH_RETHROW(Exception) DECAF_CATCHALL_THROW(Exception) } //////////////////////////////////////////////////////////////////////////////// IntBuffer *BufferFactory::createIntBuffer(int capacity) { try { return new IntArrayBuffer(capacity); } DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCHALL_THROW(IndexOutOfBoundsException) } //////////////////////////////////////////////////////////////////////////////// IntBuffer *BufferFactory::createIntBuffer(int *buffer, int size, int offset, int length) { try { return new IntArrayBuffer(buffer, size, offset, length, false); } DECAF_CATCH_RETHROW(NullPointerException) DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCH_EXCEPTION_CONVERT(Exception, NullPointerException) DECAF_CATCHALL_THROW(NullPointerException) } //////////////////////////////////////////////////////////////////////////////// IntBuffer *BufferFactory::createIntBuffer(std::vector<int> &buffer) { try { return new IntArrayBuffer(&buffer[0], (int)buffer.size(), 0, (int)buffer.size(), false); } DECAF_CATCH_RETHROW(Exception) DECAF_CATCHALL_THROW(Exception) } //////////////////////////////////////////////////////////////////////////////// ShortBuffer *BufferFactory::createShortBuffer(int capacity) { try { return new ShortArrayBuffer(capacity); } DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCHALL_THROW(IndexOutOfBoundsException) } //////////////////////////////////////////////////////////////////////////////// ShortBuffer *BufferFactory::createShortBuffer(short *buffer, int size, int offset, int length) { try { return new ShortArrayBuffer(buffer, size, offset, length, false); } DECAF_CATCH_RETHROW(NullPointerException) DECAF_CATCH_RETHROW(IndexOutOfBoundsException) DECAF_CATCH_EXCEPTION_CONVERT(Exception, NullPointerException) DECAF_CATCHALL_THROW(NullPointerException) } //////////////////////////////////////////////////////////////////////////////// ShortBuffer *BufferFactory::createShortBuffer(std::vector<short> &buffer) { try { return new ShortArrayBuffer(&buffer[0], (int)buffer.size(), 0, (int)buffer.size(), false); } DECAF_CATCH_RETHROW(Exception) DECAF_CATCHALL_THROW(Exception) }
// Copyright (c) 2011-2016 The Bitcoin Core developers // Copyright (c) 2017-2019 The Raven Core developers // Copyright (c) 2020 The Chellit Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode _mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(_mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *_model) { this->model = _model; if(!_model) return; mapper->setModel(_model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Chellit address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &_address) { this->address = _address; ui->addressEdit->setText(_address); }
#define USE_SWIZZLE #include "CustomMaterialParameterFS.h" #include "../../../../General/Template/TShaderMacro.h" using namespace PaintsNow; CustomMaterialParameterFS::CustomMaterialParameterFS() { description = TShared<CustomMaterialDescription>::From(new CustomMaterialDescription()); } String CustomMaterialParameterFS::GetShaderText() { if (description->code.empty()) { return UnifyShaderCode( outputColor = float3(1.0, 1.0, 1.0); alpha = 1.0; outputNormal = float3(0.0, 0.0, 1.0); metallic = 0.0; roughness = 1.0; occlusion = 1.0; ); } else { return description->code; } } TObject<IReflect>& CustomMaterialParameterFS::operator () (IReflect& reflect) { BaseClass::operator () (reflect); if (reflect.IsReflectProperty()) { description->ReflectExternal(reflect, instanceData); ReflectProperty(outputColor)[BindOutput(BindOutput::LOCAL)]; ReflectProperty(outputNormal)[BindOutput(BindOutput::LOCAL)]; ReflectProperty(alpha)[BindOutput(BindOutput::LOCAL)]; ReflectProperty(metallic)[BindOutput(BindOutput::LOCAL)]; ReflectProperty(roughness)[BindOutput(BindOutput::LOCAL)]; ReflectProperty(occlusion)[BindOutput(BindOutput::LOCAL)]; } return *this; }
#include "core_headers.h" //TODO : Currently, any strings with spaces will cause the star file (but not binary) reader to break - needs to be fixed. // ADDING A NEW COLUMN // ---------------------- // See top of cistem_parameters.cpp for documentation describing how to add a new column cisTEMStarFileReader::cisTEMStarFileReader() { Reset(); } cisTEMStarFileReader::cisTEMStarFileReader(wxString wanted_filename, ArrayOfcisTEMParameterLines *alternate_cached_parameters_pointer, bool exclude_negative_film_numbers) { Reset(); if (alternate_cached_parameters_pointer == NULL) { cached_parameters = new ArrayOfcisTEMParameterLines; using_external_array = false; } else { cached_parameters = alternate_cached_parameters_pointer; using_external_array = true; } ReadTextFile(wanted_filename, NULL, alternate_cached_parameters_pointer, exclude_negative_film_numbers); } void cisTEMStarFileReader::Reset() { filename = ""; input_text_file = NULL; binary_file_read_buffer = NULL; binary_file_size = 0; current_position_in_stack = 0; current_column = 0; cached_parameters = NULL; using_external_array = false; ResetColumnPositions(); parameters_that_were_read.SetAllToFalse(); } void cisTEMStarFileReader::ResetColumnPositions() { position_in_stack_column = -1; image_is_active_column = -1; psi_column = -1; theta_column = -1; phi_column = -1; x_shift_column = -1; y_shift_column = -1; defocus_1_column = -1; defocus_2_column = -1; defocus_angle_column = -1; phase_shift_column = -1; occupancy_column = -1; logp_column = -1; sigma_column = -1; score_column = -1; score_change_column = -1; pixel_size_column = -1; microscope_voltage_kv_column = -1; microscope_spherical_aberration_mm_column = -1; amplitude_contrast_column = -1; beam_tilt_x_column = -1; beam_tilt_y_column = -1; image_shift_x_column = -1; image_shift_y_column = -1; best_2d_class_column = -1; beam_tilt_group_column = -1; particle_group_column = -1; assigned_subset_column = -1; pre_exposure_column = -1; total_exposure_column = -1; original_image_filename_column = -1; reference_3d_filename_column = -1; stack_filename_column = -1; } cisTEMStarFileReader::~cisTEMStarFileReader() { Close(); } void cisTEMStarFileReader::Open(wxString wanted_filename, ArrayOfcisTEMParameterLines *alternate_cached_parameters_pointer, bool read_as_binary) { Close(); if (cached_parameters != NULL && using_external_array == false) { delete cached_parameters; cached_parameters = NULL; } filename = wanted_filename; if (read_as_binary == false) // read it as a text based star file { input_text_file = new wxTextFile(wanted_filename); input_text_file->Open(); //if (input_text_file_stream->IsOk() == false) if (input_text_file->IsOpened() == false) { MyPrintWithDetails("Error: Cannot open star file (%s) for read\n", wanted_filename); DEBUG_ABORT; } } else // binary input - read the whole file into memory.. { FILE *binary_file = fopen(filename.ToStdString().c_str(), "rb"); fseek(binary_file, 0, SEEK_END); binary_file_size = ftell(binary_file); fseek(binary_file, 0, SEEK_SET); if (binary_file_read_buffer != NULL) delete [] binary_file_read_buffer; binary_file_read_buffer = new char[binary_file_size]; fread(binary_file_read_buffer, 1, binary_file_size, binary_file); fclose(binary_file); } if (alternate_cached_parameters_pointer == NULL) { cached_parameters = new ArrayOfcisTEMParameterLines; using_external_array = false; } else { cached_parameters = alternate_cached_parameters_pointer; using_external_array = true; } } void cisTEMStarFileReader::Close() { if (cached_parameters != NULL && using_external_array == false) { delete cached_parameters; cached_parameters = NULL; } if (input_text_file != NULL) { delete input_text_file; input_text_file = NULL; } if (binary_file_read_buffer != NULL) { delete [] binary_file_read_buffer; binary_file_read_buffer = NULL; binary_file_size = -1; } binary_file_size = 0; } bool cisTEMStarFileReader::ExtractParametersFromLine(wxString &wanted_line, wxString *error_string, bool exclude_negative_film_numbers) { /*! \brief Parse a line read from a star file with checks on numeric convertibility. * * Detailed: * Each potential variable has a default column i.d. of -1. If this is not changed, this method will not try to parse the variable, * but instead will set it's respective default. */ // extract info. wxArrayString all_tokens; wxStringTokenizer tokens(wanted_line); cisTEMParameterLine temp_parameters; double temp_double; long temp_long; wxString current_token; wxString string_buffer; while (tokens.HasMoreTokens() == true) { current_token = tokens.GetNextToken(); all_tokens.Add(current_token); } // start with image is active, because sometimes we can just stop.. // image is active if (image_is_active_column == -1) temp_parameters.image_is_active = 1.0; else { if (all_tokens[image_is_active_column].ToLong(&temp_long) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[image_is_active_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[image_is_active_column]); return false; } temp_parameters.image_is_active = int(temp_long); } if (temp_parameters.image_is_active < 0 && exclude_negative_film_numbers == true) return true; // position in stack if (position_in_stack_column == -1) temp_double = -1; else if (all_tokens[position_in_stack_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[position_in_stack_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[position_in_stack_column]); return false; } temp_parameters.position_in_stack = int(temp_double); // phi if (phi_column == -1) temp_double = 0.0; else if (all_tokens[phi_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[phi_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[phi_column]); return false; } temp_parameters.phi = float(temp_double); // theta if (theta_column == -1) temp_double = 0.0; else if (all_tokens[theta_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[theta_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[theta_column]); return false; } temp_parameters.theta = float(temp_double); // psi if (psi_column == -1) temp_double = 0.0; else if (all_tokens[psi_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[psi_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[psi_column]); return false; } temp_parameters.psi = float(temp_double); // xshift if (x_shift_column == -1) temp_double = 0.0; else if (all_tokens[x_shift_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[x_shift_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[x_shift_column]); return false; } temp_parameters.x_shift = float(temp_double); // yshift if (y_shift_column == -1) temp_double = 0.0; else if (all_tokens[y_shift_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[y_shift_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[y_shift_column]); return false; } temp_parameters.y_shift = float(temp_double); // defocus1 if (all_tokens[defocus_1_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[defocus_1_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[defocus_1_column]); return false; } temp_parameters.defocus_1 = float(temp_double); // defocus2 if (all_tokens[defocus_2_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[defocus_2_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[defocus_2_column]); return false; } temp_parameters.defocus_2 = float(temp_double); // defocus_angle if (all_tokens[defocus_angle_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[defocus_angle_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[defocus_angle_column]); return false; } temp_parameters.defocus_angle = float(temp_double); // phase_shift if (phase_shift_column == -1) temp_parameters.phase_shift = 0.0; else { if (all_tokens[phase_shift_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[phase_shift_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[phase_shift_column]); return false; } temp_parameters.phase_shift = deg_2_rad(float(temp_double)); } // occupancy if (occupancy_column == -1) temp_parameters.occupancy = 100.0f; else { if (all_tokens[occupancy_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[occupancy_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[occupancy_column]); return false; } temp_parameters.occupancy = float(temp_double); } // logp if (logp_column == -1) temp_parameters.logp = 100.0f; else { if (all_tokens[logp_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[logp_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[logp_column]); return false; } temp_parameters.logp = float(temp_double); } // sigma if (sigma_column == -1) temp_parameters.sigma = 10.0f; else { if (all_tokens[sigma_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[sigma_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[sigma_column]); return false; } temp_parameters.sigma = float(temp_double); } // score if (score_column == -1) temp_parameters.score = 0.0f; else { if (all_tokens[score_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[score_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[score_column]); return false; } temp_parameters.score = float(temp_double); //wxPrintf("Score = %f, image_is_active = %i, exclude negative = %s\n", temp_parameters.score, temp_parameters.image_is_active, BoolToYesNo(exclude_negative_film_numbers)); } // score_change if (score_change_column == -1) temp_parameters.score_change = 0.0f; else { if (all_tokens[score_change_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[score_change_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[score_change_column]); return false; } temp_parameters.score_change = float(temp_double); } // pixel_size if (pixel_size_column == -1) temp_parameters.pixel_size = 0.0f; else { if (all_tokens[pixel_size_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[pixel_size_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[pixel_size_column]); return false; } temp_parameters.pixel_size = float(temp_double); } // voltage if (microscope_voltage_kv_column == -1) temp_parameters.microscope_voltage_kv = 0.0f; else { if (all_tokens[microscope_voltage_kv_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[microscope_voltage_kv_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[microscope_voltage_kv_column]); return false; } temp_parameters.microscope_voltage_kv = float(temp_double); } // Cs if ( microscope_spherical_aberration_mm_column == -1) temp_parameters.microscope_spherical_aberration_mm = 2.7f; else { if (all_tokens[microscope_spherical_aberration_mm_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[microscope_spherical_aberration_mm_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[microscope_spherical_aberration_mm_column]); return false; } temp_parameters.microscope_spherical_aberration_mm = float(temp_double); } // amplitude_contrast if ( amplitude_contrast_column == -1) temp_parameters.amplitude_contrast = 0.07f; else { if (all_tokens[amplitude_contrast_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[amplitude_contrast_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[amplitude_contrast_column]); return false; } temp_parameters.amplitude_contrast = float(temp_double); } // beam_tilt_x if ( beam_tilt_x_column == -1) temp_parameters.beam_tilt_x = 0.0f; else { if (all_tokens[beam_tilt_x_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[beam_tilt_x_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[beam_tilt_x_column]); return false; } temp_parameters.beam_tilt_x = float(temp_double); } // beam_tilt_y if ( beam_tilt_y_column == -1) temp_parameters.beam_tilt_y = 0.0f; else { if (all_tokens[beam_tilt_y_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[beam_tilt_y_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[beam_tilt_y_column]); return false; } temp_parameters.beam_tilt_y = float(temp_double); } // image_shift_x if ( image_shift_x_column == -1) temp_parameters.image_shift_x = 0.0f; else { if (all_tokens[image_shift_x_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[image_shift_x_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[image_shift_x_column]); return false; } temp_parameters.image_shift_x = float(temp_double); } // image_shift_y if ( image_shift_y_column == -1) temp_parameters.image_shift_y = 0.0f; else { if (all_tokens[image_shift_y_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[image_shift_y_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[image_shift_y_column]); return false; } temp_parameters.image_shift_y = float(temp_double); } // best 2D class if ( best_2d_class_column == -1) temp_parameters.best_2d_class = 0; else { if (all_tokens[best_2d_class_column].ToLong(&temp_long) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[best_2d_class_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[best_2d_class_column]); return false; } temp_parameters.best_2d_class = int(temp_long); } // beam tilt group if ( beam_tilt_group_column == -1) temp_parameters.beam_tilt_group = 0; else { if (all_tokens[beam_tilt_group_column].ToLong(&temp_long) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[beam_tilt_group_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[beam_tilt_group_column]); return false; } temp_parameters.beam_tilt_group = int(temp_long); } // particle group if ( particle_group_column == -1) temp_parameters.particle_group = 0; else { if (all_tokens[particle_group_column].ToLong(&temp_long) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[particle_group_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[particle_group_column]); return false; } temp_parameters.particle_group = int(temp_long); } // assigned subset (for half-dataset refinement, or half map FSCs, etc) if ( assigned_subset_column == -1) temp_parameters.assigned_subset = 0; else { if (all_tokens[assigned_subset_column].ToLong(&temp_long) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[assigned_subset_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[assigned_subset_column]); return false; } temp_parameters.assigned_subset = int(temp_long); } // pre exposure if ( pre_exposure_column == -1) temp_parameters.pre_exposure = 0.0f; else { if (all_tokens[pre_exposure_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[pre_exposure_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[pre_exposure_column]); return false; } temp_parameters.pre_exposure = float(temp_double); } // total exposure if ( total_exposure_column == -1) temp_parameters.total_exposure = 0.0f; else { if (all_tokens[total_exposure_column].ToDouble(&temp_double) == false) { MyPrintWithDetails("Error: Converting to a number (%s)\n", all_tokens[total_exposure_column]); if (error_string != NULL) *error_string = wxString::Format("Error: Converting to a number (%s)\n", all_tokens[total_exposure_column]); return false; } temp_parameters.total_exposure = float(temp_double); } // stack filename if ( stack_filename_column == -1) temp_parameters.stack_filename = ""; else { temp_parameters.stack_filename = all_tokens[stack_filename_column].Trim(true).Trim(false); if (StripEnclosingSingleQuotesFromString(temp_parameters.stack_filename) == false) { MyPrintfRed("Error: stack file name read as %s is not enclosed in single quotes ('), replacing with blank string\n", temp_parameters.stack_filename); temp_parameters.stack_filename = ""; } } // original_image_filename if ( original_image_filename_column == -1) temp_parameters.original_image_filename = ""; else { temp_parameters.original_image_filename = all_tokens[original_image_filename_column].Trim(true).Trim(false); if (StripEnclosingSingleQuotesFromString(temp_parameters.original_image_filename) == false) { MyPrintfRed("Error: original image file name read as %s is not enclosed in single quotes ('), replacing with blank string\n", temp_parameters.original_image_filename); temp_parameters.original_image_filename = ""; } } // reference_3d_filename if ( reference_3d_filename_column == -1) temp_parameters.reference_3d_filename = ""; else { temp_parameters.reference_3d_filename = all_tokens[reference_3d_filename_column].Trim(true).Trim(false); if (StripEnclosingSingleQuotesFromString(temp_parameters.reference_3d_filename) == false) { MyPrintfRed("Error: reference 3d file name read as %s is not enclosed in single quotes ('), replacing with blank string\n", temp_parameters.reference_3d_filename); temp_parameters.reference_3d_filename = ""; } } cached_parameters->Add(temp_parameters); return true; } bool cisTEMStarFileReader::ReadTextFile(wxString wanted_filename, wxString *error_string, ArrayOfcisTEMParameterLines *alternate_cached_parameters_pointer, bool exclude_negative_film_numbers) { Open(wanted_filename, alternate_cached_parameters_pointer); wxString current_line; //MyDebugAssertTrue(input_text_file_stream != NULL, "FileStream is NULL!"); MyDebugAssertTrue(input_text_file->IsOpened(), "File not open"); bool found_valid_data_block = false; bool found_valid_loop_block = false; input_text_file->GoToLine(-1); // this triggers warning: integer conversion resulted in a change of sign // find a data block //while (input_text_file_stream->Eof() == false) while (input_text_file->Eof() == false) { //current_line = input_text_stream->ReadLine(); current_line = input_text_file->GetNextLine(); current_line = current_line.Trim(true); current_line = current_line.Trim(false); if (current_line.Find("data_") != wxNOT_FOUND) { found_valid_data_block = true; break; } } if (found_valid_data_block == false) { MyPrintWithDetails("Error: Couldn't find a valid data block in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find a valid data block in star file (%s)\n", wanted_filename); return false; } // find a loop block //while (input_text_file_stream->Eof() == false) while (input_text_file->Eof() == false) { //current_line = input_text_stream->ReadLine(); current_line = input_text_file->GetNextLine(); current_line = current_line.Trim(true); current_line = current_line.Trim(false); if (current_line.Find("loop_") != wxNOT_FOUND) { found_valid_loop_block = true; break; } } if (found_valid_loop_block == false) { MyPrintWithDetails("Error: Couldn't find a valid loop block in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find a valid loop block in star file (%s)\n", wanted_filename); return false; } // now we can get headers.. ResetColumnPositions(); //while (input_text_file_stream->Eof() == false) while (input_text_file->Eof() == false) { //current_line = input_text_stream->ReadLine(); current_line = input_text_file->GetNextLine(); current_line = current_line.Trim(true); current_line = current_line.Trim(false); if (current_line[0] == '#' || current_line[0] == '\0' || current_line[0] == ';') continue; if (current_line[0] != '_') break; // otherwise it is a label, is it a label we want though? if (current_line.StartsWith("_cisTEMPositionInStack ") == true) { if (position_in_stack_column != -1) wxPrintf("Warning :: _cisTEMPositionInStack occurs more than once. I will take the last occurrence\n"); position_in_stack_column = current_column; parameters_that_were_read.position_in_stack = true; } else if (current_line.StartsWith("_cisTEMAnglePsi ") == true) { if (psi_column != -1) wxPrintf("Warning :: _cisTEMAnglePsi occurs more than once. I will take the last occurrence\n"); psi_column = current_column; parameters_that_were_read.psi = true; } else if (current_line.StartsWith("_cisTEMAngleTheta ") == true) { if (theta_column != -1) wxPrintf("Warning :: _cisTEMAngleTheta occurs more than once. I will take the last occurrence\n"); theta_column = current_column; parameters_that_were_read.theta = true; } else if (current_line.StartsWith("_cisTEMAnglePhi ") == true) { if (phi_column != -1) wxPrintf("Warning :: _cisTEMAnglePhi occurs more than once. I will take the last occurrence\n"); phi_column = current_column; parameters_that_were_read.phi = true; } else if (current_line.StartsWith("_cisTEMXShift ") == true) { if (x_shift_column != -1) wxPrintf("Warning :: _cisTEMXShift occurs more than once. I will take the last occurrence\n"); x_shift_column = current_column; parameters_that_were_read.x_shift = true; } else if (current_line.StartsWith("_cisTEMYShift ") == true) { if (y_shift_column != -1) wxPrintf("Warning :: _cisTEMYShift occurs more than once. I will take the last occurrence\n"); y_shift_column = current_column; parameters_that_were_read.y_shift = true; } else if (current_line.StartsWith("_cisTEMDefocus1 ") == true) { if (defocus_1_column != -1) wxPrintf("Warning :: _cisTEMDefocus1 occurs more than once. I will take the last occurrence\n"); defocus_1_column = current_column; parameters_that_were_read.defocus_1 = true; } else if (current_line.StartsWith("_cisTEMDefocus2 ") == true) { if (defocus_2_column != -1) wxPrintf("Warning :: _cisTEMDefocus2 occurs more than once. I will take the last occurrence\n"); defocus_2_column = current_column; parameters_that_were_read.defocus_2 = true; } else if (current_line.StartsWith("_cisTEMDefocusAngle ") == true) { if (defocus_angle_column != -1) wxPrintf("Warning :: _cisTEMDefocusAngle occurs more than once. I will take the last occurrence\n"); defocus_angle_column = current_column; parameters_that_were_read.defocus_angle = true; } else if (current_line.StartsWith("_cisTEMPhaseShift ") == true) { if (phase_shift_column != -1) wxPrintf("Warning :: _cisTEMPhaseShift occurs more than once. I will take the last occurrence\n"); phase_shift_column = current_column; parameters_that_were_read.phase_shift = true; } else if (current_line.StartsWith("_cisTEMImageActivity ") == true) { if (image_is_active_column != -1) wxPrintf("Warning :: _cisTEMImageActivity occurs more than once. I will take the last occurrence\n"); image_is_active_column = current_column; parameters_that_were_read.image_is_active = true; } else if (current_line.StartsWith("_cisTEMOccupancy ") == true) { if (occupancy_column != -1) wxPrintf("Warning :: _cisTEMOccupancy occurs more than once. I will take the last occurrence\n"); occupancy_column = current_column; parameters_that_were_read.occupancy = true; } else if (current_line.StartsWith("_cisTEMLogP ") == true) { if (logp_column != -1) wxPrintf("Warning :: _cisTEMLogP occurs more than once. I will take the last occurrence\n"); logp_column = current_column; parameters_that_were_read.logp = true; } else if (current_line.StartsWith("_cisTEMSigma ") == true) { if (sigma_column != -1) wxPrintf("Warning :: _cisTEMSigma occurs more than once. I will take the last occurrence\n"); sigma_column = current_column; parameters_that_were_read.sigma = true; } else if (current_line.StartsWith("_cisTEMScore ") == true) { if (score_column != -1) wxPrintf("Warning :: _cisTEMScore occurs more than once. I will take the last occurrence\n"); score_column = current_column; parameters_that_were_read.score = true; } else if (current_line.StartsWith("_cisTEMScoreChange ") == true) { if (score_change_column != -1) wxPrintf("Warning :: _cisTEMScoreChange occurs more than once. I will take the last occurrence\n"); score_change_column = current_column; parameters_that_were_read.score_change = true; } else if (current_line.StartsWith("_cisTEMPixelSize ") == true) { if (pixel_size_column != -1) wxPrintf("Warning :: _cisTEMPixelSize occurs more than once. I will take the last occurrence\n"); pixel_size_column = current_column; parameters_that_were_read.pixel_size = true; } else if (current_line.StartsWith("_cisTEMMicroscopeVoltagekV ") == true) { if (microscope_voltage_kv_column != -1) wxPrintf("Warning :: _cisTEMMicroscopeVoltagekV occurs more than once. I will take the last occurrence\n"); microscope_voltage_kv_column = current_column; parameters_that_were_read.microscope_voltage_kv = true; } else if (current_line.StartsWith("_cisTEMMicroscopeCsMM ") == true) { if (microscope_spherical_aberration_mm_column != -1) wxPrintf("Warning :: _cisTEMMicroscopeCsMM occurs more than once. I will take the last occurrence\n"); microscope_spherical_aberration_mm_column = current_column; parameters_that_were_read.microscope_spherical_aberration_mm = true; } else if (current_line.StartsWith("_cisTEMAmplitudeContrast ") == true) { if (amplitude_contrast_column != -1) wxPrintf("Warning :: _cisTEMAmplitudeContrast occurs more than once. I will take the last occurrence\n"); amplitude_contrast_column = current_column; parameters_that_were_read.amplitude_contrast = true; } else if (current_line.StartsWith("_cisTEMBeamTiltX ") == true) { if (beam_tilt_x_column != -1) wxPrintf("Warning :: _cisTEMBeamTiltX occurs more than once. I will take the last occurrence\n"); beam_tilt_x_column = current_column; parameters_that_were_read.beam_tilt_x = true; } else if (current_line.StartsWith("_cisTEMBeamTiltY ") == true) { if (beam_tilt_y_column != -1) wxPrintf("Warning :: _cisTEMBeamTiltY occurs more than once. I will take the last occurrence\n"); beam_tilt_y_column = current_column; parameters_that_were_read.beam_tilt_y = true; } else if (current_line.StartsWith("_cisTEMImageShiftX ") == true) { if (image_shift_x_column != -1) wxPrintf("Warning :: _cisTEMImageShiftX occurs more than once. I will take the last occurrence\n"); image_shift_x_column = current_column; parameters_that_were_read.image_shift_x = true; } else if (current_line.StartsWith("_cisTEMImageShiftY ") == true) { if (image_shift_y_column != -1) wxPrintf("Warning :: _cisTEMImageShiftY occurs more than once. I will take the last occurrence\n"); image_shift_y_column = current_column; parameters_that_were_read.image_shift_y = true; } else if (current_line.StartsWith("_cisTEMBest2DClass ") == true) { if (best_2d_class_column != -1) wxPrintf("Warning :: _cisTEMBest2DClass occurs more than once. I will take the last occurrence\n"); best_2d_class_column = current_column; parameters_that_were_read.best_2d_class = true; } else if (current_line.StartsWith("_cisTEMBeamTiltGroup ") == true) { if (beam_tilt_group_column != -1) wxPrintf("Warning :: _cisTEMBeamTiltGroup occurs more than once. I will take the last occurrence\n"); beam_tilt_group_column = current_column; parameters_that_were_read.beam_tilt_group = true; } else if (current_line.StartsWith("_cisTEMParticleGroup ") == true) { if (particle_group_column != -1) wxPrintf("Warning :: _cisTEMParticleGroup occurs more than once. I will take the last occurrence\n"); particle_group_column = current_column; parameters_that_were_read.particle_group = true; } else if (current_line.StartsWith("_cisTEMAssignedSubset ") == true) { if (assigned_subset_column != -1) wxPrintf("Warning :: _cisTEMAssignedSubset occurs more than once. I will take the last occurrence\n"); assigned_subset_column = current_column; parameters_that_were_read.assigned_subset = true; } else if (current_line.StartsWith("_cisTEMPreExposure ") == true) { if (pre_exposure_column != -1) wxPrintf("Warning :: _cisTEMPreExposure occurs more than once. I will take the last occurrence\n"); pre_exposure_column = current_column; parameters_that_were_read.pre_exposure = true; } else if (current_line.StartsWith("_cisTEMTotalExposure ") == true) { if (total_exposure_column != -1) wxPrintf("Warning :: _cisTEMTotalExposure occurs more than once. I will take the last occurrence\n"); total_exposure_column = current_column; parameters_that_were_read.total_exposure = true; } else if (current_line.StartsWith("_cisTEMReference3DFilename ") == true) { if (reference_3d_filename_column != -1) wxPrintf("Warning :: _cisTEMReference3DFilename occurs more than once. I will take the last occurrence\n"); reference_3d_filename_column = current_column; parameters_that_were_read.reference_3d_filename = true; } else if (current_line.StartsWith("_cisTEMOriginalImageFilename ") == true) { if (original_image_filename_column != -1) wxPrintf("Warning :: _cisTEMOriginalImageFilename occurs more than once. I will take the last occurrence\n"); original_image_filename_column = current_column; parameters_that_were_read.original_image_filename = true; } else if (current_line.StartsWith("_cisTEMStackFilename ") == true) { if (stack_filename_column != -1) wxPrintf("Warning :: _cisTEMStackFilename occurs more than once. I will take the last occurrence\n"); stack_filename_column = current_column; parameters_that_were_read.stack_filename = true; } current_column++; } // quick checks we have all the desired info. /* if (phi_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnAngleRot in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnAngleRot in star file (%s)\n", wanted_filename); return false; } if (theta_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnAngleTilt in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnAngleTilt in star file (%s)\n", wanted_filename); return false; } if (psi_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnAnglePsi in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnAnglePsi in star file (%s)\n", wanted_filename); return false; } if (xshift_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnOriginX in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnOriginX in star file (%s)\n", wanted_filename); return false; } if (yshift_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnOriginY in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnOriginY in star file (%s)\n", wanted_filename); return false; } if (defocus1_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnDefocusU in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnDefocusU in star file (%s)\n", wanted_filename); return false; } if (defocus2_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnDefocusV in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnDefocusV in star file (%s)\n", wanted_filename); return false; } if (defocus_angle_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnDefocusAngle in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnDefocusAngle in star file (%s)\n", wanted_filename); return false; } if (phase_shift_column == -1) { // MyPrintWithDetails("Warning: Couldn't find _rlnPhaseShift in star file (%s) - phase shift will be set to 0.0\n", wanted_filename); } */ // we have the headers, the current line should be the first parameter to extract the info if (ExtractParametersFromLine(current_line, error_string, exclude_negative_film_numbers) == false) return false; // loop over the data lines and fill in.. //while (input_text_file_stream->Eof() == false) while (input_text_file->Eof() == false) { //current_line = input_text_stream->ReadLine(); current_line = input_text_file->GetNextLine(); current_line = current_line.Trim(true); current_line = current_line.Trim(false); if (current_line.IsEmpty() == true) break; if (current_line[0] == '#' || current_line[0] == '\0' || current_line[0] == ';') continue; if (ExtractParametersFromLine(current_line, error_string, exclude_negative_film_numbers) == false) return false; } return true; } bool cisTEMStarFileReader::ReadBinaryFile(wxString wanted_filename, ArrayOfcisTEMParameterLines *alternate_cached_parameters_pointer, bool exclude_negative_film_numbers) { Open(wanted_filename, alternate_cached_parameters_pointer, true); MyDebugAssertTrue(binary_file_size > 2, "Input binary file is too small") int number_of_columns; int number_of_lines; int current_column; int current_line; binary_buffer_position = 0; // get the number of columns and line if (SafelyReadFromBinaryBufferIntoInteger(number_of_columns) == false) return false; if (SafelyReadFromBinaryBufferIntoInteger(number_of_lines) == false) return false; if (number_of_columns < 1 || number_of_lines < 1) { MyPrintWithDetails("Format Error %i columns and %i lines", number_of_columns, number_of_lines); } // Preallocate the memory for speed cached_parameters->Alloc(number_of_lines); // get the order of columns.. long column_order_buffer[number_of_columns]; // so we can keep the order for reading later.. char column_data_types[number_of_columns]; // in case we don't recognize a column - see cistem_paramters for more details ResetColumnPositions(); for (current_column = 0; current_column < number_of_columns; current_column++) { if (SafelyReadFromBinaryBufferIntoLong(column_order_buffer[current_column]) == false) return false; if (SafelyReadFromBinaryBufferIntoChar(column_data_types[current_column]) == false) return false; if (column_order_buffer[current_column] == POSITION_IN_STACK) { if (position_in_stack_column != -1) wxPrintf("Warning :: _cisTEMPositionInStack occurs more than once. I will take the last occurrence\n"); position_in_stack_column = current_column; parameters_that_were_read.position_in_stack = true; } else if (column_order_buffer[current_column] == PSI) { if (psi_column != -1) wxPrintf("Warning :: _cisTEMAnglePsi occurs more than once. I will take the last occurrence\n"); psi_column = current_column; parameters_that_were_read.psi = true; } else if (column_order_buffer[current_column] == THETA) { if (theta_column != -1) wxPrintf("Warning :: _cisTEMAngleTheta occurs more than once. I will take the last occurrence\n"); theta_column = current_column; parameters_that_were_read.theta = true; } else if (column_order_buffer[current_column] == PHI) { if (phi_column != -1) wxPrintf("Warning :: _cisTEMAnglePhi occurs more than once. I will take the last occurrence\n"); phi_column = current_column; parameters_that_were_read.phi = true; } else if (column_order_buffer[current_column] == X_SHIFT) { if (x_shift_column != -1) wxPrintf("Warning :: _cisTEMXShift occurs more than once. I will take the last occurrence\n"); x_shift_column = current_column; parameters_that_were_read.x_shift = true; } else if (column_order_buffer[current_column] == Y_SHIFT) { if (y_shift_column != -1) wxPrintf("Warning :: _cisTEMYShift occurs more than once. I will take the last occurrence\n"); y_shift_column = current_column; parameters_that_were_read.y_shift = true; } else if (column_order_buffer[current_column] == DEFOCUS_1) { if (defocus_1_column != -1) wxPrintf("Warning :: _cisTEMDefocus1 occurs more than once. I will take the last occurrence\n"); defocus_1_column = current_column; parameters_that_were_read.defocus_1 = true; } else if (column_order_buffer[current_column] == DEFOCUS_2) { if (defocus_2_column != -1) wxPrintf("Warning :: _cisTEMDefocus2 occurs more than once. I will take the last occurrence\n"); defocus_2_column = current_column; parameters_that_were_read.defocus_2 = true; } else if (column_order_buffer[current_column] == DEFOCUS_ANGLE) { if (defocus_angle_column != -1) wxPrintf("Warning :: _cisTEMDefocusAngle occurs more than once. I will take the last occurrence\n"); defocus_angle_column = current_column; parameters_that_were_read.defocus_angle = true; } else if (column_order_buffer[current_column] == PHASE_SHIFT) { if (phase_shift_column != -1) wxPrintf("Warning :: _cisTEMPhaseShift occurs more than once. I will take the last occurrence\n"); phase_shift_column = current_column; parameters_that_were_read.phase_shift = true; } else if (column_order_buffer[current_column] == IMAGE_IS_ACTIVE) { if (image_is_active_column != -1) wxPrintf("Warning :: _cisTEMImageActivity occurs more than once. I will take the last occurrence\n"); image_is_active_column = current_column; parameters_that_were_read.image_is_active = true; } else if (column_order_buffer[current_column] == OCCUPANCY) { if (occupancy_column != -1) wxPrintf("Warning :: _cisTEMOccupancy occurs more than once. I will take the last occurrence\n"); occupancy_column = current_column; parameters_that_were_read.occupancy = true; } else if (column_order_buffer[current_column] == LOGP) { if (logp_column != -1) wxPrintf("Warning :: _cisTEMLogP occurs more than once. I will take the last occurrence\n"); logp_column = current_column; parameters_that_were_read.logp = true; } else if (column_order_buffer[current_column] == SIGMA) { if (sigma_column != -1) wxPrintf("Warning :: _cisTEMSigma occurs more than once. I will take the last occurrence\n"); sigma_column = current_column; parameters_that_were_read.sigma = true; } else if (column_order_buffer[current_column] == SCORE) { if (score_column != -1) wxPrintf("Warning :: _cisTEMScore occurs more than once. I will take the last occurrence\n"); score_column = current_column; parameters_that_were_read.score = true; } else if (column_order_buffer[current_column] == SCORE_CHANGE) { if (score_change_column != -1) wxPrintf("Warning :: _cisTEMScoreChange occurs more than once. I will take the last occurrence\n"); score_change_column = current_column; parameters_that_were_read.score_change = true; } else if (column_order_buffer[current_column] == PIXEL_SIZE) { if (pixel_size_column != -1) wxPrintf("Warning :: _cisTEMPixelSize occurs more than once. I will take the last occurrence\n"); pixel_size_column = current_column; parameters_that_were_read.pixel_size = true; } else if (column_order_buffer[current_column] == MICROSCOPE_VOLTAGE) { if (microscope_voltage_kv_column != -1) wxPrintf("Warning :: _cisTEMMicroscopeVoltagekV occurs more than once. I will take the last occurrence\n"); microscope_voltage_kv_column = current_column; parameters_that_were_read.microscope_voltage_kv = true; } else if (column_order_buffer[current_column] == MICROSCOPE_CS) { if (microscope_spherical_aberration_mm_column != -1) wxPrintf("Warning :: _cisTEMMicroscopeCsMM occurs more than once. I will take the last occurrence\n"); microscope_spherical_aberration_mm_column = current_column; parameters_that_were_read.microscope_spherical_aberration_mm = true; } else if (column_order_buffer[current_column] == AMPLITUDE_CONTRAST) { if (amplitude_contrast_column != -1) wxPrintf("Warning :: _cisTEMAmplitudeContrast occurs more than once. I will take the last occurrence\n"); amplitude_contrast_column = current_column; parameters_that_were_read.amplitude_contrast = true; } else if (column_order_buffer[current_column] == BEAM_TILT_X) { if (beam_tilt_x_column != -1) wxPrintf("Warning :: _cisTEMBeamTiltX occurs more than once. I will take the last occurrence\n"); beam_tilt_x_column = current_column; parameters_that_were_read.beam_tilt_x = true; } else if (column_order_buffer[current_column] == BEAM_TILT_Y) { if (beam_tilt_y_column != -1) wxPrintf("Warning :: _cisTEMBeamTiltY occurs more than once. I will take the last occurrence\n"); beam_tilt_y_column = current_column; parameters_that_were_read.beam_tilt_y = true; } else if (column_order_buffer[current_column] == IMAGE_SHIFT_X) { if (image_shift_x_column != -1) wxPrintf("Warning :: _cisTEMImageShiftX occurs more than once. I will take the last occurrence\n"); image_shift_x_column = current_column; parameters_that_were_read.image_shift_x = true; } else if (column_order_buffer[current_column] == IMAGE_SHIFT_Y) { if (image_shift_y_column != -1) wxPrintf("Warning :: _cisTEMImageShiftY occurs more than once. I will take the last occurrence\n"); image_shift_y_column = current_column; parameters_that_were_read.image_shift_y = true; } else if (column_order_buffer[current_column] == BEST_2D_CLASS) { if (best_2d_class_column != -1) wxPrintf("Warning :: _cisTEMBest2DClass occurs more than once. I will take the last occurrence\n"); best_2d_class_column = current_column; parameters_that_were_read.best_2d_class = true; } else if (column_order_buffer[current_column] == BEAM_TILT_GROUP) { if (beam_tilt_group_column != -1) wxPrintf("Warning :: _cisTEMBeamTiltGroup occurs more than once. I will take the last occurrence\n"); beam_tilt_group_column = current_column; parameters_that_were_read.beam_tilt_group = true; } else if (column_order_buffer[current_column] == PARTICLE_GROUP) { if (particle_group_column != -1) wxPrintf("Warning :: _cisTEMParticleGroup occurs more than once. I will take the last occurrence\n"); particle_group_column = current_column; parameters_that_were_read.particle_group = true; } else if (column_order_buffer[current_column] == ASSIGNED_SUBSET) { if (assigned_subset_column != -1) wxPrintf("Warning :: _cisTEMAssignedSubset occurs more than once. I will take the last occurrence\n"); assigned_subset_column = current_column; parameters_that_were_read.assigned_subset = true; } else if (column_order_buffer[current_column] == PRE_EXPOSURE) { if (pre_exposure_column != -1) wxPrintf("Warning :: _cisTEMPreExposure occurs more than once. I will take the last occurrence\n"); pre_exposure_column = current_column; parameters_that_were_read.pre_exposure = true; } else if (column_order_buffer[current_column] == TOTAL_EXPOSURE) { if (total_exposure_column != -1) wxPrintf("Warning :: _cisTEMTotalExposure occurs more than once. I will take the last occurrence\n"); total_exposure_column = current_column; parameters_that_were_read.total_exposure = true; } else if (column_order_buffer[current_column] == REFERENCE_3D_FILENAME) { if (reference_3d_filename_column != -1) wxPrintf("Warning :: _cisTEMReference3DFilename occurs more than once. I will take the last occurrence\n"); reference_3d_filename_column = current_column; parameters_that_were_read.reference_3d_filename = true; } else if (column_order_buffer[current_column] == ORIGINAL_IMAGE_FILENAME) { if (original_image_filename_column != -1) wxPrintf("Warning :: _cisTEMOriginalImageFilename occurs more than once. I will take the last occurrence\n"); original_image_filename_column = current_column; parameters_that_were_read.original_image_filename = true; } else if (column_order_buffer[current_column] == STACK_FILENAME) { if (stack_filename_column != -1) wxPrintf("Warning :: _cisTEMStackFilename occurs more than once. I will take the last occurrence\n"); stack_filename_column = current_column; parameters_that_were_read.stack_filename = true; } } // quick checks we have all the desired info. /* if (phi_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnAngleRot in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnAngleRot in star file (%s)\n", wanted_filename); return false; } if (theta_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnAngleTilt in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnAngleTilt in star file (%s)\n", wanted_filename); return false; } if (psi_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnAnglePsi in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnAnglePsi in star file (%s)\n", wanted_filename); return false; } if (xshift_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnOriginX in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnOriginX in star file (%s)\n", wanted_filename); return false; } if (yshift_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnOriginY in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnOriginY in star file (%s)\n", wanted_filename); return false; } if (defocus1_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnDefocusU in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnDefocusU in star file (%s)\n", wanted_filename); return false; } if (defocus2_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnDefocusV in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnDefocusV in star file (%s)\n", wanted_filename); return false; } if (defocus_angle_column == -1) { MyPrintWithDetails("Error: Couldn't find _rlnDefocusAngle in star file (%s)\n", wanted_filename); if (error_string != NULL) *error_string = wxString::Format("Error: Couldn't find _rlnDefocusAngle in star file (%s)\n", wanted_filename); return false; } if (phase_shift_column == -1) { // MyPrintWithDetails("Warning: Couldn't find _rlnPhaseShift in star file (%s) - phase shift will be set to 0.0\n", wanted_filename); } */ // extract the data.. cisTEMParameterLine temp_parameters; for (current_line = 0; current_line < number_of_lines; current_line++) { temp_parameters.SetAllToZero(); for (current_column = 0; current_column < number_of_columns; current_column++) { if (column_order_buffer[current_column] == POSITION_IN_STACK) { if (SafelyReadFromBinaryBufferIntoUnsignedInteger(temp_parameters.position_in_stack) == false) return false; } else if (column_order_buffer[current_column] == PSI) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.psi) == false) return false; } else if (column_order_buffer[current_column] == THETA) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.theta) == false) return false; } else if (column_order_buffer[current_column] == PHI) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.phi) == false) return false; } else if (column_order_buffer[current_column] == X_SHIFT) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.x_shift) == false) return false; } else if (column_order_buffer[current_column] == Y_SHIFT) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.y_shift) == false) return false; } else if (column_order_buffer[current_column] == DEFOCUS_1) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.defocus_1) == false) return false; } else if (column_order_buffer[current_column] == DEFOCUS_2) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.defocus_2) == false) return false; } else if (column_order_buffer[current_column] == DEFOCUS_ANGLE) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.defocus_angle) == false) return false; } else if (column_order_buffer[current_column] == PHASE_SHIFT) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.phase_shift) == false) return false; } else if (column_order_buffer[current_column] == IMAGE_IS_ACTIVE) { if (SafelyReadFromBinaryBufferIntoInteger(temp_parameters.image_is_active) == false) return false; } else if (column_order_buffer[current_column] == OCCUPANCY) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.occupancy) == false) return false; } else if (column_order_buffer[current_column] == LOGP) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.logp) == false) return false; } else if (column_order_buffer[current_column] == SIGMA) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.sigma) == false) return false; } else if (column_order_buffer[current_column] == SCORE) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.score) == false) return false; } else if (column_order_buffer[current_column] == SCORE_CHANGE) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.score_change) == false) return false; } else if (column_order_buffer[current_column] == PIXEL_SIZE) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.pixel_size) == false) return false; } else if (column_order_buffer[current_column] == MICROSCOPE_VOLTAGE) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.microscope_voltage_kv) == false) return false; } else if (column_order_buffer[current_column] == MICROSCOPE_CS) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.microscope_spherical_aberration_mm) == false) return false; } else if (column_order_buffer[current_column] == AMPLITUDE_CONTRAST) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.amplitude_contrast) == false) return false; } else if (column_order_buffer[current_column] == BEAM_TILT_X) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.beam_tilt_x) == false) return false; } else if (column_order_buffer[current_column] == BEAM_TILT_Y) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.beam_tilt_y) == false) return false; } else if (column_order_buffer[current_column] == IMAGE_SHIFT_X) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.image_shift_x) == false) return false; } else if (column_order_buffer[current_column] == IMAGE_SHIFT_Y) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.image_shift_y) == false) return false; } else if (column_order_buffer[current_column] == BEST_2D_CLASS) { if (SafelyReadFromBinaryBufferIntoInteger(temp_parameters.best_2d_class) == false) return false; } else if (column_order_buffer[current_column] == BEAM_TILT_GROUP) { if (SafelyReadFromBinaryBufferIntoInteger(temp_parameters.beam_tilt_group) == false) return false; } else if (column_order_buffer[current_column] == STACK_FILENAME) { if (SafelyReadFromBinaryBufferIntowxString(temp_parameters.stack_filename) == false) return false; } else if (column_order_buffer[current_column] == ORIGINAL_IMAGE_FILENAME) { if (SafelyReadFromBinaryBufferIntowxString(temp_parameters.original_image_filename) == false) return false; } else if (column_order_buffer[current_column] == REFERENCE_3D_FILENAME) { if (SafelyReadFromBinaryBufferIntowxString(temp_parameters.reference_3d_filename) == false) return false; } else if (column_order_buffer[current_column] == PARTICLE_GROUP) { if (SafelyReadFromBinaryBufferIntoInteger(temp_parameters.particle_group) == false) return false; } else if (column_order_buffer[current_column] == ASSIGNED_SUBSET) { if (SafelyReadFromBinaryBufferIntoInteger(temp_parameters.assigned_subset) == false) return false; } else if (column_order_buffer[current_column] == PRE_EXPOSURE) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.pre_exposure) == false) return false; } else if (column_order_buffer[current_column] == TOTAL_EXPOSURE) { if (SafelyReadFromBinaryBufferIntoFloat(temp_parameters.total_exposure) == false) return false; } else // We do not recongnize this column type { if (current_line == 0) wxPrintf("Unknown Column Type in Binary File (%li) - it will be ignored.\n"); if (column_data_types[current_column] == INTEGER) { int buffer_int; if (SafelyReadFromBinaryBufferIntoInteger(buffer_int) == false) return false; } else if (column_data_types[current_column] == INTEGER_UNSIGNED) { unsigned int buffer_int; if (SafelyReadFromBinaryBufferIntoUnsignedInteger(buffer_int) == false) return false; } else if (column_data_types[current_column] == FLOAT) { float buffer_float; if (SafelyReadFromBinaryBufferIntoFloat(buffer_float) == false) return false; } else if (column_data_types[current_column] == LONG) { long buffer_long; if (SafelyReadFromBinaryBufferIntoLong(buffer_long) == false) return false; } else if (column_data_types[current_column] == DOUBLE) { double buffer_double; if (SafelyReadFromBinaryBufferIntoDouble(buffer_double) == false) return false; } else if (column_data_types[current_column] == CHAR) { char buffer_char; if (SafelyReadFromBinaryBufferIntoChar(buffer_char) == false) return false; } else if (column_data_types[current_column] == VARIABLE_LENGTH) { wxString buffer_string; if (SafelyReadFromBinaryBufferIntowxString(buffer_string) == false) return false; } } } if (temp_parameters.image_is_active >= 0 || exclude_negative_film_numbers == false) cached_parameters->Add(temp_parameters); } return true; }
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bergcounits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "base58.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Bergco address (e.g. 8aVWAvxsUzgQfHWqbPTcXFWeDhvMEu7wJ2)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bergcoAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { if(!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BergcoUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BergcoUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed!"), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::NarrationTooLong: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Narration is too long."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBergcoURI(uri, &rv)) { CBergcoAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(model && model->getOptionsModel()) { ui->labelBalance->setText(BergcoUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance)); } } void SendCoinsDialog::updateDisplayUnit() { setBalance(model->getBalance(), 0, 0, 0); } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBergcoAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBergcoAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBergcoAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid Bergco address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBergcoAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
#include "SharkAnimInstance.h" USharkAnimInstance::USharkAnimInstance() { this->SharkState = ESharkEnemyState::Idle; this->IsCloseToGround = false; this->AttackConnected = false; this->IsAttackingAndAttackNotConnected = false; this->IsNotAttackingOrAttackConnected = false; this->IsFalling = false; this->IsVulnerable = false; this->BendValue = 0.00f; this->IsTurning = false; this->TurnSpeed = 0.00f; this->IdleSpeed = 0.00f; }
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #define BOOST_TEST_MODULE BitenX Test Suite #include "test_bitenx.h" #include "chainparams.h" #include "consensus/consensus.h" #include "consensus/validation.h" #include "key.h" #include "validation.h" #include "miner.h" #include "net_processing.h" #include "pubkey.h" #include "random.h" #include "txdb.h" #include "txmempool.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet/db.h" #include "wallet/wallet.h" #endif #include <boost/filesystem.hpp> #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h CWallet* pwalletMain; std::unique_ptr<CConnman> g_connman; extern bool fPrintToConsole; extern void noui_connect(); BasicTestingSetup::BasicTestingSetup(const std::string& chainName) { ECC_Start(); SetupEnvironment(); SetupNetworking(); fPrintToDebugLog = false; // don't want to write to debug.log file fCheckBlockIndex = true; SelectParams(chainName); noui_connect(); } BasicTestingSetup::~BasicTestingSetup() { ECC_Stop(); g_connman.reset(); } TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName) { const CChainParams& chainparams = Params(); #ifdef ENABLE_WALLET bitdb.MakeMock(); #endif ClearDatadirCache(); pathTemp = GetTempPath() / strprintf("test_bitenx_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); boost::filesystem::create_directories(pathTemp); mapArgs["-datadir"] = pathTemp.string(); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(pcoinsdbview); InitBlockIndex(chainparams); #ifdef ENABLE_WALLET bool fFirstRun; pwalletMain = new CWallet("wallet.dat"); pwalletMain->LoadWallet(fFirstRun); RegisterValidationInterface(pwalletMain); #endif nScriptCheckThreads = 3; for (int i=0; i < nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); g_connman = std::unique_ptr<CConnman>(new CConnman()); connman = g_connman.get(); RegisterNodeSignals(GetNodeSignals()); } TestingSetup::~TestingSetup() { UnregisterNodeSignals(GetNodeSignals()); threadGroup.interrupt_all(); threadGroup.join_all(); #ifdef ENABLE_WALLET UnregisterValidationInterface(pwalletMain); delete pwalletMain; pwalletMain = NULL; #endif UnloadBlockIndex(); delete pcoinsTip; delete pcoinsdbview; delete pblocktree; #ifdef ENABLE_WALLET bitdb.Flush(true); bitdb.Reset(); #endif boost::filesystem::remove_all(pathTemp); } TestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST) { // Generate a 100-block chain: coinbaseKey.MakeNewKey(true); CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; for (int i = 0; i < COINBASE_MATURITY; i++) { std::vector<CMutableTransaction> noTxns; CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey); coinbaseTxns.push_back(b.vtx[0]); } } // // Create a new block with just given transactions, coinbase paying to // scriptPubKey, and try to add it to the current chain. // CBlock TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey) { const CChainParams& chainparams = Params(); CBlockTemplate *pblocktemplate = CreateNewBlock(chainparams, scriptPubKey); CBlock& block = pblocktemplate->block; // Replace mempool-selected txns with just coinbase plus passed-in txns: block.vtx.resize(1); BOOST_FOREACH(const CMutableTransaction& tx, txns) block.vtx.push_back(tx); // IncrementExtraNonce creates a valid coinbase and merkleRoot unsigned int extraNonce = 0; IncrementExtraNonce(&block, chainActive.Tip(), extraNonce); while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce; ProcessNewBlock(chainparams, &block, true, NULL, NULL); CBlock result = block; delete pblocktemplate; return result; } TestChain100Setup::~TestChain100Setup() { } CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(CMutableTransaction &tx, CTxMemPool *pool) { CTransaction txn(tx); bool hasNoDependencies = pool ? pool->HasNoInputsOf(tx) : hadNoDependencies; // Hack to assume either its completely dependent on other mempool txs or not at all CAmount inChainValue = hasNoDependencies ? txn.GetValueOut() : 0; return CTxMemPoolEntry(txn, nFee, nTime, dPriority, nHeight, hasNoDependencies, inChainValue, spendsCoinbase, sigOpCount, lp); } void Shutdown(void* parg) { exit(0); } void StartShutdown() { exit(0); } bool ShutdownRequested() { return false; }
#include "lzma2.h" #include "mordor/assert.h" #include "mordor/exception.h" #include "mordor/log.h" #ifdef MSVC #pragma comment(lib, "liblzma") #endif namespace Mordor { static Logger::ptr g_log = Log::lookup("mordor:streams:lzma2"); LZMAStream::LZMAStream(Stream::ptr parent, uint32_t preset, lzma_check check, bool own) : MutatingFilterStream(parent, own) { lzma_stream strm = LZMA_STREAM_INIT; m_strm = strm; lzma_ret ret; if (supportsRead()) { ret = lzma_stream_decoder(&m_strm, UINT64_MAX, LZMA_CONCATENATED); } else { lzma_options_lzma opt_lzma2; if (lzma_lzma_preset(&opt_lzma2, preset)) { MORDOR_THROW_EXCEPTION(std::invalid_argument("unsupported option")); } lzma_filter filters[] = { #if defined(X86_64) || defined(X86) { LZMA_FILTER_X86, NULL }, #elif defined(PPC) { LZMA_FILTER_POWERPC, NULL }, #elif defined(ARM) #if defined(__thumb__) { LZMA_FILTER_ARMTHUMB, NULL }, #else { LZMA_FILTER_ARM, NULL }, #endif #endif { LZMA_FILTER_LZMA2, &opt_lzma2 }, { LZMA_VLI_UNKNOWN, NULL }, }; ret = lzma_stream_encoder(&m_strm, filters, check); } switch (ret) { case LZMA_OK: m_closed = false; break; case LZMA_MEM_ERROR: MORDOR_THROW_EXCEPTION(std::bad_alloc()); break; case LZMA_OPTIONS_ERROR: MORDOR_THROW_EXCEPTION(std::invalid_argument("unsupported option")); break; case LZMA_UNSUPPORTED_CHECK: MORDOR_THROW_EXCEPTION(std::invalid_argument("unsupported check")); break; default: MORDOR_THROW_EXCEPTION(std::runtime_error("unknown lzma error")); break; } } LZMAStream::~LZMAStream() { lzma_end(&m_strm); } void LZMAStream::close(CloseType type) { if ((type == READ && supportsWrite()) || (type == WRITE && supportsRead()) || m_closed) { if (ownsParent()) parent()->close(type); return; } finish(); if (ownsParent()) parent()->close(type); } size_t LZMAStream::read(Buffer &buffer, size_t length) { struct iovec outbuf = buffer.writeBuffer(length, false); m_strm.next_out = (uint8_t*)outbuf.iov_base; m_strm.avail_out = outbuf.iov_len; for (;;) { std::vector<iovec> inbufs = m_inBuffer.readBuffers(); if (m_inBuffer.readAvailable() == 0) { m_strm.next_in = NULL; m_strm.avail_in = 0; } else { m_strm.next_in = (uint8_t*)inbufs[0].iov_base; m_strm.avail_in = inbufs[0].iov_len; } lzma_ret rc = lzma_code(&m_strm, LZMA_RUN); MORDOR_LOG_DEBUG(g_log) << this << " lzma_code((" << (inbufs.empty() ? 0 : inbufs[0].iov_len) << ", " << outbuf.iov_len << ")): " << rc << " (" << m_strm.avail_in << ", " << m_strm.avail_out << ")"; if (m_inBuffer.readAvailable() > 0) m_inBuffer.consume(inbufs[0].iov_len - m_strm.avail_in); size_t result; switch (rc) { case LZMA_BUF_ERROR: // no progress... MORDOR_ASSERT(m_strm.avail_in == 0); MORDOR_ASSERT(m_inBuffer.readAvailable() == 0); result = parent()->read(m_inBuffer, BUFFER_SIZE); // the end of input file has been reached, and since we are in // LZMA_CONCATENATED mode, we need to tell lzma_code() that no // more input will be coming. if (result != 0) break; finish(); return result; case LZMA_STREAM_END: // May have still produced output result = outbuf.iov_len - m_strm.avail_out; buffer.produce(result); finish(); return result; case LZMA_OK: result = outbuf.iov_len - m_strm.avail_out; // It consumed input, but produced no output... DON'T return eof if (result == 0) continue; buffer.produce(result); return result; case LZMA_MEM_ERROR: MORDOR_THROW_EXCEPTION(std::bad_alloc()); case LZMA_FORMAT_ERROR: MORDOR_THROW_EXCEPTION(UnknownLZMAFormatException()); case LZMA_DATA_ERROR: MORDOR_THROW_EXCEPTION(CorruptedLZMAStreamException()); default: MORDOR_THROW_EXCEPTION(LZMAException(rc)); } } } size_t LZMAStream::write(const Buffer &buffer, size_t length) { MORDOR_ASSERT(!m_closed); flushBuffer(); for (;;) { if (m_outBuffer.writeAvailable() == 0) m_outBuffer.reserve(BUFFER_SIZE); struct iovec inbuf = buffer.readBuffer(length, false); struct iovec outbuf = m_outBuffer.writeBuffer(~0u, false); m_strm.next_in = (uint8_t*)inbuf.iov_base; m_strm.avail_in = inbuf.iov_len; m_strm.next_out = (uint8_t*)outbuf.iov_base; m_strm.avail_out = outbuf.iov_len; lzma_ret rc = lzma_code(&m_strm, LZMA_RUN); MORDOR_LOG_DEBUG(g_log) << this << " lzma_code((" << inbuf.iov_len << ", " << outbuf.iov_len << "), LZMA_RUN): " << rc << " (" << m_strm.avail_in << ", " << m_strm.avail_out << ")"; // We are always providing both input and output MORDOR_ASSERT(rc != LZMA_BUF_ERROR); // We're not doing LZMA_FINISH, so we shouldn't get EOF MORDOR_ASSERT(rc != LZMA_STREAM_END); MORDOR_ASSERT(rc == LZMA_OK); size_t result = inbuf.iov_len - m_strm.avail_in; if (result == 0) continue; m_outBuffer.produce(outbuf.iov_len - m_strm.avail_out); try { flushBuffer(); } catch (std::runtime_error) { // Swallow it } return result; } } void LZMAStream::flush(bool flushParent) { flushBuffer(); if (flushParent) parent()->flush(); } void LZMAStream::flushBuffer() { while (m_outBuffer.readAvailable() > 0) m_outBuffer.consume(parent()->write(m_outBuffer, m_outBuffer.readAvailable())); } void LZMAStream::finish() { MORDOR_ASSERT(m_strm.avail_in == 0); lzma_ret rc = LZMA_OK; do { if (m_outBuffer.writeAvailable() == 0) m_outBuffer.reserve(BUFFER_SIZE); iovec outbuf = m_outBuffer.writeBuffer(~0u, false); m_strm.next_out = (uint8_t*)outbuf.iov_base; m_strm.avail_out = outbuf.iov_len; rc = lzma_code(&m_strm, LZMA_FINISH); MORDOR_ASSERT(m_strm.avail_in == 0); MORDOR_LOG_DEBUG(g_log) << this << " lzma_code(0, " << outbuf.iov_len << "): " << rc << " (0, " << m_strm.avail_out << ")"; if (m_strm.avail_out == 0 || rc == LZMA_STREAM_END) { m_outBuffer.produce(outbuf.iov_len - m_strm.avail_out); } if (m_outBuffer.writeAvailable() == 0) { flushBuffer(); } } while (rc == LZMA_OK); if (rc != LZMA_STREAM_END) { MORDOR_THROW_EXCEPTION(LZMAException(rc)); } m_closed = true; flushBuffer(); } }
/* Goal: use constant variables */ #include <iostream> int main() { using std::cout; const int weight_goal = 100; cout << "WeightGoal = " << weight_goal << "\n"; // weight_goal = 200; // cout << "WeightGoal = " << weight_goal << "\n"; }
/****************************************************************************** ** Copyright (C) 2011 by CEA ******************************************************************************* ** ** UNIT ** ** Version: 1.0 ** ** Author: Jean-Luc Starck ** ** Date: 02/11/2011 ** ** File: mrs_almrec.cc ** ******************************************************************************* ** ** DESCRIPTION genus program ** ----------- ** ******************************************************************************/ #include"HealpixClass.h" char Name_Imag_In[256]; /* input file image */ char Name_Imag_Out[256]; /* output file name */ extern int OptInd; extern char *OptArg; extern int GetOpt(int argc, char **argv, char *opts); Bool Verbose=False; Bool NormALM = False; float ZeroPadding=0.0; int Lmax = 0.; Bool OptS_PS = False; Bool CFIMA= False; int Nside=16; int NbrIter=0; /***************************************************************************/ static void usage(char *argv[]) { fprintf(OUTMAN, "Usage: %s options in_map out_map \n\n", argv[0]); fprintf(OUTMAN, " where options = \n"); fprintf(OUTMAN, " [-n Nside]\n"); fprintf(OUTMAN, " Default is 16.\n"); fprintf(OUTMAN, " [-N]\n"); fprintf(OUTMAN, " Normalization. Default is no.\n"); fprintf(OUTMAN, " [-i NbrIter]\n"); fprintf(OUTMAN, " Number of iteration for the reconstruction. Default is no iteraton\n"); fprintf(OUTMAN, " [-T]\n"); fprintf(OUTMAN, " Read the input as a complex image.\n"); exit(-1); } /*********************************************************************/ /* GET COMMAND LINE ARGUMENTS */ static void sinit(int argc, char *argv[]) { int c; float Val; int seed; while ((c = GetOpt(argc,argv,(char *) "n:TNi:l:p:vzZ")) != -1) { switch (c) { case 'T': CFIMA=True; break; case 'N': NormALM=True; break; case 'p': if (sscanf(OptArg,"%f",&ZeroPadding) != 1) { fprintf(OUTMAN, "Error: bad zero padding value: %s\n", OptArg); exit(-1); } break; case 'i': if (sscanf(OptArg,"%d",&NbrIter) != 1) { fprintf(OUTMAN, "Error: bad nside value: %s\n", OptArg); exit(-1); } break; case 'n': if (sscanf(OptArg,"%d",&Nside) != 1) { fprintf(OUTMAN, "Error: bad nside value: %s\n", OptArg); exit(-1); } break; case 'l': if (sscanf(OptArg,"%d",&Lmax) != 1) { fprintf(OUTMAN, "Error: bad lmax value: %s\n", OptArg); exit(-1); } break; case 'v': Verbose = True; break; case '?': usage(argv); break; default: usage(argv); break; } } /* get optional input file names from trailing parameters and open files */ if (OptInd < argc) strcpy(Name_Imag_In, argv[OptInd++]); else usage(argv); if (OptInd < argc) strcpy(Name_Imag_Out, argv[OptInd++]); else usage(argv); /* make sure there are not too many parameters */ if (OptInd < argc) { fprintf(OUTMAN, "Too many parameters: %s ...\n", argv[OptInd]); exit(-1); } } /*********************************************************************/ /* void mrs_almtrans(Hdmap map, CAlmR & A) { map.info(); double avg=map.average(); map.add(-avg); if (map.Scheme()==NEST) map.swap_scheme(); map2alm_iter(map, A, A.Niter, A.weight_T); // template<typename T> void map2alm_iter (const Healpix_Map<T> &map, // Alm<xcomplex<T> > &alm, int num_iter, const arr<double> &weight); int Niter = A.Niter; Alm<xcomplex<double> > A1(A.Lmax(),A.Mmax()); map2alm_iter(map, A1, Niter, A.weight_T); A(0,0) += avg*sqrt(fourpi); map.info(); } */ /*********************************************************************/ int main(int argc, char *argv[]) { int k; fitsstruct Header, HD1; char Cmd[512]; Cmd[0] = '\0'; for (k =0; k < argc; k++) sprintf(Cmd, "%s %s", Cmd, argv[k]); /* Get command line arguments, open input file(s) if necessary */ sinit(argc, argv); if (Verbose == True) { cout << "# PARAMETERS: " << endl; cout << "# File Name in = " << Name_Imag_In << endl; cout << "# File Name Out = " << Name_Imag_Out << endl; if (NbrIter > 0) cout << "# Nbr of iter = " << NbrIter << endl; } // /Users/Shared/software/Healpix_2.01/src/cxx/Healpix_cxx // alm_map_tools.cc et .h // cout << "TEST " << Name_Imag_In << endl; // Healpix_Map<float> map; Hdmap map; Hdmap Result; CAlmR ALM; if (CFIMA == False) { ALM.read(Name_Imag_In, Nside); if (Verbose == True) cout << "Lmax = " << ALM.Lmax() << endl; } else { dblarray A; fits_read_dblarr(Name_Imag_In, A); Lmax = A.nx() - 1; int Lmax_Tot = mrs_get_lmax (Lmax, Nside, ZeroPadding); ALM.alloc(Nside, Lmax_Tot); for (int l=0; l <= ALM.Lmax(); l++) for (int m=0; m <= l; m++) { ALM(l,m) = xcomplex<REAL>( A(l,m,0),A(l,m,1)); } } if (NbrIter > 0) ALM.Niter = NbrIter; ALM.Norm = NormALM; ALM.alm_rec(Result); if (Verbose == True) { double Min, Max; Result.minmax(Min,Max); cout << " Npix = " << Result.Npix() << endl; cout << " Min = " << Min << " Max = " << Max << endl; } Result.write(Name_Imag_Out); exit(0); }
// _build.cpp // // $Id: _build.cpp,v 1.4 2004/06/10 15:39:34 sdennis Exp $ // // MUX 2.4 // Copyright (C) 1998 through 2004 Solid Vertical Domains, Ltd. All // rights not explicitly given are reserved. // #include "_build.h" char szBuildDate[] = __DATE__ " " __TIME__; char szBuildNum[] = "1";
#include <string> #include <vector> #include <iostream> // 根据d字符串中提供的字符分割字符串 std::vector<std::string> StringSplit(const std::string& str, const std::string& d) { std::string::size_type pos = 0; std::vector<std::string> ret; while (pos < str.size() && pos != std::string::npos) { std::string::size_type start = str.find_first_not_of(d, pos); if (start == std::string::npos) { break; } pos = start; std::string::size_type end = str.find_first_of(d, pos); if (end == std::string::npos) { end = str.size(); } pos = end; ret.push_back(str.substr(start, end - start)); } return ret; } // 判断字符ch是否是一个数字 bool IsDigit(char ch) { return '0' <= ch && ch <= '9' ? true : false; } // 判断字符ch是否是一个正负号 bool IsSign(char ch) { return ch == '-' || ch == '+' ? true : false; } // 判断该字符是否可以转化为有符号整形 bool IsIntStr(const std::string& str) { for (std::string::size_type index = 0; index < str.size(); ++index) { if (IsDigit(str[index]) || (!IsDigit(str[index]) && IsSign(str[index]) && index == 0)) { continue; } return false; } return true; } // 求b的绝对值 int64_t Abs(int64_t b) { return b < 0 ? -b : b; } // 返回两个数中的最大值 int64_t Max(int64_t left, int64_t right) { return left >= right ? left : right; } // 返回三个数中的最大值 int64_t MaxThree(int64_t mid, int64_t left, int64_t right) { return Max(mid, Max(left, right)); } // 返回两个数中的最小值 int64_t Min(int64_t left, int64_t right) { return left <= right ? left : right; } // 从一行中读取一个数,在一个程序中使用getline时,最好使用这个函数来读取行数,不然会出现多于的换行 int GetIntFromLine() { std::string line; std::getline(std::cin, line); return std::atoi(line.c_str()); } // 从cin中读取n行数据 std::vector<std::string> ReadNLineFromCin(int n) { std::vector<std::string> strs; for (int i = 0; i < n; ++i) { std::string line; std::getline(std::cin, line); strs.push_back(line); } return strs; } // 先用sp中的任意一个字符去分割str,然后再把分割的每一个单元转化为int std::vector<int> GetIntVectorFromStr(const std::string& str, const std::string& sp) { std::vector<int> ret; auto sps = StringSplit(str, sp); for (size_t ks = 0; ks < sps.size(); ++ks) { ret.push_back(std::atoi(sps[ks].c_str())); } return std::move(ret); } // 相当于处理多个字符串的GetIntVectorFromStr std::vector<std::vector<int>> GetIntMatrixFromStrs(const std::vector<std::string> &strs, const std::string& sp) { std::vector<std::vector<int>> ret; ret.resize(strs.size()); for (size_t i = 0; i < strs.size(); ++i) { auto sps = StringSplit(strs[i], sp); for (size_t ks = 0; ks < sps.size(); ++ks) { ret[i].push_back(std::atoi(sps[ks].c_str())); } } return std::move(ret); } // 从一行中读取N个整数,分隔符为sp里面的任意字符 std::vector<int> GetIntVectorFromCin(const std::string& sp) { auto str = ReadNLineFromCin(1); return GetIntVectorFromStr(str[0], sp); } // 相当于ReadNLineFromCin + GetIntMatrixFromStrs std::vector<std::vector<int>> ReadMatrixFromCin(int n, const std::string& sp) { return GetIntMatrixFromStrs(ReadNLineFromCin(n), sp); }
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Special Function Registers namespace SfrOhciicr{ ///<OHCI Interrupt Configuration Register using Addr = Register::Address<0xf0038010,0xff7fffc8,0x00000000,unsigned>; ///USB PORTx RESET constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> res0{}; ///USB PORTx RESET constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> res1{}; ///USB PORTx RESET constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> res2{}; ///OHCI Asynchronous Resume Interrupt Enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> arie{}; ///Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> appstart{}; ///OHCI USB DEVICE PULL-UP DISABLE constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> udppudis{}; } namespace SfrOhciisr{ ///<OHCI Interrupt Status Register using Addr = Register::Address<0xf0038014,0xfffffff8,0x00000000,unsigned>; ///OHCI Resume Interrupt Status Port 0 constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ris0{}; ///OHCI Resume Interrupt Status Port 1 constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ris1{}; ///OHCI Resume Interrupt Status Port 2 constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ris2{}; } namespace SfrAhb{ ///<AHB Configuration Register using Addr = Register::Address<0xf0038020,0x83ff83ff,0x00000000,unsigned>; ///AHB MASTERx 10 Converter Prefetch enum class Pfetch10Val { incr4=0x00000000, ///<INCR undefined burst converted to burst of 4 beats. incr8=0x00000001, ///<INCR undefined burst converted to burst of 8 beats. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,Pfetch10Val> pfetch10{}; namespace Pfetch10ValC{ constexpr Register::FieldValue<decltype(pfetch10)::Type,Pfetch10Val::incr4> incr4{}; constexpr Register::FieldValue<decltype(pfetch10)::Type,Pfetch10Val::incr8> incr8{}; } ///AHB MASTERx 11 Converter Prefetch enum class Pfetch11Val { incr4=0x00000000, ///<INCR undefined burst converted to burst of 4 beats. incr8=0x00000001, ///<INCR undefined burst converted to burst of 8 beats. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,Pfetch11Val> pfetch11{}; namespace Pfetch11ValC{ constexpr Register::FieldValue<decltype(pfetch11)::Type,Pfetch11Val::incr4> incr4{}; constexpr Register::FieldValue<decltype(pfetch11)::Type,Pfetch11Val::incr8> incr8{}; } ///AHB MASTERx 12 Converter Prefetch enum class Pfetch12Val { incr4=0x00000000, ///<INCR undefined burst converted to burst of 4 beats. incr8=0x00000001, ///<INCR undefined burst converted to burst of 8 beats. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,Pfetch12Val> pfetch12{}; namespace Pfetch12ValC{ constexpr Register::FieldValue<decltype(pfetch12)::Type,Pfetch12Val::incr4> incr4{}; constexpr Register::FieldValue<decltype(pfetch12)::Type,Pfetch12Val::incr8> incr8{}; } ///AHB MASTERx 13 Converter Prefetch enum class Pfetch13Val { incr4=0x00000000, ///<INCR undefined burst converted to burst of 4 beats. incr8=0x00000001, ///<INCR undefined burst converted to burst of 8 beats. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Pfetch13Val> pfetch13{}; namespace Pfetch13ValC{ constexpr Register::FieldValue<decltype(pfetch13)::Type,Pfetch13Val::incr4> incr4{}; constexpr Register::FieldValue<decltype(pfetch13)::Type,Pfetch13Val::incr8> incr8{}; } ///AHB MASTERx 14 Converter Prefetch enum class Pfetch14Val { incr4=0x00000000, ///<INCR undefined burst converted to burst of 4 beats. incr8=0x00000001, ///<INCR undefined burst converted to burst of 8 beats. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,Pfetch14Val> pfetch14{}; namespace Pfetch14ValC{ constexpr Register::FieldValue<decltype(pfetch14)::Type,Pfetch14Val::incr4> incr4{}; constexpr Register::FieldValue<decltype(pfetch14)::Type,Pfetch14Val::incr8> incr8{}; } ///AHB MASTERx 10 Converter Define Length Burst Optimization constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> dlbopt10{}; ///AHB MASTERx 11 Converter Define Length Burst Optimization constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> dlbopt11{}; ///AHB MASTERx 12 Converter Define Length Burst Optimization constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> dlbopt12{}; ///AHB MASTERx 13 Converter Define Length Burst Optimization constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> dlbopt13{}; ///AHB MASTERx 14 Converter Define Length Burst Optimization constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> dlbopt14{}; } namespace SfrBridge{ ///<Bridge Configuration Register using Addr = Register::Address<0xf0038024,0xfffffefe,0x00000000,unsigned>; ///AHB to APB Bridge mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> apbturbo{}; ///AXI to AHB bridge for DDR controller selection enum class Axi2ahbselVal { single=0x00000000, ///<use single port bridge. dual=0x00000001, ///<use dual port bridge. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,Axi2ahbselVal> axi2ahbsel{}; namespace Axi2ahbselValC{ constexpr Register::FieldValue<decltype(axi2ahbsel)::Type,Axi2ahbselVal::single> single{}; constexpr Register::FieldValue<decltype(axi2ahbsel)::Type,Axi2ahbselVal::dual> dual{}; } } namespace SfrSecure{ ///<Security Configuration Register using Addr = Register::Address<0xf0038028,0xfffffefe,0x00000000,unsigned>; ///Disable Access to ROM Code constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> rom{}; ///Disable Access to Fuse Controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> fuse{}; } namespace SfrUtmicktrim{ ///<UTMI Clock Trimming Register using Addr = Register::Address<0xf0038030,0xfff0fffc,0x00000000,unsigned>; ///UTMI Reference Clock Frequency enum class FreqVal { v12=0x00000000, ///<12 MHz reference clock v16=0x00000001, ///<16 MHz reference clock v24=0x00000002, ///<24 MHz reference clock v48=0x00000003, ///<48 MHz reference clock }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,FreqVal> freq{}; namespace FreqValC{ constexpr Register::FieldValue<decltype(freq)::Type,FreqVal::v12> v12{}; constexpr Register::FieldValue<decltype(freq)::Type,FreqVal::v16> v16{}; constexpr Register::FieldValue<decltype(freq)::Type,FreqVal::v24> v24{}; constexpr Register::FieldValue<decltype(freq)::Type,FreqVal::v48> v48{}; } ///UTMI Band Gap Voltage Trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> vbg{}; } namespace SfrUtmihstrim{ ///<UTMI High Speed Trimming Register using Addr = Register::Address<0xf0038034,0xfff88888,0x00000000,unsigned>; ///UTMI HS SQUELCH Voltage Trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> squelch{}; ///UTMI Disconnect Voltage Trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> disc{}; ///UTMI HS PORTx Transceiver Slope Trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,unsigned> slope0{}; ///UTMI HS PORTx Transceiver Slope Trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> slope1{}; ///UTMI HS PORTx Transceiver Slope Trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> slope2{}; } namespace SfrUtmifstrim{ ///<UTMI Full Speed Trimming Register using Addr = Register::Address<0xf0038038,0xff88fc88,0x00000000,unsigned>; ///FS Transceiver output rising slope trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> rise{}; ///FS Transceiver output falling slope trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> fall{}; ///FS Transceiver crossover voltage trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> xcvr{}; ///FS Transceiver NMOS impedance trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> zn{}; ///FS Transceiver PMOS impedance trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> zp{}; } namespace SfrUtmiswap{ ///<UTMI DP/DM Pin Swapping Register using Addr = Register::Address<0xf003803c,0xfffffff8,0x00000000,unsigned>; ///PORT 0 DP/DM Pin Swapping enum class Port0Val { normal=0x00000000, ///<DP/DM normal pinout. swapped=0x00000001, ///<DP/DM swapped pinout. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,Port0Val> port0{}; namespace Port0ValC{ constexpr Register::FieldValue<decltype(port0)::Type,Port0Val::normal> normal{}; constexpr Register::FieldValue<decltype(port0)::Type,Port0Val::swapped> swapped{}; } ///PORT 1 DP/DM Pin Swapping enum class Port1Val { normal=0x00000000, ///<DP/DM normal pinout. swapped=0x00000001, ///<DP/DM swapped pinout. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,Port1Val> port1{}; namespace Port1ValC{ constexpr Register::FieldValue<decltype(port1)::Type,Port1Val::normal> normal{}; constexpr Register::FieldValue<decltype(port1)::Type,Port1Val::swapped> swapped{}; } ///PORT 2 DP/DM Pin Swapping enum class Port2Val { normal=0x00000000, ///<DP/DM normal pinout. swapped=0x00000001, ///<DP/DM swapped pinout. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,Port2Val> port2{}; namespace Port2ValC{ constexpr Register::FieldValue<decltype(port2)::Type,Port2Val::normal> normal{}; constexpr Register::FieldValue<decltype(port2)::Type,Port2Val::swapped> swapped{}; } } namespace SfrEbicfg{ ///<EBI Configuration Register using Addr = Register::Address<0xf0038040,0xfffee0e0,0x00000000,unsigned>; ///EBI Pins Drive Level enum class Drive0Val { low=0x00000000, ///<Low drive level medium=0x00000002, ///<Medium drive level high=0x00000003, ///<High drive level }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,Drive0Val> drive0{}; namespace Drive0ValC{ constexpr Register::FieldValue<decltype(drive0)::Type,Drive0Val::low> low{}; constexpr Register::FieldValue<decltype(drive0)::Type,Drive0Val::medium> medium{}; constexpr Register::FieldValue<decltype(drive0)::Type,Drive0Val::high> high{}; } ///EBI Pins Pull Value enum class Pull0Val { up=0x00000000, ///<Pull-up none=0x00000001, ///<No Pull down=0x00000003, ///<Pull-down }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,Pull0Val> pull0{}; namespace Pull0ValC{ constexpr Register::FieldValue<decltype(pull0)::Type,Pull0Val::up> up{}; constexpr Register::FieldValue<decltype(pull0)::Type,Pull0Val::none> none{}; constexpr Register::FieldValue<decltype(pull0)::Type,Pull0Val::down> down{}; } ///EBI Pins Schmitt Trigger constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> sch0{}; ///EBI Pins Drive Level enum class Drive1Val { low=0x00000000, ///<Low drive level medium=0x00000002, ///<Medium drive level high=0x00000003, ///<High drive level }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,Drive1Val> drive1{}; namespace Drive1ValC{ constexpr Register::FieldValue<decltype(drive1)::Type,Drive1Val::low> low{}; constexpr Register::FieldValue<decltype(drive1)::Type,Drive1Val::medium> medium{}; constexpr Register::FieldValue<decltype(drive1)::Type,Drive1Val::high> high{}; } ///EBI Pins Pull Value enum class Pull1Val { up=0x00000000, ///<Pull-up none=0x00000001, ///<No Pull down=0x00000003, ///<Pull-down }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,Pull1Val> pull1{}; namespace Pull1ValC{ constexpr Register::FieldValue<decltype(pull1)::Type,Pull1Val::up> up{}; constexpr Register::FieldValue<decltype(pull1)::Type,Pull1Val::none> none{}; constexpr Register::FieldValue<decltype(pull1)::Type,Pull1Val::down> down{}; } ///EBI Pins Schmitt Trigger constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> sch1{}; ///BMS Sampled Value (Read Only) enum class BmsVal { rom=0x00000000, ///<Boot on ROM. ebi=0x00000001, ///<Boot on EBI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,BmsVal> bms{}; namespace BmsValC{ constexpr Register::FieldValue<decltype(bms)::Type,BmsVal::rom> rom{}; constexpr Register::FieldValue<decltype(bms)::Type,BmsVal::ebi> ebi{}; } } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the class library */ /* SoPlex --- the Sequential object-oriented simPlex. */ /* */ /* Copyright (C) 1996-2018 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SoPlex is distributed under the terms of the ZIB Academic Licence. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with SoPlex; see the file COPYING. If not email to soplex@zib.de. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file rational.cpp * @brief Wrapper for GMP types. */ #ifndef SOPLEX_LEGACY #include <cmath> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <iomanip> #include <sstream> #include <cstring> #include <limits.h> #include "rational.h" #include "spxalloc.h" #include "spxdefines.h" #ifdef SOPLEX_WITH_GMP #include "gmp.h" #endif /// use mpq_sgn instead of mpq_equal to compare rationals with zero #define SOPLEX_PERFALT_1 /// turn on checking rationals for zero in arithmetic plus and minus operators #define SOPLEX_PERFALT_2a /// turn on checking rationals for zero, posone, negone in arithmetic multiplication and division operators #define SOPLEX_PERFALT_2b /// turn on checking rationals for zero, posone, negone before conversion to double and long double #define SOPLEX_PERFALT_3 /// turn on checking for equality before assigning in operator=() #define SOPLEX_PERFALT_4 /// turn on checking whether assignment in assignment operators is redundant for 0 #define SOPLEX_PERFALT_5a /// turn on checking whether assignment in assignment operators is redundant for +1 and -1 #define SOPLEX_PERFALT_5b namespace soplex { #ifdef SOPLEX_WITH_GMP /// rational zero const Rational Rational::ZERO(0, true); /// rational plus one const Rational Rational::POSONE(1, true); /// rational minus one const Rational Rational::NEGONE(-1, true); /// list of unused Private objects; note that this cannot be used if SOPLEX_WITH_GMP is not defined, since then the /// Private class has no member next() and prev() /// should list memory be used? #ifdef SOPLEX_NOLISTMEM THREADLOCAL bool Rational::useListMem = false; #else THREADLOCAL bool Rational::useListMem = true; #endif /// list of unused Private objects #ifdef SOPLEX_WITH_GMP THREADLOCAL IdList< Rational::Private > Rational::unusedPrivateList(0, 0, true); #endif /// Defines the "Pimpl"-class Private class Rational::Private { public: mpq_t privatevalue; ///< actual value of the Rational object Private* theprev; ///< pointer to the previous element in the list Private* thenext; ///< pointer to the next element in the list /// default constructor Private() : theprev(0) , thenext(0) { mpq_init(privatevalue); } /// copy constructor Private(const Private& p) : theprev(0) , thenext(0) { // a newly constructed element is not in any list, even if the original element (p) is; hence we initialize // theprev and thenext to zero mpq_init(privatevalue); mpq_set(this->privatevalue, p.privatevalue); } /// constructor from long double Private(const long double& r) : theprev(0) , thenext(0) { mpq_init(privatevalue); if( r == (long double)(1.0) ) mpq_set(privatevalue, Rational::POSONE.dpointer->privatevalue); else if( r == (long double)(-1.0) ) mpq_set(privatevalue, Rational::NEGONE.dpointer->privatevalue); else if( r == (long double)(0.0) ) { assert(mpq_equal(privatevalue, Rational::ZERO.dpointer->privatevalue) != 0); } else mpq_set_d(privatevalue, double(r)); } /// constructor from double Private(const double& r) : theprev(0) , thenext(0) { mpq_init(privatevalue); if( r == 1.0 ) mpq_set(privatevalue, Rational::POSONE.dpointer->privatevalue); else if( r == -1.0 ) mpq_set(privatevalue, Rational::NEGONE.dpointer->privatevalue); else if( r == 0.0 ) { assert(mpq_equal(privatevalue, Rational::ZERO.dpointer->privatevalue) != 0); } else mpq_set_d(privatevalue, r); } /// constructor from int Private(const int& i) : theprev(0) , thenext(0) { mpq_init(privatevalue); if( i == 1 ) mpq_set(privatevalue, Rational::POSONE.dpointer->privatevalue); else if( i == -1 ) mpq_set(privatevalue, Rational::NEGONE.dpointer->privatevalue); else if( i == 0 ) { assert(mpq_equal(privatevalue, Rational::ZERO.dpointer->privatevalue) != 0); } else mpq_set_si(privatevalue, i, 1); } /// constructor from mpq_t Private(const mpq_t& q) : theprev(0) , thenext(0) { mpq_init(privatevalue); mpq_set(privatevalue, q); } /// destructor ~Private() { mpq_clear(privatevalue); } /// assignment operator Private& operator=(const Private& p) { #ifdef SOPLEX_PERFALT_4 if( mpq_equal(this->privatevalue, p.privatevalue) != 0 ) return *this; #endif // we only assign the value; the position in the list, i.e., theprev and thenext, must not be modified mpq_set(this->privatevalue, p.privatevalue); return *this; } /// assignment operator from long double Private& operator=(const long double& r) { // we only assign the value; the position in the list, i.e., theprev and thenext, must not be modified if( r == (long double)(0.0) ) { #ifdef SOPLEX_PERFALT_5a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(privatevalue) != 0 ) #else if( mpq_equal(privatevalue, Rational::ZERO.dpointer->privatevalue) == 0 ) #endif #endif mpq_set(privatevalue, Rational::ZERO.dpointer->privatevalue); } else if( r == (long double)(1.0) ) { #ifdef SOPLEX_PERFALT_5b if( mpq_equal(privatevalue, Rational::POSONE.dpointer->privatevalue) == 0 ) #endif mpq_set(privatevalue, Rational::POSONE.dpointer->privatevalue); } else if( r == (long double)(-1.0) ) { #ifdef SOPLEX_PERFALT_5b if( mpq_equal(privatevalue, Rational::NEGONE.dpointer->privatevalue) == 0 ) #endif mpq_set(privatevalue, Rational::NEGONE.dpointer->privatevalue); } else mpq_set_d(this->privatevalue, double(r)); return *this; } /// assignment operator from double Private& operator=(const double& r) { // we only assign the value; the position in the list, i.e., theprev and thenext, must not be modified if( r == 0.0 ) { #ifdef SOPLEX_PERFALT_5a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(privatevalue) != 0 ) #else if( mpq_equal(privatevalue, Rational::ZERO.dpointer->privatevalue) == 0 ) #endif #endif mpq_set(privatevalue, Rational::ZERO.dpointer->privatevalue); } else if( r == 1.0 ) { #ifdef SOPLEX_PERFALT_5b if( mpq_equal(privatevalue, Rational::POSONE.dpointer->privatevalue) == 0 ) #endif mpq_set(privatevalue, Rational::POSONE.dpointer->privatevalue); } else if( r == -1.0 ) { #ifdef SOPLEX_PERFALT_5b if( mpq_equal(privatevalue, Rational::NEGONE.dpointer->privatevalue) == 0 ) #endif mpq_set(privatevalue, Rational::NEGONE.dpointer->privatevalue); } else mpq_set_d(privatevalue, r); return *this; } /// assignment operator from int Private& operator=(const int& i) { // we only assign the value; the position in the list, i.e., theprev and thenext, must not be modified if( i == 0 ) { #ifdef SOPLEX_PERFALT_5a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(privatevalue) != 0 ) #else if( mpq_equal(privatevalue, Rational::ZERO.dpointer->privatevalue) == 0 ) #endif #endif mpq_set(privatevalue, Rational::ZERO.dpointer->privatevalue); } else if( i == 1 ) { #ifdef SOPLEX_PERFALT_5b if( mpq_equal(privatevalue, Rational::POSONE.dpointer->privatevalue) == 0 ) #endif mpq_set(privatevalue, Rational::POSONE.dpointer->privatevalue); } else if( i == -1 ) { #ifdef SOPLEX_PERFALT_5b if( mpq_equal(privatevalue, Rational::NEGONE.dpointer->privatevalue) == 0 ) #endif mpq_set(privatevalue, Rational::NEGONE.dpointer->privatevalue); } else mpq_set_si(privatevalue, i, 1); return *this; } /// assignment operator from mpq_t Private& operator=(const mpq_t& q) { #ifdef SOPLEX_PERFALT_4 if( mpq_equal(this->privatevalue, q) != 0 ) return *this; #endif // we only assign the value; the position in the list, i.e., theprev and thenext, must not be modified mpq_set(this->privatevalue, q); return *this; } /// previous Private element Private*& prev() { return theprev; } /// previous Private element Private* const& prev() const { return theprev; } /// next Private element Private*& next() { return thenext; } /// next Private element Private* const& next() const { return thenext; } }; /// special constructor only for initializing static rational variables; this is necessary since we need a constructor /// for Rational::{ZERO, POSONE, NEGONE} that does not use these numbers Rational::Rational(const int& i, const bool& dummy) { dpointer = 0; spx_alloc(dpointer); new (dpointer) Private(); mpq_set_si(dpointer->privatevalue, i, 1); assert(dpointer != 0); } /// default constructor Rational::Rational() { if( Rational::useListMem ) { dpointer = unusedPrivateList.last(); if( dpointer != 0 ) { assert(unusedPrivateList.first() != 0); unusedPrivateList.remove(dpointer); } else { assert(unusedPrivateList.first() == 0); spx_alloc(dpointer); new (dpointer) Private(); } } else { assert(unusedPrivateList.length() == 0); dpointer = 0; spx_alloc(dpointer); new (dpointer) Private(); } assert(dpointer != 0); } /// copy constructor Rational::Rational(const Rational& r) { if( Rational::useListMem ) { dpointer = unusedPrivateList.last(); if( dpointer != 0 ) { assert(unusedPrivateList.first() != 0); unusedPrivateList.remove(dpointer); *dpointer = *(r.dpointer); } else { assert(unusedPrivateList.first() == 0); spx_alloc(dpointer); new (dpointer) Private(*(r.dpointer)); } } else { assert(unusedPrivateList.length() == 0); dpointer = 0; spx_alloc(dpointer); new (dpointer) Private(*(r.dpointer)); } assert(dpointer != 0); } /// constructor from long double Rational::Rational(const long double& r) { if( Rational::useListMem ) { dpointer = unusedPrivateList.last(); if( dpointer != 0 ) { assert(unusedPrivateList.first() != 0); unusedPrivateList.remove(dpointer); *dpointer = r; } else { assert(unusedPrivateList.first() == 0); spx_alloc(dpointer); new (dpointer) Private(r); } } else { assert(unusedPrivateList.length() == 0); dpointer = 0; spx_alloc(dpointer); new (dpointer) Private(r); } assert(dpointer != 0); } /// constructor from double Rational::Rational(const double& r) { if( Rational::useListMem ) { dpointer = unusedPrivateList.last(); if( dpointer != 0 ) { assert(unusedPrivateList.first() != 0); unusedPrivateList.remove(dpointer); *dpointer = r; } else { assert(unusedPrivateList.first() == 0); spx_alloc(dpointer); new (dpointer) Private(r); } } else { assert(unusedPrivateList.length() == 0); dpointer = 0; spx_alloc(dpointer); new (dpointer) Private(r); } assert(dpointer != 0); } /// constructor from int Rational::Rational(const int& i) { if( Rational::useListMem ) { dpointer = unusedPrivateList.last(); if( dpointer != 0 ) { assert(unusedPrivateList.first() != 0); unusedPrivateList.remove(dpointer); *dpointer = i; } else { assert(unusedPrivateList.first() == 0); spx_alloc(dpointer); new (dpointer) Private(i); } } else { assert(unusedPrivateList.length() == 0); dpointer = 0; spx_alloc(dpointer); new (dpointer) Private(i); } assert(dpointer != 0); } /// constructor from mpq_t Rational::Rational(const mpq_t& q) { if( Rational::useListMem ) { dpointer = unusedPrivateList.last(); if( dpointer != 0 ) { assert(unusedPrivateList.first() != 0); unusedPrivateList.remove(dpointer); *dpointer = q; } else { assert(unusedPrivateList.first() == 0); spx_alloc(dpointer); new (dpointer) Private(q); } } else { assert(unusedPrivateList.length() == 0); dpointer = 0; spx_alloc(dpointer); new (dpointer) Private(q); } assert(dpointer != 0); } /// destructor Rational::~Rational() { assert(Rational::useListMem || unusedPrivateList.length() == 0); if( !Rational::useListMem || this == &Rational::ZERO || this == &Rational::POSONE || this == &Rational::NEGONE ) { dpointer->~Private(); spx_free(dpointer); } else { // for memory efficiency, we could free the Private object (or even more Private objects from the list of unused // elements) if there are much more unused than used Private objects; this requires counting the used Private // objects, though; we do not implement this currently, because we have not encountered memory problems, so far, and // because freeing costs time unusedPrivateList.append(dpointer); } } /// enables list memory void Rational::enableListMem() { assert(Rational::useListMem || unusedPrivateList.length() == 0); Rational::useListMem = true; } /// frees the unused rational elements in the memory list /// frees the unused rational elements in the memory list /** this can be useful when you want to save memory or needed when working with a GMP memory manager like the one * in EGlib that frees GMP memory before the destructor of the static memory list is called; in most cases this * method is optional; note that this does not free the Rational elements that are currently in use */ void Rational::freeListMem() { unusedPrivateList.clear(true); assert(unusedPrivateList.length() == 0); } /// disables list memory void Rational::disableListMem() { Rational::freeListMem(); Rational::useListMem = false; } /// assignment operator Rational& Rational::operator=(const Rational &r) { *(this->dpointer) = *(r.dpointer); return *this; } /// assignment operator from long double Rational& Rational::operator=(const long double &r) { *(this->dpointer) = r; return *this; } /// assignment operator from double Rational& Rational::operator=(const double &r) { *(this->dpointer) = r; return *this; } /// assignment operator from int Rational& Rational::operator=(const int &i) { *(this->dpointer) = i; return *this; } /// assignment operator from mpq_t Rational& Rational::operator=(const mpq_t &q) { *(this->dpointer) = q; return *this; } /// typecasts Rational to double (allows only explicit typecast) Rational::operator double() const { #ifdef SOPLEX_PERFALT_3 #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) #endif return 0.0; else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return 1.0; else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) return -1.0; #endif return mpq_get_d(this->dpointer->privatevalue); } /// typecasts Rational to long double (allows only explicit typecast) Rational::operator long double() const { #ifdef SOPLEX_PERFALT_3 #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) #endif return 0.0; else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return 1.0; else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) return -1.0; #endif return (long double)mpq_get_d(this->dpointer->privatevalue); } /// provides read-only access to underlying mpq_t const mpq_t* Rational::getMpqPtr() const { return &(this->dpointer->privatevalue); } /// provides read-only access to underlying mpq_t const mpq_t& Rational::getMpqRef() const { return this->dpointer->privatevalue; } /// provides write access to underlying mpq_t; use with care mpq_t* Rational::getMpqPtr_w() const { return &(this->dpointer->privatevalue); } /// provides write access to underlying mpq_t; use with care mpq_t& Rational::getMpqRef_w() const { return this->dpointer->privatevalue; } /// addition operator Rational Rational::operator+(const Rational& r) const { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; else if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return r; #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return r; #endif #endif Rational retval; mpq_add(retval.dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return retval; } /// addition assignment operator Rational& Rational::operator+=(const Rational& r) { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; else if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return (*this = r); #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return (*this = r); #endif #endif mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } /// addition operator for doubles Rational Rational::operator+(const double& d) const { if( d == 0.0 ) return *this; else { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return d; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return d; #endif #endif Rational retval(d); mpq_add(retval.dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } } /// addition assignment operator for doubles Rational& Rational::operator+=(const double& d) { if( d == 1.0 ) return (*this += Rational::POSONE); else if( d == -1.0 ) return (*this += Rational::NEGONE); else if( d != 0.0 ) { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return (*this = d); #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return (*this = d); #endif #endif Rational retval(d); mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); } return *this; } /// addition operator for ints Rational Rational::operator+(const int& d) const { if( d == 0 ) return *this; else { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return d; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return d; #endif #endif Rational retval(d); mpq_add(retval.dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } } /// addition assignment operator for ints Rational& Rational::operator+=(const int& d) { if( d == 1 ) return (*this += Rational::POSONE); else if( d == -1 ) return (*this += Rational::NEGONE); else if( d != 0 ) { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return (*this = d); #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return (*this = d); #endif #endif Rational retval(d); mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); } return *this; } /// subtraction operator Rational Rational::operator-(const Rational& r) const { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; else if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return -r; #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return -r; #endif #endif Rational retval; mpq_sub(retval.dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return retval; } /// subtraction assignment operator Rational& Rational::operator-=(const Rational& r) { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; else if( mpq_sgn(this->dpointer->privatevalue) == 0 ) { *this = r; *this *= -1; return *this; } #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) { *this = r; *this *= -1; return *this; } #endif #endif mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } /// subtraction operator for doubles Rational Rational::operator-(const double& d) const { if( d == 0.0 ) return *this; else { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return -d; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return -d; #endif #endif Rational retval(d); mpq_sub(retval.dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } } /// subtraction assignment operator for doubles Rational& Rational::operator-=(const double& d) { if( d == 1.0 ) return (*this -= Rational::POSONE); else if( d == -1.0 ) return (*this -= Rational::NEGONE); else if( d != 0.0 ) { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return (*this = -d); #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return (*this = -d); #endif #endif Rational retval(d); mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); } return *this; } /// subtraction operator for ints Rational Rational::operator-(const int& d) const { if( d == 0 ) return *this; else { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return -d; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return -d; #endif #endif Rational retval(d); mpq_sub(retval.dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } } /// subtraction assignment operator for ints Rational& Rational::operator-=(const int& d) { if( d == 1 ) return (*this -= Rational::POSONE); else if( d == -1 ) return (*this -= Rational::NEGONE); else if( d != 0 ) { #ifdef SOPLEX_PERFALT_2a #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return (*this = -d); #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return (*this = -d); #endif #endif Rational retval(d); mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); } return *this; } /// multiplication operator Rational Rational::operator*(const Rational& r) const { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return Rational::ZERO; else if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return Rational::ZERO; #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return Rational::ZERO; else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return Rational::ZERO; #endif else if( mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return r; else if( mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) return -*this; else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) return -r; #endif Rational retval; mpq_mul(retval.dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return retval; } /// multiplication assignment operator Rational& Rational::operator*=(const Rational& r) { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return (*this = Rational::ZERO); else if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return (*this = Rational::ZERO); else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return (*this = r); else if( mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_neg(this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } #endif mpq_mul(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } /// multiplication operator for doubles Rational Rational::operator*(const double& d) const { if( d == 0.0 ) return Rational::ZERO; else if( d == 1.0 ) return *this; else if( d == -1.0 ) { Rational retval; mpq_neg(retval.dpointer->privatevalue, this->dpointer->privatevalue); return retval; } else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return Rational::ZERO; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return Rational::ZERO; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return d; else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) return -d; #endif Rational retval(d); mpq_mul(retval.dpointer->privatevalue, retval.dpointer->privatevalue, this->dpointer->privatevalue); return retval; } } /// multiplication assignment operator for doubles Rational& Rational::operator*=(const double& d) { if( d == 0.0 ) return (*this = Rational::ZERO); else if( d == 1.0 ) return *this; else if( d == -1.0 ) { mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return (*this = d); else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { *this = d; mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } #endif Rational retval(d); mpq_mul(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return *this; } } /// multiplication operator for ints Rational Rational::operator*(const int& d) const { if( d == 0 ) return Rational::ZERO; else if( d == 1 ) return *this; else if( d == -1 ) { Rational retval; mpq_neg(retval.dpointer->privatevalue, this->dpointer->privatevalue); return retval; } else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return Rational::ZERO; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return Rational::ZERO; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return d; else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) return -d; #endif Rational retval(d); mpq_mul(retval.dpointer->privatevalue, retval.dpointer->privatevalue, this->dpointer->privatevalue); return retval; } } /// multiplication assignment operator for ints Rational& Rational::operator*=(const int& d) { if( d == 0 ) return (*this = Rational::ZERO); else if( d == 1 ) return *this; else if( d == -1 ) { mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return (*this = d); else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { *this = d; mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } #endif Rational retval(d); mpq_mul(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return *this; } } /// division operator Rational Rational::operator/(const Rational& r) const { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return Rational::ZERO; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return Rational::ZERO; #endif else if( mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { Rational retval(r); retval.invert(); return retval; } else if( mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) return -*this; else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { Rational retval(r); retval.invert(); mpq_neg(retval.dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } #endif Rational retval; mpq_div(retval.dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return retval; } /// division assignment operator Rational& Rational::operator/=(const Rational& r) { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { mpq_inv(this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_inv(this->dpointer->privatevalue, r.dpointer->privatevalue); mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } #endif mpq_div(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } /// division operator for doubles Rational Rational::operator/(const double& d) const { if( d == 1.0 ) return *this; else if( d == -1.0 ) return -(*this); else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return Rational::ZERO; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return Rational::ZERO; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { Rational retval(d); retval.invert(); return retval; } else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { Rational retval(d); retval.invert(); mpq_neg(retval.dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } #endif Rational retval(d); mpq_div(retval.dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } } /// division assignment operator for doubles Rational& Rational::operator/=(const double& d) { if( d == 1.0 ) return *this; else if( d == -1.0 ) { mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { *this = d; this->invert(); return *this; } else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { *this = -d; this->invert(); return *this; } #endif Rational retval(d); mpq_div(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return *this; } } /// division operator for ints Rational Rational::operator/(const int& d) const { if( d == 1 ) return *this; else if( d == -1 ) return -(*this); else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return Rational::ZERO; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return Rational::ZERO; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { Rational retval(d); retval.invert(); return retval; } else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { Rational retval(d); retval.invert(); mpq_neg(retval.dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } #endif Rational retval(d); mpq_div(retval.dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } } /// division assignment operator for ints Rational& Rational::operator/=(const int& d) { if( d == 1 ) return *this; else if( d == -1 ) { mpq_neg(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } else { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(this->dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(this->dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(this->dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { *this = d; this->invert(); return *this; } else if( mpq_equal(this->dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { *this = -d; this->invert(); return *this; } #endif Rational retval(d); mpq_div(this->dpointer->privatevalue, this->dpointer->privatevalue, retval.dpointer->privatevalue); return *this; } } /// add product of two rationals Rational& Rational::addProduct(const Rational& r, const Rational& s) { #ifdef SOPLEX_PERFALT_2b if( mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, s.dpointer->privatevalue); return *this; } else if( mpq_equal(s.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } else if( mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, s.dpointer->privatevalue); return *this; } else if( mpq_equal(s.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } #if 0 // currently, SoPlex calls this method only with nonzero r and s, hence we do not check this case #ifdef SOPLEX_PERFALT_1 else if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; else if( mpq_sgn(s.dpointer->privatevalue) == 0 ) return *this; #else else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(s.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif #endif #endif Rational product(r); mpq_mul(product.dpointer->privatevalue, product.dpointer->privatevalue, s.dpointer->privatevalue); mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, product.dpointer->privatevalue); return *this; } /// subtract product of two rationals Rational& Rational::subProduct(const Rational& r, const Rational& s) { #ifdef SOPLEX_PERFALT_2b if( mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, s.dpointer->privatevalue); return *this; } else if( mpq_equal(s.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } else if( mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, s.dpointer->privatevalue); return *this; } else if( mpq_equal(s.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } #if 0 // currently, SoPlex calls this method only with nonzero r and s, hence we do not check this case #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; else if( mpq_sgn(s.dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; else if( mpq_equal(s.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif #endif #endif Rational product(r); mpq_mul(product.dpointer->privatevalue, product.dpointer->privatevalue, s.dpointer->privatevalue); mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, product.dpointer->privatevalue); return *this; } /// add quotient of two rationals, r divided by s Rational& Rational::addQuotient(const Rational& r, const Rational& s) { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(s.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } else if( mpq_equal(s.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } #endif Rational quotient(r); mpq_div(quotient.dpointer->privatevalue, quotient.dpointer->privatevalue, s.dpointer->privatevalue); mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, quotient.dpointer->privatevalue); return *this; } /// subtract quotient of two rationals, r divided by s Rational& Rational::subQuotient(const Rational& r, const Rational& s) { #ifdef SOPLEX_PERFALT_2b #ifdef SOPLEX_PERFALT_1 if( mpq_sgn(r.dpointer->privatevalue) == 0 ) return *this; #else if( mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0 ) return *this; #endif else if( mpq_equal(s.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0 ) { mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } else if( mpq_equal(s.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0 ) { mpq_add(this->dpointer->privatevalue, this->dpointer->privatevalue, r.dpointer->privatevalue); return *this; } #endif Rational quotient(r); mpq_div(quotient.dpointer->privatevalue, quotient.dpointer->privatevalue, s.dpointer->privatevalue); mpq_sub(this->dpointer->privatevalue, this->dpointer->privatevalue, quotient.dpointer->privatevalue); return *this; } /// inversion Rational& Rational::invert() { mpq_inv(this->dpointer->privatevalue, this->dpointer->privatevalue); return *this; } /// round up to next power of two Rational& Rational::powRound() { mpz_t roundval; MSG_DEBUG( std::cout << "rounding " << rationalToString(this->dpointer->privatevalue) << " to power of two" << "\n" ); mpz_init(roundval); mpz_cdiv_q(roundval, mpq_numref(this->dpointer->privatevalue), mpq_denref(this->dpointer->privatevalue)); mpz_sub_ui(roundval, roundval, 1); MSG_DEBUG( std::cout << " --> " << mpz_get_str(0, 10, roundval) << "\n" ); size_t binlog = mpz_sizeinbase(roundval, 2); MSG_DEBUG( std::cout << " --> 2^" << binlog << "\n" ); mpz_ui_pow_ui(roundval, 2, binlog); MSG_DEBUG( std::cout << " --> " << mpz_get_str(0, 10, roundval) << "\n" ); mpq_set_z(this->dpointer->privatevalue, roundval); mpz_clear(roundval); MSG_DEBUG( std::cout << " --> " << rationalToString(this->dpointer->privatevalue) << "\n" ); return *this; } /// checks if d is the closest possible double bool Rational::isNextTo(const double& d) { // get intervall [a,b] of doubles that the Rational is in double x = mpq_get_d(this->dpointer->privatevalue); double a; double b; if( Rational(x) < *this ) { a = x; b = (double)spxNextafter(a, infinity); } else { b = x; a = (double)spxNextafter(b, -infinity); } // check if d equals the closer end of the intervall bool result = (spxAbs(*this - a) < spxAbs(*this - b)) ? (d == a) : (d == b); return result; } /// checks if d is exactly equal to the Rational and if not, if it is one of the two adjacent doubles bool Rational::isAdjacentTo(const double& d) const { double x = mpq_get_d(this->dpointer->privatevalue); double a; double b; mpq_t tmp; mpq_init(tmp); mpq_set_d(tmp, x); int cmp = mpq_cmp(tmp, this->dpointer->privatevalue); mpq_clear(tmp); // the rounded value is smaller than the rational value if( cmp < 0 ) { a = x; b = (double)spxNextafter(a, infinity); } // the rounded value is larger than the rational value else if( cmp > 0 ) { b = x; a = (double)spxNextafter(b, -infinity); } // the rational value is representable in double precision else return (x == d); return ((a == d) || (b == d)); } /// Size in specified base (bit size for base 2) int Rational::sizeInBase(const int base) const { return (int)mpz_sizeinbase(mpq_numref(this->dpointer->privatevalue), base) + (int)mpz_sizeinbase(mpq_denref(this->dpointer->privatevalue), base); } /// returns precision of Rational implementation, i.e., number of bits used to store Rational numbers (INT_MAX if exact) int Rational::precision() { return INT_MAX; } #define MAX_STR_LEN 10000 /// read Rational from string bool Rational::readString(const char* s) { assert(s != 0); assert(strlen(s) <= MAX_STR_LEN); Rational value; const char* pos; // if there is a slash or there is no dot and exponent (i.e. we // have an integer), we may simply call GMP's string reader if( strchr(s, '/') != 0 || strpbrk(s, ".eE") == 0 ) { pos = (*s == '+') ? s + 1 : s; if( mpq_set_str(value.dpointer->privatevalue, pos, 10) == 0 ) { mpq_canonicalize(value.dpointer->privatevalue); mpq_set(this->dpointer->privatevalue, value.dpointer->privatevalue); return true; } else return false; } // otherwise we analyze the string #ifndef NDEBUG bool has_exponent = false; bool has_dot = false; #endif bool has_digits = false; bool has_emptyexponent = false; long int exponent = 0; long int decshift = 0; mpz_t shiftpower; mpz_init(shiftpower); mpq_t shiftpowerRational; mpq_init(shiftpowerRational); char* t; char tmp[MAX_STR_LEN]; pos = s; // 1. sign if( (*pos == '+') || (*pos == '-') ) pos++; // 2. Digits before the decimal dot while( (*pos >= '0') && (*pos <= '9') ) { has_digits = true; pos++; } // 3. Decimal dot if( *pos == '.' ) { #ifndef NDEBUG has_dot = true; #endif pos++; // 4. If there was a dot, possible digit behind it while( (*pos >= '0') && (*pos <= '9') ) { has_digits = true; pos++; } } // 5. Exponent if( tolower(*pos) == 'e' ) { #ifndef NDEBUG has_exponent = true; #endif has_emptyexponent = true; pos++; // 6. Exponent sign if( (*pos == '+') || (*pos == '-') ) pos++; // 7. Exponent digits while( (*pos >= '0') && (*pos <= '9') ) { has_emptyexponent = false; pos++; } } if( has_emptyexponent || !has_digits ) return false; assert(has_exponent || has_dot); //read up to dot recording digits t = tmp; pos = s; if( *pos == '+' ) pos++; while( ((*pos >= '0') && (*pos <= '9') ) || *pos == '+' || *pos == '-' ) { *t++ = *pos; pos++; } //record digits after dot, recording positions decshift = 0; if( *pos == '.' ) { assert(has_dot); pos++; while( (*pos >= '0') && (*pos <= '9') ) { *t++ = *pos; decshift++; pos++; } } *t = '\0'; if( mpq_set_str(value.dpointer->privatevalue, tmp, 10) != 0) return false; mpq_canonicalize(value.dpointer->privatevalue); //record exponent and update final result exponent = -decshift; if( tolower(*pos) == 'e' ) { pos++; assert(has_exponent); for( t = tmp; *pos != '\0'; pos++ ) *t++ = *pos; *t = '\0'; exponent += atol(tmp); } if( exponent > 0 ) { mpz_ui_pow_ui(shiftpower, 10, exponent); mpq_set_z(shiftpowerRational, shiftpower); mpq_mul(value.dpointer->privatevalue, value.dpointer->privatevalue, shiftpowerRational); } else if( exponent < 0 ) { mpz_ui_pow_ui(shiftpower, 10, -exponent); mpq_set_z(shiftpowerRational, shiftpower); mpq_div(value.dpointer->privatevalue, value.dpointer->privatevalue, shiftpowerRational); } mpq_canonicalize(value.dpointer->privatevalue); mpq_set(this->dpointer->privatevalue, value.dpointer->privatevalue); mpz_clear(shiftpower); mpq_clear(shiftpowerRational); return true; } /// convert rational number to string std::string rationalToString(const Rational& r, const int precision) { #if defined(_WIN32) || defined(_WIN64) || defined(__APPLE__) std::stringstream sstream; sstream << r; return sstream.str(); #else if( precision <= 0 ) { std::stringstream sstream; sstream << r; return sstream.str(); } else { mpf_t tmpFloat; char tmpString[64]; FILE* tmpStream; tmpStream = fmemopen(tmpString, 63, "w"); mpf_init2(tmpFloat, 256); mpf_set_q(tmpFloat, r.dpointer->privatevalue); mpf_out_str(tmpStream, 10, precision, tmpFloat); mpf_clear(tmpFloat); fflush(tmpStream); std::string retString = std::string(tmpString); fclose(tmpStream); return retString; } #endif } /// read Rational from string bool readStringRational(const char* s, Rational& value) { assert(s != 0); assert(strlen(s) <= MAX_STR_LEN); const char* pos; // if there is a slash or there is no dot and exponent (i.e. we // have an integer), we may simply call GMP's string reader if( strchr(s, '/') != 0 || strpbrk(s, ".eE") == 0 ) { pos = (*s == '+') ? s + 1 : s; if( mpq_set_str(value.dpointer->privatevalue, pos, 10) == 0 ) { mpq_canonicalize(value.dpointer->privatevalue); return true; } else return false; } // otherwise we analyze the string #ifndef NDEBUG bool has_exponent = false; bool has_dot = false; #endif bool has_digits = false; bool has_emptyexponent = false; long int exponent = 0; long int decshift = 0; mpz_t shiftpower; mpz_init(shiftpower); mpq_t shiftpowerRational; mpq_init(shiftpowerRational); char* t; char tmp[MAX_STR_LEN]; pos = s; // 1. sign if( (*pos == '+') || (*pos == '-') ) pos++; // 2. Digits before the decimal dot while( (*pos >= '0') && (*pos <= '9') ) { has_digits = true; pos++; } // 3. Decimal dot if( *pos == '.' ) { #ifndef NDEBUG has_dot = true; #endif pos++; // 4. If there was a dot, possible digit behind it while( (*pos >= '0') && (*pos <= '9') ) { has_digits = true; pos++; } } // 5. Exponent if( tolower(*pos) == 'e' ) { #ifndef NDEBUG has_exponent = true; #endif has_emptyexponent = true; pos++; // 6. Exponent sign if( (*pos == '+') || (*pos == '-') ) pos++; // 7. Exponent digits while( (*pos >= '0') && (*pos <= '9') ) { has_emptyexponent = false; pos++; } } if( has_emptyexponent || !has_digits ) return false; assert(has_exponent || has_dot); // read up to dot recording digits t = tmp; pos = s; if( *pos == '+' ) pos++; while( ((*pos >= '0') && (*pos <= '9') ) || *pos == '+' || *pos == '-' ) { *t++ = *pos; pos++; } // record digits after dot, recording positions decshift = 0; if( *pos == '.' ) { assert(has_dot); pos++; while( (*pos >= '0') && (*pos <= '9') ) { *t++ = *pos; decshift++; pos++; } } *t = '\0'; if( mpq_set_str(value.dpointer->privatevalue, tmp, 10) != 0) return false; mpq_canonicalize(value.dpointer->privatevalue); // record exponent and update final result exponent = -decshift; if( tolower(*pos) == 'e' ) { pos++; assert(has_exponent); for( t = tmp; *pos != '\0'; pos++ ) *t++ = *pos; *t = '\0'; exponent += atol(tmp); } if( exponent > 0 ) { mpz_ui_pow_ui(shiftpower, 10, exponent); mpq_set_z(shiftpowerRational, shiftpower); mpq_mul(value.dpointer->privatevalue, value.dpointer->privatevalue, shiftpowerRational); } else if( exponent < 0 ) { mpz_ui_pow_ui(shiftpower, 10, -exponent); mpq_set_z(shiftpowerRational, shiftpower); mpq_div(value.dpointer->privatevalue, value.dpointer->privatevalue, shiftpowerRational); } mpq_canonicalize(value.dpointer->privatevalue); mpz_clear(shiftpower); mpq_clear(shiftpowerRational); return true; } /// print Rational std::ostream& operator<<(std::ostream& os, const Rational& r) { char* buffer; buffer = (char*) malloc (mpz_sizeinbase(mpq_numref(r.dpointer->privatevalue), 10) + mpz_sizeinbase(mpq_denref(r.dpointer->privatevalue), 10) + 3); os << mpq_get_str(buffer, 10, r.dpointer->privatevalue); free(buffer); return os; } /// comparison operator returning a positive value if r > s, zero if r = s, and a negative value if r < s int compareRational(const Rational& r, const Rational& s) { return mpq_cmp(r.dpointer->privatevalue, s.dpointer->privatevalue); } /// equality operator bool operator==(const Rational& r, const Rational& s) { return (mpq_equal(r.dpointer->privatevalue, s.dpointer->privatevalue) != 0); } /// inequality operator bool operator!=(const Rational& r, const Rational& s) { return (mpq_equal(r.dpointer->privatevalue, s.dpointer->privatevalue) == 0); } /// less than operator bool operator<(const Rational& r, const Rational& s) { return (mpq_cmp(r.dpointer->privatevalue, s.dpointer->privatevalue) < 0); } /// less than or equal to operator bool operator<=(const Rational& r, const Rational& s) { return (mpq_cmp(r.dpointer->privatevalue, s.dpointer->privatevalue) <= 0); } /// greater than operator bool operator>(const Rational& r, const Rational& s) { return (mpq_cmp(r.dpointer->privatevalue, s.dpointer->privatevalue) > 0); } /// greater than or equal to operator bool operator>=(const Rational& r, const Rational& s) { return (mpq_cmp(r.dpointer->privatevalue, s.dpointer->privatevalue) >= 0); } /// equality operator for Rational and double bool operator==(const Rational& r, const double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == 0); #else return (mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0); #endif else if( s == 1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0); else if( s == -1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0); else return (r == Rational(s)); } /// inequality operator for Rational and double bool operator!=(const Rational& r, const double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) != 0); #else return (mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) == 0); #endif else if( s == 1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) == 0); else if( s == -1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) == 0); else return (r != Rational(s)); } /// less than operator for Rational and double bool operator<(const Rational& r, const double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == -1); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) < 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) < 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) < 0); else return (r < Rational(s)); } /// less than or equal to operator for Rational and double bool operator<=(const Rational& r, const double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) <= 0); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) <= 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) <= 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) <= 0); else return (r <= Rational(s)); } /// greater than operator for Rational and double bool operator>(const Rational& r, const double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == 1); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) > 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) > 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) > 0); else return (r > Rational(s)); } /// greater than or equal to operator for Rational and double bool operator>=(const Rational& r, const double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) >= 0); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) >= 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) >= 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) >= 0); else return (r >= Rational(s)); } /// equality operator for double and Rational bool operator==(const double& r, const Rational& s) { return (s == r); } /// inequality operator double and Rational bool operator!=(const double& r, const Rational& s) { return (s != r); } /// less than operator double and Rational bool operator<(const double& r, const Rational& s) { return (s > r); } /// less than or equal to operator double and Rational bool operator<=(const double& r, const Rational& s) { return (s >= r); } /// greater than operator double and Rational bool operator>(const double& r, const Rational& s) { return (s < r); } /// greater than or equal to operator double and Rational bool operator>=(const double& r, const Rational& s) { return (s <= r); } /// equality operator for Rational and long double bool operator==(const Rational& r, const long double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == 0); #else return (mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0); #endif else if( s == 1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0); else if( s == -1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0); else return (r == Rational(s)); } /// inequality operator for Rational and long double bool operator!=(const Rational& r, const long double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) != 0); #else return (mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) == 0); #endif else if( s == 1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) == 0); else if( s == -1.0 ) return (mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) == 0); else return (r != Rational(s)); } /// less than operator for Rational and long double bool operator<(const Rational& r, const long double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == -1); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) < 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) < 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) < 0); else return (r < Rational(s)); } /// less than or equal to operator for Rational and long double bool operator<=(const Rational& r, const long double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) <= 0); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) <= 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) <= 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) <= 0); else return (r <= Rational(s)); } /// greater than operator for Rational and long double bool operator>(const Rational& r, const long double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == 1); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) > 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) > 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) > 0); else return (r > Rational(s)); } /// greater than or equal to operator for Rational and long double bool operator>=(const Rational& r, const long double& s) { if( s == 0.0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) >= 0); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) >= 0); #endif else if( s == 1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) >= 0); else if( s == -1.0 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) >= 0); else return (r >= Rational(s)); } /// equality operator for long double and Rational bool operator==(const long double& r, const Rational& s) { return (s == r); } /// inequality operator for long double and Rational bool operator!=(const long double& r, const Rational& s) { return (s != r); } /// less than operator for long double and Rational bool operator<(const long double& r, const Rational& s) { return (s > r); } /// less than or equal to operator for long double and Rational bool operator<=(const long double& r, const Rational& s) { return (s >= r); } /// greater than operator for long double and Rational bool operator>(const long double& r, const Rational& s) { return (s < r); } /// greater than or equal to operator for long double and Rational bool operator>=(const long double& r, const Rational& s) { return (s <= r); } /// addition operator for double and Rational Rational operator+(const double& d, const Rational& r) { return (r + d); } /// subtraction operator for double and Rational Rational operator-(const double& d, const Rational& r) { Rational res(r); mpq_neg(res.dpointer->privatevalue, res.dpointer->privatevalue); res += d; return res; } /// multiplication operator for double and Rational Rational operator*(const double& d, const Rational& r) { if( d == 0.0 ) return Rational::ZERO; else if( d == 1.0 ) return r; else if( d == -1.0 ) return -r; else { Rational retval(d); mpq_mul(retval.dpointer->privatevalue, retval.dpointer->privatevalue, r.dpointer->privatevalue); return retval; } } /// division operator for double and Rational Rational operator/(const double& d, const Rational& r) { if( d == 0.0 ) return Rational::ZERO; else if( d == 1.0 ) { Rational retval(r); retval.invert(); return retval; } else if( d == -1.0 ) { Rational retval(r); retval.invert(); mpq_neg(retval.dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } else { Rational retval(d); mpq_div(retval.dpointer->privatevalue, retval.dpointer->privatevalue, r.dpointer->privatevalue); return retval; } } /// equality operator for Rational and int bool operator==(const Rational& r, const int& s) { if( s == 0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == 0); #else return (mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) != 0); #endif else if( s == 1 ) return (mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) != 0); else if( s == -1 ) return (mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) != 0); else return (r == Rational(s)); } /// inequality operator for Rational and int bool operator!=(const Rational& r, const int& s) { if( s == 0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) != 0); #else return (mpq_equal(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) == 0); #endif else if( s == 1 ) return (mpq_equal(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) == 0); else if( s == -1 ) return (mpq_equal(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) == 0); else return (r != Rational(s)); } /// less than operator for Rational and int bool operator<(const Rational& r, const int& s) { if( s == 0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == -1); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) < 0); #endif else if( s == 1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) < 0); else if( s == -1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) < 0); else return (r < Rational(s)); } /// less than or equal to operator for Rational and int bool operator<=(const Rational& r, const int& s) { if( s == 0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) <= 0); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) <= 0); #endif else if( s == 1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) <= 0); else if( s == -1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) <= 0); else return (r <= Rational(s)); } /// greater than operator for Rational and int bool operator>(const Rational& r, const int& s) { if( s == 0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) == 1); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) > 0); #endif else if( s == 1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) > 0); else if( s == -1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) > 0); else return (r > Rational(s)); } /// greater than or equal to operator for Rational and int bool operator>=(const Rational& r, const int& s) { if( s == 0 ) #ifdef SOPLEX_PERFALT_1 return (mpq_sgn(r.dpointer->privatevalue) >= 0); #else return (mpq_cmp(r.dpointer->privatevalue, Rational::ZERO.dpointer->privatevalue) >= 0); #endif else if( s == 1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::POSONE.dpointer->privatevalue) >= 0); else if( s == -1 ) return (mpq_cmp(r.dpointer->privatevalue, Rational::NEGONE.dpointer->privatevalue) >= 0); else return (r >= Rational(s)); } /// equality operator for int and Rational bool operator==(const int& r, const Rational& s) { return (s == r); } /// inequality operator int and Rational bool operator!=(const int& r, const Rational& s) { return (s != r); } /// less than operator int and Rational bool operator<(const int& r, const Rational& s) { return (s > r); } /// less than or equal to operator int and Rational bool operator<=(const int& r, const Rational& s) { return (s >= r); } /// greater than operator int and Rational bool operator>(const int& r, const Rational& s) { return (s < r); } /// greater than or equal to operator int and Rational bool operator>=(const int& r, const Rational& s) { return (s <= r); } /// addition operator for int and Rational Rational operator+(const int& d, const Rational& r) { return (r + d); } /// subtraction operator for int and Rational Rational operator-(const int& d, const Rational& r) { Rational res(r); mpq_neg(res.dpointer->privatevalue, res.dpointer->privatevalue); res += d; return res; } /// multiplication operator for int and Rational Rational operator*(const int& d, const Rational& r) { if( d == 0 ) return Rational::ZERO; else if( d == 1 ) return r; else if( d == -1 ) return -r; else { Rational retval(d); mpq_mul(retval.dpointer->privatevalue, retval.dpointer->privatevalue, r.dpointer->privatevalue); return retval; } } /// division operator for int and Rational Rational operator/(const int& d, const Rational& r) { if( d == 0 ) return Rational::ZERO; else if( d == 1 ) { Rational retval(r); retval.invert(); return retval; } else if( d == -1 ) { Rational retval(r); retval.invert(); mpq_neg(retval.dpointer->privatevalue, retval.dpointer->privatevalue); return retval; } else { Rational retval(d); mpq_div(retval.dpointer->privatevalue, retval.dpointer->privatevalue, r.dpointer->privatevalue); return retval; } } /// Absolute. Rational spxAbs(const Rational& r) { Rational res; mpq_abs(res.dpointer->privatevalue, r.dpointer->privatevalue); return res; } /// Sign function; returns 1 if r > 0, 0 if r = 0, and -1 if r < 0. int sign(const Rational& r) { return mpq_sgn(r.dpointer->privatevalue); } /// Negation. Rational operator-(const Rational& r) { Rational res; mpq_neg(res.dpointer->privatevalue, r.dpointer->privatevalue); return res; } /// Total size of rational vector. int totalSizeRational(const Rational* vector, const int length, const int base) { assert(vector != 0); assert(length >= 0); assert(base >= 0); int size = 0; for( int i = 0; i < length; i++ ) size += vector[i].sizeInBase(base); return size; } /// Size of least common multiple of denominators in rational vector. int dlcmSizeRational(const Rational* vector, const int length, const int base) { assert(vector != 0); assert(length >= 0); assert(base >= 0); mpz_t lcm; mpz_init_set_ui(lcm, 1); for( int i = 0; i < length; i++ ) mpz_lcm(lcm, lcm, mpq_denref(vector[i].getMpqRef())); int size = (int)mpz_sizeinbase(lcm, base); mpz_clear(lcm); return size; } /// Size of largest denominator in rational vector. int dmaxSizeRational(const Rational* vector, const int length, const int base) { assert(vector != 0); assert(length >= 0); assert(base >= 0); size_t dmax = 0; for( int i = 0; i < length; i++ ) { size_t dsize = mpz_sizeinbase(mpq_denref(vector[i].getMpqRef()), base); if( dsize > dmax ) dmax = dsize; } return (int)dmax; } #else /// Defines the "Pimpl"-class Private class Rational::Private { public: /// value long double privatevalue; /// default constructor Private() { privatevalue = 0; } /// copy constructor Private(const Private& p) { *this = p; } /// constructor from long double Private(const long double& r) { privatevalue = r; } /// constructor from double Private(const double& r) { privatevalue = r; } /// constructor from int Private(const int& i) { privatevalue = i; } /// assignment operator Private& operator=(const Private& p) { this->privatevalue = p.privatevalue; return *this; } /// assignment operator from long double Private& operator=(const long double& r) { this->privatevalue = r; return *this; } /// assignment operator from double Private& operator=(const double& r) { this->privatevalue = (long double)(r); return *this; } /// assignment operator from int Private& operator=(const int& i) { this->privatevalue = (long double)(i); return *this; } }; /// default constructor Rational::Rational() { dpointer = 0; spx_alloc(dpointer); dpointer = new (dpointer) Private(); } /// copy constructor Rational::Rational(const Rational& r) { dpointer = 0; spx_alloc(dpointer); dpointer = new (dpointer) Private(*(r.dpointer)); } /// constructor from long double Rational::Rational(const long double& r) { dpointer = 0; spx_alloc(dpointer); dpointer = new (dpointer) Private(r); } /// constructor from double Rational::Rational(const double& r) { dpointer = 0; spx_alloc(dpointer); dpointer = new (dpointer) Private(r); } /// constructor from int Rational::Rational(const int& i) { dpointer = 0; spx_alloc(dpointer); dpointer = new (dpointer) Private(i); } /// destructor Rational::~Rational() { spx_free(dpointer); } /// enables list memory void Rational::enableListMem() { // because list memory is not used when SOPLEX_WITH_GMP is not defined, there is nothing to do here } /// frees the unused rational elements in the memory list /** this can be useful when you want to save memory or needed when working with a GMP memory manager like the one * in EGlib that frees GMP memory before the destructor of the static memory list is called; in most cases this * method is optional; note that this does not free the Rational elements that are currently in use */ void Rational::freeListMem() { // because list memory is not used when SOPLEX_WITH_GMP is not defined, there is nothing to do here } /// disables list memory void Rational::disableListMem() { // because list memory is not used when SOPLEX_WITH_GMP is not defined, there is nothing to do here } /// assignment operator Rational& Rational::operator=(const Rational &r) { *dpointer = *(r.dpointer); return *this; } /// assignment operator from long double Rational& Rational::operator=(const long double &r) { *dpointer = r; return *this; } /// assignment operator from double Rational& Rational::operator=(const double &r) { *dpointer = r; return *this; } /// assignment operator from int Rational& Rational::operator=(const int &i) { *dpointer = i; return *this; } /// typecasts Rational to double (allows only explicit typecast) Rational::operator double() const { return (double)this->dpointer->privatevalue; } /// typecasts Rational to long double (allows only explicit typecast) Rational::operator long double() const { return this->dpointer->privatevalue; } /// addition operator Rational Rational::operator+(const Rational& r) const { Rational retval = *this; retval.dpointer->privatevalue += r.dpointer->privatevalue; return retval; } /// addition assignment operator Rational& Rational::operator+=(const Rational& r) { this->dpointer->privatevalue += r.dpointer->privatevalue; return *this; } /// addition operator for doubles Rational Rational::operator+(const double& d) const { Rational retval = *this; retval.dpointer->privatevalue += d; return retval; } /// addition assignment operator for doubles Rational& Rational::operator+=(const double& d) { this->dpointer->privatevalue += d; return *this; } /// addition operator for ints Rational Rational::operator+(const int& d) const { Rational retval = *this; retval.dpointer->privatevalue += d; return retval; } /// addition assignment operator for ints Rational& Rational::operator+=(const int& d) { this->dpointer->privatevalue += d; return *this; } /// subtraction operator Rational Rational::operator-(const Rational& r) const { Rational retval = *this; retval.dpointer->privatevalue -= r.dpointer->privatevalue; return retval; } /// subtraction assignment operator Rational& Rational::operator-=(const Rational& r) { this->dpointer->privatevalue -= r.dpointer->privatevalue; return *this; } /// subtraction operator for doubles Rational Rational::operator-(const double& d) const { Rational retval = *this; retval.dpointer->privatevalue -= d; return retval; } /// subtraction assignment operator for doubles Rational& Rational::operator-=(const double& d) { this->dpointer->privatevalue -= d; return *this; } /// subtraction operator for ints Rational Rational::operator-(const int& d) const { Rational retval = *this; retval.dpointer->privatevalue -= d; return retval; } /// subtraction assignment operator for ints Rational& Rational::operator-=(const int& d) { this->dpointer->privatevalue -= d; return *this; } /// multiplication operator Rational Rational::operator*(const Rational& r) const { Rational retval = *this; retval.dpointer->privatevalue *= r.dpointer->privatevalue; return retval; } /// multiplication assignment operator Rational& Rational::operator*=(const Rational& r) { this->dpointer->privatevalue *= r.dpointer->privatevalue; return *this; } /// multiplication operator for doubles Rational Rational::operator*(const double& d) const { Rational retval = *this; retval.dpointer->privatevalue *= d; return retval; } /// multiplication assignment operator for doubles Rational& Rational::operator*=(const double& d) { this->dpointer->privatevalue *= d; return *this; } /// multiplication operator for ints Rational Rational::operator*(const int& d) const { Rational retval = *this; retval.dpointer->privatevalue *= d; return retval; } /// multiplication assignment operator for ints Rational& Rational::operator*=(const int& d) { this->dpointer->privatevalue *= d; return *this; } /// division operator Rational Rational::operator/(const Rational& r) const { Rational retval = *this; retval.dpointer->privatevalue /= r.dpointer->privatevalue; return retval; } /// division assignment operator Rational& Rational::operator/=(const Rational& r) { this->dpointer->privatevalue /= r.dpointer->privatevalue; return *this; } /// division operator for doubles Rational Rational::operator/(const double& d) const { Rational retval = *this; retval.dpointer->privatevalue /= d; return retval; } /// division assignment operator for doubles Rational& Rational::operator/=(const double& d) { this->dpointer->privatevalue /= d; return *this; } /// division operator for ints Rational Rational::operator/(const int& r) const { Rational retval = *this; retval.dpointer->privatevalue /= r; return retval; } /// division assignment operator for ints Rational& Rational::operator/=(const int& r) { this->dpointer->privatevalue /= r; return *this; } /// add product of two rationals Rational& Rational::addProduct(const Rational& r, const Rational& s) { this->dpointer->privatevalue += r.dpointer->privatevalue * s.dpointer->privatevalue; return *this; } /// subtract product of two rationals Rational& Rational::subProduct(const Rational& r, const Rational& s) { this->dpointer->privatevalue -= r.dpointer->privatevalue * s.dpointer->privatevalue; return *this; } /// add quotient of two rationals, r divided by s Rational& Rational::addQuotient(const Rational& r, const Rational& s) { this->dpointer->privatevalue += r.dpointer->privatevalue / s.dpointer->privatevalue; return *this; } /// subtract quotient of two rationals, r divided by s Rational& Rational::subQuotient(const Rational& r, const Rational& s) { this->dpointer->privatevalue -= r.dpointer->privatevalue / s.dpointer->privatevalue; return *this; } /// inversion Rational& Rational::invert() { this->dpointer->privatevalue = 1.0 / this->dpointer->privatevalue; return *this; } /// round up to next power of two Rational& Rational::powRound() { ///@todo implement return *this; } /// checks if d is the closest possible double bool Rational::isNextTo(const double& d) { return (this->dpointer->privatevalue == d); } /// checks if d is exactly equal to the Rational and if not, if it is one of the two adjacent doubles bool Rational::isAdjacentTo(const double& d) const { return (double(this->dpointer->privatevalue) == d); } /// Size in specified base (bit size for base 2) int Rational::sizeInBase(const int base) const { ///@todo this is only correct for base 2 return precision(); } /// returns precision of Rational implementation, i.e., number of bits used to store Rational numbers (INT_MAX if exact) int Rational::precision() { return sizeof(long double); } /// read Rational from string bool Rational::readString(const char* s) { return (sscanf(s, "%Lf", &this->dpointer->privatevalue) == 1 ); } /// convert rational number to string std::string rationalToString(const Rational& r, const int precision) { std::stringstream sstream; sstream << std::setprecision(precision <= 0 ? 16 : precision) << r; return sstream.str(); } /// read Rational from string bool readStringRational(const char* s, Rational& value) { return (sscanf(s, "%Lf", &value.dpointer->privatevalue) == 1); } /// print Rational std::ostream& operator<<(std::ostream& os, const Rational& r) { os << r.dpointer->privatevalue; return os; } /// comparison operator returning a positive value if r > s, zero if r = s, and a negative value if r < s int compareRational(const Rational& r, const Rational& s) { if( r.dpointer->privatevalue > s.dpointer->privatevalue) return 1; else if( r.dpointer->privatevalue < s.dpointer->privatevalue) return -1; else return 0; } /// equality operator bool operator==(const Rational& r, const Rational& s) { return (r.dpointer->privatevalue == s.dpointer->privatevalue); } /// inequality operator bool operator!=(const Rational& r, const Rational& s) { return (r.dpointer->privatevalue != s.dpointer->privatevalue); } /// less than operator bool operator<(const Rational& r, const Rational& s) { return (r.dpointer->privatevalue < s.dpointer->privatevalue); } /// less than or equal to operator bool operator<=(const Rational& r, const Rational& s) { return (r.dpointer->privatevalue <= s.dpointer->privatevalue); } /// greater than operator bool operator>(const Rational& r, const Rational& s) { return (r.dpointer->privatevalue > s.dpointer->privatevalue); } /// greater than or equal to operator bool operator>=(const Rational& r, const Rational& s) { return (r.dpointer->privatevalue >= s.dpointer->privatevalue); } /// equality operator for Rational and double bool operator==(const Rational& r, const double& s) { return (r.dpointer->privatevalue > s - DEFAULT_EPS_ZERO) && (r.dpointer->privatevalue < s + DEFAULT_EPS_ZERO); } /// inequality operator for Rational and double bool operator!=(const Rational& r, const double& s) { return (r.dpointer->privatevalue <= s - DEFAULT_EPS_ZERO) || (r.dpointer->privatevalue >= s + DEFAULT_EPS_ZERO); } /// less than operator for Rational and double bool operator<(const Rational& r, const double& s) { return (r.dpointer->privatevalue < s); } /// less than or equal to operator for Rational and double bool operator<=(const Rational& r, const double& s) { return (r.dpointer->privatevalue <= s); } /// greater than operator for Rational and double bool operator>(const Rational& r, const double& s) { return (r.dpointer->privatevalue > s); } /// greater than or equal to operator for Rational and double bool operator>=(const Rational& r, const double& s) { return (r.dpointer->privatevalue >= s); } /// equality operator for double and Rational bool operator==(const double& r, const Rational& s) { return (s.dpointer->privatevalue > r - DEFAULT_EPS_ZERO) && (s.dpointer->privatevalue < r + DEFAULT_EPS_ZERO); } /// inequality operator double and Rational bool operator!=(const double& r, const Rational& s) { return (s.dpointer->privatevalue <= r - DEFAULT_EPS_ZERO) || (s.dpointer->privatevalue >= r + DEFAULT_EPS_ZERO); } /// less than operator double and Rational bool operator<(const double& r, const Rational& s) { return (r < s.dpointer->privatevalue); } /// less than or equal to operator double and Rational bool operator<=(const double& r, const Rational& s) { return (r <= s.dpointer->privatevalue); } /// greater than operator double and Rational bool operator>(const double& r, const Rational& s) { return (r > s.dpointer->privatevalue); } /// greater than or equal to operator double and Rational bool operator>=(const double& r, const Rational& s) { return (r >= s.dpointer->privatevalue); } /// equality operator for Rational and long double bool operator==(const Rational& r, const long double& s) { return (r.dpointer->privatevalue > s - DEFAULT_EPS_ZERO) && (r.dpointer->privatevalue < s + DEFAULT_EPS_ZERO); } /// inequality operator for Rational and long double bool operator!=(const Rational& r, const long double& s) { return (r.dpointer->privatevalue <= s - DEFAULT_EPS_ZERO) || (r.dpointer->privatevalue >= s + DEFAULT_EPS_ZERO); } /// less than operator for Rational and long double bool operator<(const Rational& r, const long double& s) { return (r.dpointer->privatevalue < s); } /// less than or equal to operator for Rational and long double bool operator<=(const Rational& r, const long double& s) { return (r.dpointer->privatevalue <= s); } /// greater than operator for Rational and long double bool operator>(const Rational& r, const long double& s) { return (r.dpointer->privatevalue > s); } /// greater than or equal to operator for Rational and long double bool operator>=(const Rational& r, const long double& s) { return (r.dpointer->privatevalue >= s); } /// equality operator for long double and Rational bool operator==(const long double& r, const Rational& s) { return (s.dpointer->privatevalue > r - DEFAULT_EPS_ZERO) && (s.dpointer->privatevalue < r + DEFAULT_EPS_ZERO); } /// inequality operator long double and Rational bool operator!=(const long double& r, const Rational& s) { return (s.dpointer->privatevalue <= r - DEFAULT_EPS_ZERO) || (s.dpointer->privatevalue >= r + DEFAULT_EPS_ZERO); } /// less than operator long double and Rational bool operator<(const long double& r, const Rational& s) { return (r < s.dpointer->privatevalue); } /// less than or equal to operator long double and Rational bool operator<=(const long double& r, const Rational& s) { return (r <= s.dpointer->privatevalue); } /// greater than operator long double and Rational bool operator>(const long double& r, const Rational& s) { return (r > s.dpointer->privatevalue); } /// greater than or equal to operator long double and Rational bool operator>=(const long double& r, const Rational& s) { return (r >= s.dpointer->privatevalue); } /// equality operator for Rational and int bool operator==(const Rational& r, const int& s) { return r.dpointer->privatevalue == s; } /// inequality operator for Rational and int bool operator!=(const Rational& r, const int& s) { return r.dpointer->privatevalue != s; } /// less than operator for Rational and int bool operator<(const Rational& r, const int& s) { return r.dpointer->privatevalue < s; } /// less than or equal to operator for Rational and int bool operator<=(const Rational& r, const int& s) { return r.dpointer->privatevalue <= s; } /// greater than operator for Rational and int bool operator>(const Rational& r, const int& s) { return r.dpointer->privatevalue > s; } /// greater than or equal to operator for Rational and int bool operator>=(const Rational& r, const int& s) { return r.dpointer->privatevalue >= s; } /// equality operator for int and Rational bool operator==(const int& r, const Rational& s) { return r == s.dpointer->privatevalue; } /// inequality operator for int and Rational bool operator!=(const int& r, const Rational& s) { return r != s.dpointer->privatevalue; } /// less than operator for int and Rational bool operator<(const int& r, const Rational& s) { return r < s.dpointer->privatevalue; } /// less than or equal to operator for int and Rational bool operator<=(const int& r, const Rational& s) { return r <= s.dpointer->privatevalue; } /// greater than operator for int and Rational bool operator>(const int& r, const Rational& s) { return r > s.dpointer->privatevalue; } /// greater than or equal to operator for int and Rational bool operator>=(const int& r, const Rational& s) { return r >= s.dpointer->privatevalue; } /// addition operator for double and Rational Rational operator+(const double& d, const Rational& r) { Rational retval(d); retval.dpointer->privatevalue += r.dpointer->privatevalue; return retval; } /// subtraction operator for double and Rational Rational operator-(const double& d, const Rational& r) { Rational retval(d); retval.dpointer->privatevalue -= r.dpointer->privatevalue; return retval; } /// multiplication operator for double and Rational Rational operator*(const double& d, const Rational& r) { Rational retval(d); retval.dpointer->privatevalue *= r.dpointer->privatevalue; return retval; } /// division operator for double and Rational Rational operator/(const double& d, const Rational& r) { Rational retval(d); retval.dpointer->privatevalue /= r.dpointer->privatevalue; return retval; } /// addition operator for int and Rational Rational operator+(const int& d, const Rational& r) { return (r + d); } /// subtraction operator for int and Rational Rational operator-(const int& d, const Rational& r) { return -(r - d); } /// multiplication operator for int and Rational Rational operator*(const int& d, const Rational& r) { return (r * d); } /// division operator for int and Rational Rational operator/(const int& d, const Rational& r) { return 1.0 / r; } /// Absolute. Rational spxAbs(const Rational& r) { Rational res = r; if( res.dpointer->privatevalue < 0 ) res.dpointer->privatevalue *= -1; return res; } /// Sign function; returns 1 if r > 0, 0 if r = 0, and -1 if r < 0. int sign(const Rational& r) { return (r.dpointer->privatevalue > 0) - (r.dpointer->privatevalue < 0); } /// Negation. Rational operator-(const Rational& r) { Rational res = r; res.dpointer->privatevalue *= -1; return res; } /// Total size of rational vector. int totalSizeRational(const Rational* vector, const int length, const int base) { assert(vector != 0); assert(length >= 0); assert(base >= 0); int size = 0; for( int i = 0; i < length; i++ ) size += vector[i].sizeInBase(base); return size; } /// Size of least common multiple of denominators in rational vector. int dlcmSizeRational(const Rational* vector, const int length, const int base) { assert(vector != 0); assert(length >= 0); assert(base >= 0); return 0; } /// Size of largest denominator in rational vector. int dmaxSizeRational(const Rational* vector, const int length, const int base) { assert(vector != 0); assert(length >= 0); assert(base >= 0); return 0; } #endif // SOPLEX_WITH_GMP } // namespace soplex #endif
/* * Copyright © 2018 Google, Inc. * Copyright © 2019 Facebook, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod * Facebook Author(s): Behdad Esfahbod */ #ifndef HB_ITER_HH #define HB_ITER_HH #include "hb.hh" #include "hb-algs.hh" #include "hb-meta.hh" /* Unified iterator object. * * The goal of this template is to make the same iterator interface * available to all types, and make it very easy and compact to use. * hb_iter_tator objects are small, light-weight, objects that can be * copied by value. If the collection / object being iterated on * is writable, then the iterator returns lvalues, otherwise it * returns rvalues. * * TODO Document more. * * If iterator implementation implements operator!=, then can be * used in range-based for loop. That comes free if the iterator * is random-access. Otherwise, the range-based for loop incurs * one traversal to find end(), which can be avoided if written * as a while-style for loop, or if iterator implements a faster * __end__() method. * TODO When opting in for C++17, address this by changing return * type of .end()? */ /* * Base classes for iterators. */ /* Base class for all iterators. */ template <typename iter_t, typename Item = typename iter_t::__item_t__> struct hb_iter_t { typedef Item item_t; constexpr unsigned get_item_size () const { return hb_static_size (Item); } static constexpr bool is_iterator = true; static constexpr bool is_random_access_iterator = false; static constexpr bool is_sorted_iterator = false; private: /* https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern */ const iter_t* thiz () const { return static_cast<const iter_t *> (this); } iter_t* thiz () { return static_cast< iter_t *> (this); } public: /* TODO: * Port operators below to use hb_enable_if to sniff which method implements * an operator and use it, and remove hb_iter_fallback_mixin_t completely. */ /* Operators. */ iter_t iter () const { return *thiz(); } iter_t operator + () const { return *thiz(); } iter_t begin () const { return *thiz(); } iter_t end () const { return thiz()->__end__ (); } explicit operator bool () const { return thiz()->__more__ (); } unsigned len () const { return thiz()->__len__ (); } /* The following can only be enabled if item_t is reference type. Otherwise * it will be returning pointer to temporary rvalue. * TODO Use a wrapper return type to fix for non-reference type. */ template <typename T = item_t, hb_enable_if (hb_is_reference (T))> hb_remove_reference<item_t>* operator -> () const { return hb_addressof (**thiz()); } item_t operator * () const { return thiz()->__item__ (); } item_t operator * () { return thiz()->__item__ (); } item_t operator [] (unsigned i) const { return thiz()->__item_at__ (i); } item_t operator [] (unsigned i) { return thiz()->__item_at__ (i); } iter_t& operator += (unsigned count) & { thiz()->__forward__ (count); return *thiz(); } iter_t operator += (unsigned count) && { thiz()->__forward__ (count); return *thiz(); } iter_t& operator ++ () & { thiz()->__next__ (); return *thiz(); } iter_t operator ++ () && { thiz()->__next__ (); return *thiz(); } iter_t& operator -= (unsigned count) & { thiz()->__rewind__ (count); return *thiz(); } iter_t operator -= (unsigned count) && { thiz()->__rewind__ (count); return *thiz(); } iter_t& operator -- () & { thiz()->__prev__ (); return *thiz(); } iter_t operator -- () && { thiz()->__prev__ (); return *thiz(); } iter_t operator + (unsigned count) const { auto c = thiz()->iter (); c += count; return c; } friend iter_t operator + (unsigned count, const iter_t &it) { return it + count; } iter_t operator ++ (int) { iter_t c (*thiz()); ++*thiz(); return c; } iter_t operator - (unsigned count) const { auto c = thiz()->iter (); c -= count; return c; } iter_t operator -- (int) { iter_t c (*thiz()); --*thiz(); return c; } template <typename T> iter_t& operator >> (T &v) & { v = **thiz(); ++*thiz(); return *thiz(); } template <typename T> iter_t operator >> (T &v) && { v = **thiz(); ++*thiz(); return *thiz(); } template <typename T> iter_t& operator << (const T v) & { **thiz() = v; ++*thiz(); return *thiz(); } template <typename T> iter_t operator << (const T v) && { **thiz() = v; ++*thiz(); return *thiz(); } protected: hb_iter_t () = default; hb_iter_t (const hb_iter_t &o HB_UNUSED) = default; hb_iter_t (hb_iter_t &&o HB_UNUSED) = default; hb_iter_t& operator = (const hb_iter_t &o HB_UNUSED) = default; hb_iter_t& operator = (hb_iter_t &&o HB_UNUSED) = default; }; #define HB_ITER_USING(Name) \ using item_t = typename Name::item_t; \ using Name::begin; \ using Name::end; \ using Name::get_item_size; \ using Name::is_iterator; \ using Name::iter; \ using Name::operator bool; \ using Name::len; \ using Name::operator ->; \ using Name::operator *; \ using Name::operator []; \ using Name::operator +=; \ using Name::operator ++; \ using Name::operator -=; \ using Name::operator --; \ using Name::operator +; \ using Name::operator -; \ using Name::operator >>; \ using Name::operator <<; \ static_assert (true, "") /* Returns iterator / item type of a type. */ template <typename Iterable> using hb_iter_type = decltype (hb_deref (hb_declval (Iterable)).iter ()); template <typename Iterable> using hb_item_type = decltype (*hb_deref (hb_declval (Iterable)).iter ()); template <typename> struct hb_array_t; template <typename> struct hb_sorted_array_t; struct { template <typename T> hb_iter_type<T> operator () (T&& c) const { return hb_deref (hb_forward<T> (c)).iter (); } /* Specialization for C arrays. */ template <typename Type> inline hb_array_t<Type> operator () (Type *array, unsigned int length) const { return hb_array_t<Type> (array, length); } template <typename Type, unsigned int length> hb_array_t<Type> operator () (Type (&array)[length]) const { return hb_array_t<Type> (array, length); } } HB_FUNCOBJ (hb_iter); struct { template <typename T> unsigned operator () (T&& c) const { return c.len (); } } HB_FUNCOBJ (hb_len); /* Mixin to fill in what the subclass doesn't provide. */ template <typename iter_t, typename item_t = typename iter_t::__item_t__> struct hb_iter_fallback_mixin_t { private: /* https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern */ const iter_t* thiz () const { return static_cast<const iter_t *> (this); } iter_t* thiz () { return static_cast< iter_t *> (this); } public: /* Access: Implement __item__(), or __item_at__() if random-access. */ item_t __item__ () const { return (*thiz())[0]; } item_t __item_at__ (unsigned i) const { return *(*thiz() + i); } /* Termination: Implement __more__(), or __len__() if random-access. */ bool __more__ () const { return bool (thiz()->len ()); } unsigned __len__ () const { iter_t c (*thiz()); unsigned l = 0; while (c) { c++; l++; } return l; } /* Advancing: Implement __next__(), or __forward__() if random-access. */ void __next__ () { *thiz() += 1; } void __forward__ (unsigned n) { while (*thiz() && n--) ++*thiz(); } /* Rewinding: Implement __prev__() or __rewind__() if bidirectional. */ void __prev__ () { *thiz() -= 1; } void __rewind__ (unsigned n) { while (*thiz() && n--) --*thiz(); } /* Range-based for: Implement __end__() if can be done faster, * and operator!=. */ iter_t __end__ () const { if (thiz()->is_random_access_iterator) return *thiz() + thiz()->len (); /* Above expression loops twice. Following loops once. */ auto it = *thiz(); while (it) ++it; return it; } protected: hb_iter_fallback_mixin_t () = default; hb_iter_fallback_mixin_t (const hb_iter_fallback_mixin_t &o HB_UNUSED) = default; hb_iter_fallback_mixin_t (hb_iter_fallback_mixin_t &&o HB_UNUSED) = default; hb_iter_fallback_mixin_t& operator = (const hb_iter_fallback_mixin_t &o HB_UNUSED) = default; hb_iter_fallback_mixin_t& operator = (hb_iter_fallback_mixin_t &&o HB_UNUSED) = default; }; template <typename iter_t, typename item_t = typename iter_t::__item_t__> struct hb_iter_with_fallback_t : hb_iter_t<iter_t, item_t>, hb_iter_fallback_mixin_t<iter_t, item_t> { protected: hb_iter_with_fallback_t () = default; hb_iter_with_fallback_t (const hb_iter_with_fallback_t &o HB_UNUSED) = default; hb_iter_with_fallback_t (hb_iter_with_fallback_t &&o HB_UNUSED) = default; hb_iter_with_fallback_t& operator = (const hb_iter_with_fallback_t &o HB_UNUSED) = default; hb_iter_with_fallback_t& operator = (hb_iter_with_fallback_t &&o HB_UNUSED) = default; }; /* * Meta-programming predicates. */ /* hb_is_iterator() / hb_is_iterator_of() */ template<typename Iter, typename Item> struct hb_is_iterator_of { template <typename Item2 = Item> static hb_true_type impl (hb_priority<2>, hb_iter_t<Iter, hb_type_identity<Item2>> *); static hb_false_type impl (hb_priority<0>, const void *); public: static constexpr bool value = decltype (impl (hb_prioritize, hb_declval (Iter*)))::value; }; #define hb_is_iterator_of(Iter, Item) hb_is_iterator_of<Iter, Item>::value #define hb_is_iterator(Iter) hb_is_iterator_of (Iter, typename Iter::item_t) /* hb_is_iterable() */ template <typename T> struct hb_is_iterable { private: template <typename U> static auto impl (hb_priority<1>) -> decltype (hb_declval (U).iter (), hb_true_type ()); template <typename> static hb_false_type impl (hb_priority<0>); public: static constexpr bool value = decltype (impl<T> (hb_prioritize))::value; }; #define hb_is_iterable(Iterable) hb_is_iterable<Iterable>::value /* hb_is_source_of() / hb_is_sink_of() */ template<typename Iter, typename Item> struct hb_is_source_of { private: template <typename Iter2 = Iter, hb_enable_if (hb_is_convertible (typename Iter2::item_t, hb_add_lvalue_reference<hb_add_const<Item>>))> static hb_true_type impl (hb_priority<2>); template <typename Iter2 = Iter> static auto impl (hb_priority<1>) -> decltype (hb_declval (Iter2) >> hb_declval (Item &), hb_true_type ()); static hb_false_type impl (hb_priority<0>); public: static constexpr bool value = decltype (impl (hb_prioritize))::value; }; #define hb_is_source_of(Iter, Item) hb_is_source_of<Iter, Item>::value template<typename Iter, typename Item> struct hb_is_sink_of { private: template <typename Iter2 = Iter, hb_enable_if (hb_is_convertible (typename Iter2::item_t, hb_add_lvalue_reference<Item>))> static hb_true_type impl (hb_priority<2>); template <typename Iter2 = Iter> static auto impl (hb_priority<1>) -> decltype (hb_declval (Iter2) << hb_declval (Item), hb_true_type ()); static hb_false_type impl (hb_priority<0>); public: static constexpr bool value = decltype (impl (hb_prioritize))::value; }; #define hb_is_sink_of(Iter, Item) hb_is_sink_of<Iter, Item>::value /* This is commonly used, so define: */ #define hb_is_sorted_source_of(Iter, Item) \ (hb_is_source_of(Iter, Item) && Iter::is_sorted_iterator) /* Range-based 'for' for iterables. */ template <typename Iterable, hb_requires (hb_is_iterable (Iterable))> static inline auto begin (Iterable&& iterable) HB_AUTO_RETURN (hb_iter (iterable).begin ()) template <typename Iterable, hb_requires (hb_is_iterable (Iterable))> static inline auto end (Iterable&& iterable) HB_AUTO_RETURN (hb_iter (iterable).end ()) /* begin()/end() are NOT looked up non-ADL. So each namespace must declare them. * Do it for namespace OT. */ namespace OT { template <typename Iterable, hb_requires (hb_is_iterable (Iterable))> static inline auto begin (Iterable&& iterable) HB_AUTO_RETURN (hb_iter (iterable).begin ()) template <typename Iterable, hb_requires (hb_is_iterable (Iterable))> static inline auto end (Iterable&& iterable) HB_AUTO_RETURN (hb_iter (iterable).end ()) } /* * Adaptors, combiners, etc. */ template <typename Lhs, typename Rhs, hb_requires (hb_is_iterator (Lhs))> static inline auto operator | (Lhs&& lhs, Rhs&& rhs) HB_AUTO_RETURN (hb_forward<Rhs> (rhs) (hb_forward<Lhs> (lhs))) /* hb_map(), hb_filter(), hb_reduce() */ enum class hb_function_sortedness_t { NOT_SORTED, RETAINS_SORTING, SORTED, }; template <typename Iter, typename Proj, hb_function_sortedness_t Sorted, hb_requires (hb_is_iterator (Iter))> struct hb_map_iter_t : hb_iter_t<hb_map_iter_t<Iter, Proj, Sorted>, decltype (hb_get (hb_declval (Proj), *hb_declval (Iter)))> { hb_map_iter_t (const Iter& it, Proj f_) : it (it), f (f_) {} typedef decltype (hb_get (hb_declval (Proj), *hb_declval (Iter))) __item_t__; static constexpr bool is_random_access_iterator = Iter::is_random_access_iterator; static constexpr bool is_sorted_iterator = Sorted == hb_function_sortedness_t::SORTED ? true : Sorted == hb_function_sortedness_t::RETAINS_SORTING ? Iter::is_sorted_iterator : false; __item_t__ __item__ () const { return hb_get (f.get (), *it); } __item_t__ __item_at__ (unsigned i) const { return hb_get (f.get (), it[i]); } bool __more__ () const { return bool (it); } unsigned __len__ () const { return it.len (); } void __next__ () { ++it; } void __forward__ (unsigned n) { it += n; } void __prev__ () { --it; } void __rewind__ (unsigned n) { it -= n; } hb_map_iter_t __end__ () const { return hb_map_iter_t (it.end (), f); } bool operator != (const hb_map_iter_t& o) const { return it != o.it; } private: Iter it; hb_reference_wrapper<Proj> f; }; template <typename Proj, hb_function_sortedness_t Sorted> struct hb_map_iter_factory_t { hb_map_iter_factory_t (Proj f) : f (f) {} template <typename Iter, hb_requires (hb_is_iterator (Iter))> hb_map_iter_t<Iter, Proj, Sorted> operator () (Iter it) { return hb_map_iter_t<Iter, Proj, Sorted> (it, f); } private: Proj f; }; struct { template <typename Proj> hb_map_iter_factory_t<Proj, hb_function_sortedness_t::NOT_SORTED> operator () (Proj&& f) const { return hb_map_iter_factory_t<Proj, hb_function_sortedness_t::NOT_SORTED> (f); } } HB_FUNCOBJ (hb_map); struct { template <typename Proj> hb_map_iter_factory_t<Proj, hb_function_sortedness_t::RETAINS_SORTING> operator () (Proj&& f) const { return hb_map_iter_factory_t<Proj, hb_function_sortedness_t::RETAINS_SORTING> (f); } } HB_FUNCOBJ (hb_map_retains_sorting); struct { template <typename Proj> hb_map_iter_factory_t<Proj, hb_function_sortedness_t::SORTED> operator () (Proj&& f) const { return hb_map_iter_factory_t<Proj, hb_function_sortedness_t::SORTED> (f); } } HB_FUNCOBJ (hb_map_sorted); template <typename Iter, typename Pred, typename Proj, hb_requires (hb_is_iterator (Iter))> struct hb_filter_iter_t : hb_iter_with_fallback_t<hb_filter_iter_t<Iter, Pred, Proj>, typename Iter::item_t> { hb_filter_iter_t (const Iter& it_, Pred p_, Proj f_) : it (it_), p (p_), f (f_) { while (it && !hb_has (p.get (), hb_get (f.get (), *it))) ++it; } typedef typename Iter::item_t __item_t__; static constexpr bool is_sorted_iterator = Iter::is_sorted_iterator; __item_t__ __item__ () const { return *it; } bool __more__ () const { return bool (it); } void __next__ () { do ++it; while (it && !hb_has (p.get (), hb_get (f.get (), *it))); } void __prev__ () { do --it; while (it && !hb_has (p.get (), hb_get (f.get (), *it))); } hb_filter_iter_t __end__ () const { return hb_filter_iter_t (it.end (), p, f); } bool operator != (const hb_filter_iter_t& o) const { return it != o.it; } private: Iter it; hb_reference_wrapper<Pred> p; hb_reference_wrapper<Proj> f; }; template <typename Pred, typename Proj> struct hb_filter_iter_factory_t { hb_filter_iter_factory_t (Pred p, Proj f) : p (p), f (f) {} template <typename Iter, hb_requires (hb_is_iterator (Iter))> hb_filter_iter_t<Iter, Pred, Proj> operator () (Iter it) { return hb_filter_iter_t<Iter, Pred, Proj> (it, p, f); } private: Pred p; Proj f; }; struct { template <typename Pred = decltype ((hb_identity)), typename Proj = decltype ((hb_identity))> hb_filter_iter_factory_t<Pred, Proj> operator () (Pred&& p = hb_identity, Proj&& f = hb_identity) const { return hb_filter_iter_factory_t<Pred, Proj> (p, f); } } HB_FUNCOBJ (hb_filter); template <typename Redu, typename InitT> struct hb_reduce_t { hb_reduce_t (Redu r, InitT init_value) : r (r), init_value (init_value) {} template <typename Iter, hb_requires (hb_is_iterator (Iter)), typename AccuT = hb_decay<decltype (hb_declval (Redu) (hb_declval (InitT), hb_declval (typename Iter::item_t)))>> AccuT operator () (Iter it) { AccuT value = init_value; for (; it; ++it) value = r (value, *it); return value; } private: Redu r; InitT init_value; }; struct { template <typename Redu, typename InitT> hb_reduce_t<Redu, InitT> operator () (Redu&& r, InitT init_value) const { return hb_reduce_t<Redu, InitT> (r, init_value); } } HB_FUNCOBJ (hb_reduce); /* hb_zip() */ template <typename A, typename B> struct hb_zip_iter_t : hb_iter_t<hb_zip_iter_t<A, B>, hb_pair_t<typename A::item_t, typename B::item_t>> { hb_zip_iter_t () {} hb_zip_iter_t (const A& a, const B& b) : a (a), b (b) {} typedef hb_pair_t<typename A::item_t, typename B::item_t> __item_t__; static constexpr bool is_random_access_iterator = A::is_random_access_iterator && B::is_random_access_iterator; /* Note. The following categorization is only valid if A is strictly sorted, * ie. does NOT have duplicates. Previously I tried to categorize sortedness * more granularly, see commits: * * 513762849a683914fc266a17ddf38f133cccf072 * 4d3cf2adb669c345cc43832d11689271995e160a * * However, that was not enough, since hb_sorted_array_t, hb_sorted_vector_t, * SortedArrayOf, etc all needed to be updated to add more variants. At that * point I saw it not worth the effort, and instead we now deem all sorted * collections as essentially strictly-sorted for the purposes of zip. * * The above assumption is not as bad as it sounds. Our "sorted" comes with * no guarantees. It's just a contract, put in place to help you remember, * and think about, whether an iterator you receive is expected to be * sorted or not. As such, it's not perfect by definition, and should not * be treated so. The inaccuracy here just errs in the direction of being * more permissive, so your code compiles instead of erring on the side of * marking your zipped iterator unsorted in which case your code won't * compile. * * This semantical limitation does NOT affect logic in any other place I * know of as of this writing. */ static constexpr bool is_sorted_iterator = A::is_sorted_iterator; __item_t__ __item__ () const { return __item_t__ (*a, *b); } __item_t__ __item_at__ (unsigned i) const { return __item_t__ (a[i], b[i]); } bool __more__ () const { return bool (a) && bool (b); } unsigned __len__ () const { return hb_min (a.len (), b.len ()); } void __next__ () { ++a; ++b; } void __forward__ (unsigned n) { a += n; b += n; } void __prev__ () { --a; --b; } void __rewind__ (unsigned n) { a -= n; b -= n; } hb_zip_iter_t __end__ () const { return hb_zip_iter_t (a.end (), b.end ()); } /* Note, we should stop if ANY of the iters reaches end. As such two compare * unequal if both items are unequal, NOT if either is unequal. */ bool operator != (const hb_zip_iter_t& o) const { return a != o.a && b != o.b; } private: A a; B b; }; struct { HB_PARTIALIZE(2); template <typename A, typename B, hb_requires (hb_is_iterable (A) && hb_is_iterable (B))> hb_zip_iter_t<hb_iter_type<A>, hb_iter_type<B>> operator () (A&& a, B&& b) const { return hb_zip_iter_t<hb_iter_type<A>, hb_iter_type<B>> (hb_iter (a), hb_iter (b)); } } HB_FUNCOBJ (hb_zip); /* hb_apply() */ template <typename Appl> struct hb_apply_t { hb_apply_t (Appl a) : a (a) {} template <typename Iter, hb_requires (hb_is_iterator (Iter))> void operator () (Iter it) { for (; it; ++it) (void) hb_invoke (a, *it); } private: Appl a; }; struct { template <typename Appl> hb_apply_t<Appl> operator () (Appl&& a) const { return hb_apply_t<Appl> (a); } template <typename Appl> hb_apply_t<Appl&> operator () (Appl *a) const { return hb_apply_t<Appl&> (*a); } } HB_FUNCOBJ (hb_apply); /* hb_range()/hb_iota()/hb_repeat() */ template <typename T, typename S> struct hb_range_iter_t : hb_iter_t<hb_range_iter_t<T, S>, T> { hb_range_iter_t (T start, T end_, S step) : v (start), end_ (end_for (start, end_, step)), step (step) {} typedef T __item_t__; static constexpr bool is_random_access_iterator = true; static constexpr bool is_sorted_iterator = true; __item_t__ __item__ () const { return hb_ridentity (v); } __item_t__ __item_at__ (unsigned j) const { return v + j * step; } bool __more__ () const { return v != end_; } unsigned __len__ () const { return !step ? UINT_MAX : (end_ - v) / step; } void __next__ () { v += step; } void __forward__ (unsigned n) { v += n * step; } void __prev__ () { v -= step; } void __rewind__ (unsigned n) { v -= n * step; } hb_range_iter_t __end__ () const { return hb_range_iter_t (end_, end_, step); } bool operator != (const hb_range_iter_t& o) const { return v != o.v; } private: static inline T end_for (T start, T end_, S step) { if (!step) return end_; auto res = (end_ - start) % step; if (!res) return end_; end_ += step - res; return end_; } private: T v; T end_; S step; }; struct { template <typename T = unsigned> hb_range_iter_t<T, unsigned> operator () (T end = (unsigned) -1) const { return hb_range_iter_t<T, unsigned> (0, end, 1u); } template <typename T, typename S = unsigned> hb_range_iter_t<T, S> operator () (T start, T end, S step = 1u) const { return hb_range_iter_t<T, S> (start, end, step); } } HB_FUNCOBJ (hb_range); template <typename T, typename S> struct hb_iota_iter_t : hb_iter_with_fallback_t<hb_iota_iter_t<T, S>, T> { hb_iota_iter_t (T start, S step) : v (start), step (step) {} private: template <typename S2 = S> auto inc (hb_type_identity<S2> s, hb_priority<1>) -> hb_void_t<decltype (hb_invoke (hb_forward<S2> (s), hb_declval<T&> ()))> { v = hb_invoke (hb_forward<S2> (s), v); } void inc (S s, hb_priority<0>) { v += s; } public: typedef T __item_t__; static constexpr bool is_random_access_iterator = true; static constexpr bool is_sorted_iterator = true; __item_t__ __item__ () const { return hb_ridentity (v); } bool __more__ () const { return true; } unsigned __len__ () const { return UINT_MAX; } void __next__ () { inc (step, hb_prioritize); } void __prev__ () { v -= step; } hb_iota_iter_t __end__ () const { return *this; } bool operator != (const hb_iota_iter_t& o) const { return true; } private: T v; S step; }; struct { template <typename T = unsigned, typename S = unsigned> hb_iota_iter_t<T, S> operator () (T start = 0u, S step = 1u) const { return hb_iota_iter_t<T, S> (start, step); } } HB_FUNCOBJ (hb_iota); template <typename T> struct hb_repeat_iter_t : hb_iter_t<hb_repeat_iter_t<T>, T> { hb_repeat_iter_t (T value) : v (value) {} typedef T __item_t__; static constexpr bool is_random_access_iterator = true; static constexpr bool is_sorted_iterator = true; __item_t__ __item__ () const { return v; } __item_t__ __item_at__ (unsigned j) const { return v; } bool __more__ () const { return true; } unsigned __len__ () const { return UINT_MAX; } void __next__ () {} void __forward__ (unsigned) {} void __prev__ () {} void __rewind__ (unsigned) {} hb_repeat_iter_t __end__ () const { return *this; } bool operator != (const hb_repeat_iter_t& o) const { return true; } private: T v; }; struct { template <typename T> hb_repeat_iter_t<T> operator () (T value) const { return hb_repeat_iter_t<T> (value); } } HB_FUNCOBJ (hb_repeat); /* hb_enumerate()/hb_take() */ struct { template <typename Iterable, typename Index = unsigned, hb_requires (hb_is_iterable (Iterable))> auto operator () (Iterable&& it, Index start = 0u) const HB_AUTO_RETURN ( hb_zip (hb_iota (start), it) ) } HB_FUNCOBJ (hb_enumerate); struct { HB_PARTIALIZE(2); template <typename Iterable, hb_requires (hb_is_iterable (Iterable))> auto operator () (Iterable&& it, unsigned count) const HB_AUTO_RETURN ( hb_zip (hb_range (count), it) | hb_map (hb_second) ) /* Specialization arrays. */ template <typename Type> inline hb_array_t<Type> operator () (hb_array_t<Type> array, unsigned count) const { return array.sub_array (0, count); } template <typename Type> inline hb_sorted_array_t<Type> operator () (hb_sorted_array_t<Type> array, unsigned count) const { return array.sub_array (0, count); } } HB_FUNCOBJ (hb_take); struct { HB_PARTIALIZE(2); template <typename Iter, hb_requires (hb_is_iterator (Iter))> auto operator () (Iter it, unsigned count) const HB_AUTO_RETURN ( + hb_iota (it, hb_add (count)) | hb_map (hb_take (count)) | hb_take ((hb_len (it) + count - 1) / count) ) } HB_FUNCOBJ (hb_chop); /* hb_sink() */ template <typename Sink> struct hb_sink_t { hb_sink_t (Sink s) : s (s) {} template <typename Iter, hb_requires (hb_is_iterator (Iter))> void operator () (Iter it) { for (; it; ++it) s << *it; } private: Sink s; }; struct { template <typename Sink> hb_sink_t<Sink> operator () (Sink&& s) const { return hb_sink_t<Sink> (s); } template <typename Sink> hb_sink_t<Sink&> operator () (Sink *s) const { return hb_sink_t<Sink&> (*s); } } HB_FUNCOBJ (hb_sink); /* hb-drain: hb_sink to void / blackhole / /dev/null. */ struct { template <typename Iter, hb_requires (hb_is_iterator (Iter))> void operator () (Iter it) const { for (; it; ++it) (void) *it; } } HB_FUNCOBJ (hb_drain); /* hb_unzip(): unzip and sink to two sinks. */ template <typename Sink1, typename Sink2> struct hb_unzip_t { hb_unzip_t (Sink1 s1, Sink2 s2) : s1 (s1), s2 (s2) {} template <typename Iter, hb_requires (hb_is_iterator (Iter))> void operator () (Iter it) { for (; it; ++it) { const auto &v = *it; s1 << v.first; s2 << v.second; } } private: Sink1 s1; Sink2 s2; }; struct { template <typename Sink1, typename Sink2> hb_unzip_t<Sink1, Sink2> operator () (Sink1&& s1, Sink2&& s2) const { return hb_unzip_t<Sink1, Sink2> (s1, s2); } template <typename Sink1, typename Sink2> hb_unzip_t<Sink1&, Sink2&> operator () (Sink1 *s1, Sink2 *s2) const { return hb_unzip_t<Sink1&, Sink2&> (*s1, *s2); } } HB_FUNCOBJ (hb_unzip); /* hb-all, hb-any, hb-none. */ struct { template <typename Iterable, typename Pred = decltype ((hb_identity)), typename Proj = decltype ((hb_identity)), hb_requires (hb_is_iterable (Iterable))> bool operator () (Iterable&& c, Pred&& p = hb_identity, Proj&& f = hb_identity) const { for (auto it = hb_iter (c); it; ++it) if (!hb_match (hb_forward<Pred> (p), hb_get (hb_forward<Proj> (f), *it))) return false; return true; } } HB_FUNCOBJ (hb_all); struct { template <typename Iterable, typename Pred = decltype ((hb_identity)), typename Proj = decltype ((hb_identity)), hb_requires (hb_is_iterable (Iterable))> bool operator () (Iterable&& c, Pred&& p = hb_identity, Proj&& f = hb_identity) const { for (auto it = hb_iter (c); it; ++it) if (hb_match (hb_forward<Pred> (p), hb_get (hb_forward<Proj> (f), *it))) return true; return false; } } HB_FUNCOBJ (hb_any); struct { template <typename Iterable, typename Pred = decltype ((hb_identity)), typename Proj = decltype ((hb_identity)), hb_requires (hb_is_iterable (Iterable))> bool operator () (Iterable&& c, Pred&& p = hb_identity, Proj&& f = hb_identity) const { for (auto it = hb_iter (c); it; ++it) if (hb_match (hb_forward<Pred> (p), hb_get (hb_forward<Proj> (f), *it))) return false; return true; } } HB_FUNCOBJ (hb_none); /* * Algorithms operating on iterators. */ template <typename C, typename V, hb_requires (hb_is_iterable (C))> inline void hb_fill (C&& c, const V &v) { for (auto i = hb_iter (c); i; i++) *i = v; } template <typename S, typename D> inline void hb_copy (S&& is, D&& id) { hb_iter (is) | hb_sink (id); } #endif /* HB_ITER_HH */
/**************************************************************************//** * @file Conv_CPU.cpp * @brief Module for performing Autocorrelation on the CPU using convolution. * The module takes input data, width and height and returns the output matrix * with the time taken. * @author Ian Glass * @date 14/10/2013 ******************************************************************************* * * 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. * *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cufft.h> #include <cuda_runtime.h> /* CUDA utilities and system includes */ #include <helper_functions.h> /* Global Variables ----------------------------------------------------------*/ typedef unsigned int uint; typedef unsigned char uchar; /*-----------------------------------------------------------*/ /** * @brief Addition of complex values. * @param Two complex variables to be added. * @retval None */ static __device__ __host__ inline cuDoubleComplex ComplexAdd(cuDoubleComplex a, cuDoubleComplex b) { cuDoubleComplex c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } /*-----------------------------------------------------------*/ /** * @brief Multiplication of complex values. * @param Two complex variables to be added. * @retval None */ static __device__ __host__ inline cuDoubleComplex ComplexMul(cuDoubleComplex a, cuDoubleComplex b) { cuDoubleComplex c; c.x = a.x * b.x - a.y * b.y; c.y = a.x * b.y + a.y * b.x; return c; } /*-----------------------------------------------------------*/ /** * @brief Computes convolution on the CPU. * @param * @retval None */ void Convolve(const cuDoubleComplex *signal, const cuDoubleComplex *filter_kernel, int size, cuDoubleComplex *filtered_signal) { int minRadius = size / 2; int maxRadius = size - minRadius; /* Loop over output element indices */ for (int i = 0; i < size; ++i) { filtered_signal[i].x = filtered_signal[i].y = 0; /* Loop over convolution indices */ for (int j = - maxRadius + 1; j <= minRadius; ++j) { int k = i + j; if (k >= 0 && k < size) { filtered_signal[i] = ComplexAdd(filtered_signal[i], ComplexMul(signal[k], filter_kernel[minRadius - j])); } } } } /*-----------------------------------------------------------*/ /** * @brief Main function for this file. * @param The data to be convoluted, the data width and height * and a pointer to the processing time. * @retval The convoluted data. */ extern "C" cuDoubleComplex *Conv_CPU_fn(int argc, char **argv, cuDoubleComplex *data, int width, int height, float *time) { StopWatchInterface *timer = 0; sdkCreateTimer(&timer); sdkStartTimer(&timer); int width_out = width*2-1; int height_out = height*2-1; int size_padded = width_out*height_out; unsigned int mem_size = sizeof(cuDoubleComplex)*size_padded; /* create zero padded matrix before filling with input data */ cuDoubleComplex *data_padded = (cuDoubleComplex *) malloc(mem_size); for (int z = 0; z < size_padded; z++) { data_padded[z].x = 0; data_padded[z].y = 0; } /* Fill matrix with input data and shift to center */ for (int i = 0; i < height; i++) { for (int j = 0; j < width; j ++) { data_padded[(j+((width-1)/2))+(i+((height-1)/2))*width_out].x = data[j+i*width].x; data_padded[(j+((width-1)/2))+(i+((height-1)/2))*width_out].y = data[j+i*width].y; } } /* Allocate host memory for the convolution result */ cuDoubleComplex *conv_out = (cuDoubleComplex *)malloc(mem_size); /* Convolve on the host */ Convolve(data_padded, data_padded, size_padded, conv_out); sdkStopTimer(&timer); *time = sdkGetTimerValue(&timer); sdkDeleteTimer(&timer); /* Free allocated memory */ free(data_padded); return(conv_out); }
// Copyright (C) 2007 Id Software, Inc. // #include "../../precompiled.h" #pragma hdrstop #include "../../Game_local.h" // for cvars and debug drawing #include "../../Player.h" #include "../../Misc.h" #include "../../ContentMask.h" #include "../../botai/BotThreadData.h" #include "AAS_local.h" #include "AASCallback_FindCoverArea.h" #include "AASCallback_FindFlaggedArea.h" #include "ObstacleAvoidance.h" /* ============ idAASLocal::DrawCone ============ */ void idAASLocal::DrawCone( const idVec3 &origin, const idVec3 &dir, float radius, const idVec4 &color ) const { int i; idMat3 axis; idVec3 center, top, p, lastp; axis[2] = dir; axis[2].NormalVectors( axis[0], axis[1] ); axis[1] = -axis[1]; center = origin + dir; top = center + dir * (3.0f * radius); lastp = center + radius * axis[1]; for ( i = 20; i <= 360; i += 20 ) { p = center + sin( DEG2RAD(i) ) * radius * axis[0] + cos( DEG2RAD(i) ) * radius * axis[1]; gameRenderWorld->DebugLine( color, lastp, p, 0 ); gameRenderWorld->DebugLine( color, p, top, 0 ); lastp = p; } } /* ============ idAASLocal::DrawReachability ============ */ void idAASLocal::DrawReachability( const aasReachability_t *reach, const char *name ) const { gameRenderWorld->DebugArrow( colorCyan, reach->GetStart(), reach->GetEnd(), 2, 0 ); if ( name != NULL && name[0] != '\0' && gameLocal.GetLocalPlayer() != NULL ) { idStr flags; if ( reach->travelFlags & TFL_INVALID ) flags.Append( " invalid" ); if ( reach->travelFlags & TFL_INVALID_GDF ) flags.Append( " invalidgdf" ); if ( reach->travelFlags & TFL_INVALID_STROGG ) flags.Append( " invalidstrogg" ); if ( reach->travelFlags & TFL_AIR ) flags.Append( " air" ); if ( reach->travelFlags & TFL_WATER ) flags.Append( " water" ); if ( reach->travelFlags & TFL_WALK ) flags.Append( " walk" ); if ( reach->travelFlags & TFL_WALKOFFLEDGE ) flags.Append( " walkoffledge" ); if ( reach->travelFlags & TFL_WALKOFFBARRIER ) flags.Append( " walloffbarrier" ); if ( reach->travelFlags & TFL_BARRIERJUMP ) flags.Append( " barrierjump" ); if ( reach->travelFlags & TFL_JUMP ) flags.Append( " jump" ); if ( reach->travelFlags & TFL_LADDER ) flags.Append( " ladder" ); if ( reach->travelFlags & TFL_SWIM ) flags.Append( " swim" ); if ( reach->travelFlags & TFL_WATERJUMP ) flags.Append( " waterjump" ); if ( reach->travelFlags & TFL_TELEPORT ) flags.Append( " teleport" ); if ( reach->travelFlags & TFL_ELEVATOR ) flags.Append( " elevator" ); gameRenderWorld->DrawText( va( "%s\nTravel Flags:%s", name, flags.c_str() ), ( reach->GetStart() + reach->GetEnd() ) * 0.5f, 0.1f, colorWhite, gameLocal.GetLocalPlayer()->GetViewAxis(), 1, 0 ); } } /* ============ idAASLocal::DrawEdge ============ */ void idAASLocal::DrawEdge( int edgeNum, bool arrow ) const { const aasEdge_t *edge; if ( !file ) { return; } edge = &file->GetEdge( edgeNum ); if ( arrow ) { gameRenderWorld->DebugArrow( colorRed, file->GetVertex( edge->vertexNum[0] ), file->GetVertex( edge->vertexNum[1] ), 1, 0 ); } else { gameRenderWorld->DebugLine( colorRed, file->GetVertex( edge->vertexNum[0] ), file->GetVertex( edge->vertexNum[1] ), 0 ); } if ( aas_showEdgeNums.GetBool() && gameLocal.GetLocalPlayer() ) { gameRenderWorld->DrawText( va( "%d", edgeNum ), ( file->GetVertex( edge->vertexNum[0] ) + file->GetVertex( edge->vertexNum[1] ) ) * 0.5f + idVec3(0,0,4), 0.1f, colorRed, gameLocal.GetLocalPlayer()->GetViewAxis(), 1, 0 ); } } /* ============ idAASLocal::DrawArea ============ */ void idAASLocal::DrawArea( int areaNum ) const { int i, j, numEdges, firstEdge; idVec3 mid, end; const aasArea_t *area; const aasReachability_t *reach; if ( !file ) { return; } area = &file->GetArea( areaNum ); numEdges = area->numEdges; firstEdge = area->firstEdge; mid.Zero(); for ( i = 0; i < numEdges; i++ ) { DrawEdge( abs( file->GetEdgeIndex( firstEdge + i ) ), true ); j = file->GetEdgeIndex( firstEdge + i ); mid += file->GetVertex( file->GetEdge( abs( j ) ).vertexNum[ j < 0 ] ); } mid /= numEdges; end = mid + 5.0f * file->GetSettings().invGravityDir; gameRenderWorld->DebugArrow( colorGreen, mid, end, 1, 0 ); for ( reach = area->reach; reach; reach = reach->next ) { DrawReachability( reach, NULL ); } gameRenderWorld->DrawText( va( "%d", areaNum ), AreaCenter( areaNum ) + idVec3( 0.0f, 0.0f, 4.0f ), 0.1f, colorWhite, gameLocal.GetLocalPlayer()->GetViewAxis(), 1, 0 ); } /* ============ idAASLocal::DefaultSearchBounds ============ */ const idBounds &idAASLocal::DefaultSearchBounds( void ) const { return file->GetSettings().boundingBox; } /* ============ idAASLocal::TravelFlagForTeam ============ */ int idAASLocal::TravelFlagForTeam( void ) const { idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL || player->GetGameTeam() == NULL ) { return TFL_VALID_GDF_AND_STROGG; } switch( player->GetGameTeam()->GetBotTeam() ) { case GDF: return TFL_VALID_GDF; case STROGG: return TFL_VALID_STROGG; } return TFL_VALID_GDF_AND_STROGG; } /* ============ idAASLocal::TravelFlagWalkForTeam ============ */ int idAASLocal::TravelFlagWalkForTeam( void ) const { idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL || player->GetGameTeam() == NULL ) { return TFL_VALID_WALK_GDF_AND_STROGG; } switch( player->GetGameTeam()->GetBotTeam() ) { case GDF: return TFL_VALID_WALK_GDF; case STROGG: return TFL_VALID_WALK_STROGG; } return TFL_VALID_WALK_GDF_AND_STROGG; } /* ============ idAASLocal::TravelFlagInvalidForTeam ============ */ int idAASLocal::TravelFlagInvalidForTeam( void ) const { idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL || player->GetGameTeam() == NULL ) { return TFL_INVALID|TFL_INVALID_GDF|TFL_INVALID_STROGG; } switch( player->GetGameTeam()->GetBotTeam() ) { case GDF: return TFL_INVALID|TFL_INVALID_GDF; case STROGG: return TFL_INVALID|TFL_INVALID_STROGG; } return TFL_INVALID|TFL_INVALID_GDF|TFL_INVALID_STROGG; } /* ============ idAASLocal::ShowArea ============ */ void idAASLocal::ShowArea( const idVec3 &origin, int mode ) const { static int lastAreaNum; int areaNum; const aasArea_t *area; idVec3 org; org = origin; if ( mode == 1 ) { areaNum = PointReachableAreaNum( origin, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); PushPointIntoArea( areaNum, org ); } else { areaNum = PointAreaNum( origin ); } if ( aas_showTravelTime.GetInteger() ) { int travelTime; const aasReachability_t *reach; RouteToGoalArea( areaNum, org, aas_showTravelTime.GetInteger(), TFL_WALK|TFL_AIR, travelTime, &reach ); gameLocal.Printf( "\rtt = %4d", travelTime ); if ( reach ) { gameLocal.Printf( " to area %4d", reach->toAreaNum ); DrawArea( reach->toAreaNum ); } } if ( areaNum != lastAreaNum ) { area = &file->GetArea( areaNum ); gameLocal.Printf( "area %d:", areaNum ); if ( area->flags & AAS_AREA_LEDGE ) { gameLocal.Printf( " ledge" ); } if ( area->flags & AAS_AREA_CONTENTS_CLUSTERPORTAL ) { gameLocal.Printf( " clusterportal" ); } if ( area->flags & AAS_AREA_CONTENTS_OBSTACLE ) { gameLocal.Printf( " obstacle" ); } if ( area->flags & AAS_AREA_OUTSIDE ) { gameLocal.Printf( " outside" ); } if ( area->flags & AAS_AREA_HIGH_CEILING ) { gameLocal.Printf( " highceiling" ); } if ( area->travelFlags & ( TFL_INVALID | TFL_INVALID_GDF | TFL_INVALID_STROGG ) ) { gameLocal.Printf( " /" ); if ( area->travelFlags & TFL_INVALID ) { gameLocal.Printf( " invalid" ); } if ( area->travelFlags & TFL_INVALID_GDF ) { gameLocal.Printf( " invalidgdf" ); } if ( area->travelFlags & TFL_INVALID_STROGG ) { gameLocal.Printf( " invalidstrogg" ); } } gameLocal.Printf( "\n" ); lastAreaNum = areaNum; } if ( org != origin ) { idBounds bnds = file->GetSettings().boundingBox; bnds[ 1 ].z = bnds[ 0 ].z; gameRenderWorld->DebugBounds( colorYellow, bnds, org ); gameRenderWorld->DebugArrow( colorYellow, origin, org, 1 ); } DrawArea( areaNum ); } /* ============ idAASLocal::ShowWalkPath ============ */ void idAASLocal::ShowWalkPath( int startAreaNum, const idVec3 &startOrigin, int goalAreaNum, const idVec3 &goalOrigin, int travelFlags, int walkTravelFlags ) const { if ( file == NULL ) { return; } int curAreaNum = startAreaNum; idVec3 org = startOrigin; for ( int i = 0; i < 100; i++ ) { int travelTime; const aasReachability_t *reach; if ( !RouteToGoalArea( curAreaNum, org, goalAreaNum, travelFlags, travelTime, &reach ) ) { break; } if ( !reach ) { break; } gameRenderWorld->DebugArrow( colorGreen, org, reach->GetStart(), 2, 0 ); DrawReachability( reach, NULL ); if ( aas_showAreas.GetBool() ) { DrawArea( curAreaNum ); } if ( reach->toAreaNum == goalAreaNum ) { break; } curAreaNum = reach->toAreaNum; org = reach->GetEnd(); } idAASPath path; if ( !WalkPathToGoal( path, startAreaNum, startOrigin, goalAreaNum, goalOrigin, travelFlags, walkTravelFlags ) ) { return; } gameRenderWorld->DebugArrow( colorBlue, startOrigin, path.moveGoal, 2, 0 ); // idObstacleAvoidance::obstaclePath_t obstaclePath; // idObstacleAvoidance obstacleAvoidance; // botThreadData.BuildObstacleList( obstacleAvoidance, startOrigin, startAreaNum, false ); // obstacleAvoidance.FindPathAroundObstacles( file->GetSettings().boundingBox, file->GetSettings().obstaclePVSRadius, this, startOrigin, path.moveGoal, obstaclePath ); // if ( obstaclePath.firstObstacle != idObstacleAvoidance::OBSTACLE_ID_INVALID ) { // path.moveGoal = obstaclePath.seekPos; // gameRenderWorld->DebugArrow( colorOrange, startOrigin, path.moveGoal, 2, 0 ); // } } /* ============ idAASLocal::ShowWalkPath ============ */ void idAASLocal::ShowWalkPath( const idVec3 &startOrigin, int goalAreaNum, const idVec3 &goalOrigin ) const { if ( file == NULL ) { return; } idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL ) { return; } idVec3 areaOrigin = startOrigin; int startAreaNum = PointReachableAreaNum( areaOrigin, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); PushPointIntoArea( startAreaNum, areaOrigin ); ShowWalkPath( startAreaNum, areaOrigin, goalAreaNum, goalOrigin, TravelFlagForTeam(), TravelFlagWalkForTeam() ); } /* ============ idAASLocal::ShowHopPath ============ */ void idAASLocal::ShowHopPath( int startAreaNum, const idVec3 &startOrigin, int goalAreaNum, const idVec3 &goalOrigin, int travelFlags, int walkTravelFlags, const idAASHopPathParms &parms ) const { if ( file == NULL ) { return; } int curAreaNum = startAreaNum; idVec3 org = startOrigin; for ( int i = 0; i < 100; i++ ) { int travelTime; const aasReachability_t *reach; if ( !RouteToGoalArea( curAreaNum, org, goalAreaNum, travelFlags, travelTime, &reach ) ) { break; } if ( !reach ) { break; } gameRenderWorld->DebugArrow( colorGreen, org, reach->GetStart(), 2, 0 ); DrawReachability( reach, NULL ); if ( aas_showAreas.GetBool() ) { DrawArea( curAreaNum ); } if ( reach->toAreaNum == goalAreaNum ) { break; } curAreaNum = reach->toAreaNum; org = reach->GetEnd(); } idAASPath path; if ( WalkPathToGoal( path, startAreaNum, startOrigin, goalAreaNum, goalOrigin, travelFlags, walkTravelFlags ) ) { gameRenderWorld->DebugArrow( colorBlue, startOrigin, path.moveGoal, 2 ); if ( ExtendHopPathToGoal( path, startAreaNum, startOrigin, goalAreaNum, goalOrigin, travelFlags, walkTravelFlags, parms ) ) { gameRenderWorld->DebugArrow( colorCyan, startOrigin, path.moveGoal, 2 ); } } } /* ============ idAASLocal::ShowHopPath ============ */ void idAASLocal::ShowHopPath( const idVec3 &startOrigin, int goalAreaNum, const idVec3 &goalOrigin ) const { if ( file == NULL ) { return; } idVec3 areaOrigin = startOrigin; int startAreaNum = PointReachableAreaNum( areaOrigin, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); PushPointIntoArea( startAreaNum, areaOrigin ); ShowHopPath( startAreaNum, areaOrigin, goalAreaNum, goalOrigin, TravelFlagForTeam(), TravelFlagWalkForTeam(), idAASHopPathParms() ); } /* ============ ProjectTopDown ============ */ void ProjectTopDown( idVec3 &point, const idVec3 &viewOrigin, const idMat3 &viewAxis, const idMat3 &playerAxis, float distance ) { point = ( point - viewOrigin ) * playerAxis; point = viewOrigin + distance * viewAxis[0] + point.y * viewAxis[1] + point.x * viewAxis[2]; } /* ============ idAASLocal::ShowWallEdges ============ */ void idAASLocal::ShowWallEdges( const idVec3 &origin, int mode, bool showNumbers ) const { const int MAX_WALL_EDGES = 1024; int edges[MAX_WALL_EDGES]; float textSize; idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL ) { return; } idMat3 viewAxis = player->GetViewAxis(); idVec3 viewOrigin = player->GetViewPos(); idMat3 playerAxis = idAngles( 0.0f, -player->GetViewAngles().yaw, 0.0f ).ToMat3(); if ( mode == 3 ) { textSize = 0.2f; } else { textSize = 0.1f; } float radius = file->GetSettings().obstaclePVSRadius; int areaNum = PointReachableAreaNum( origin, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); //int numEdges = GetWallEdges( areaNum, idBounds( origin ).Expand( radius ), TFL_WALK, 64.0f, edges, MAX_WALL_EDGES ); int numEdges = GetObstaclePVSWallEdges( areaNum, edges, MAX_WALL_EDGES ); // move the wall edges to the start of the list int numWallEdges = 0; for ( int i = 0; i < numEdges; i++ ) { if ( ( file->GetEdge( abs( edges[i] ) ).flags & AAS_EDGE_WALL ) != 0 ) { idSwap( edges[numWallEdges++], edges[i] ); } } for ( int i = 0; i < numEdges; i++ ) { idVec3 start, end; GetEdge( edges[i], start, end ); if ( mode == 2 ) { start.z = end.z = origin.z; } else if ( mode == 3 ) { ProjectTopDown( start, viewOrigin, viewAxis, playerAxis, radius * 2.0f ); ProjectTopDown( end, viewOrigin, viewAxis, playerAxis, radius * 2.0f ); } if ( ( file->GetEdge( abs( edges[i] ) ).flags & AAS_EDGE_WALL ) != 0 ) { gameRenderWorld->DebugLine( colorRed, start, end, 0 ); } else { gameRenderWorld->DebugLine( colorGreen, start, end, 0 ); } if ( showNumbers ) { gameRenderWorld->DrawText( va( "%d", edges[i] ), ( start + end ) * 0.5f, textSize, colorWhite, viewAxis, 1, 0 ); } } if ( mode == 3 ) { idVec3 box[7] = { origin, origin, origin, origin, origin, origin, origin }; box[0][0] += radius; box[0][1] += radius; box[1][0] += radius; box[1][1] -= radius; box[2][0] -= radius; box[2][1] -= radius; box[3][0] -= radius; box[3][1] += radius; box[4][1] += radius; box[5][0] += radius * 0.1f; box[5][1] += radius - radius * 0.1f; box[6][0] -= radius * 0.1f; box[6][1] += radius - radius * 0.1f; for ( int i = 0; i < 7; i++ ) { ProjectTopDown( box[i], viewOrigin, viewAxis, playerAxis, radius * 2.0f ); } for ( int i = 0; i < 4; i++ ) { gameRenderWorld->DebugLine( colorCyan, box[i], box[(i+1)&3], 0 ); } gameRenderWorld->DebugLine( colorCyan, box[4], box[5], 0 ); gameRenderWorld->DebugLine( colorCyan, box[4], box[6], 0 ); } } /* ============ idAASLocal::ShowNearestCoverArea ============ */ void idAASLocal::ShowNearestCoverArea( const idVec3 &origin, int targetAreaNum ) const { int areaNum = PointReachableAreaNum( origin, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); idVec3 target = AreaCenter( targetAreaNum ); DrawCone( target, idVec3(0,0,1), 16.0f, colorYellow ); idAASCallback_FindCoverArea findCover( target ); idAASGoal goal; if ( FindNearestGoal( goal, areaNum, origin, TravelFlagInvalidForTeam(), findCover ) ) { DrawArea( goal.areaNum ); ShowWalkPath( areaNum, origin, goal.areaNum, goal.origin, TravelFlagForTeam(), TravelFlagWalkForTeam() ); DrawCone( goal.origin, idVec3( 0, 0, 1 ), 16.0f, colorWhite ); } } /* ============ idAASLocal::ShowNearestInsideArea ============ */ void idAASLocal::ShowNearestInsideArea( const idVec3 &origin ) const { int areaNum = PointReachableAreaNum( origin, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); idAASCallback_FindFlaggedArea findInside( AAS_AREA_OUTSIDE, false ); idAASGoal goal; if ( FindNearestGoal( goal, areaNum, origin, TravelFlagForTeam(), findInside ) ) { DrawArea( goal.areaNum ); ShowWalkPath( areaNum, origin, goal.areaNum, goal.origin, TravelFlagForTeam(), TravelFlagWalkForTeam() ); DrawCone( goal.origin, idVec3( 0, 0, 1 ), 16.0f, colorWhite ); } } struct idPullPlayerState { idPullPlayerState() { jumpNow = false; ladderDir = vec3_zero; ladderTime = 0; } bool jumpNow; idVec3 ladderDir; int ladderTime; } pullPlayerState; /* ============ idAASLocal::PullPlayer ============ */ bool idAASLocal::PullPlayer( const idVec3 &origin, int goalAreaNum, const idVec3 &goalOrigin, int &startAreaNum, int &travelTime ) const { startAreaNum = 0; travelTime = 0; idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL ) { return true; } if ( goalAreaNum == 0 ) { return false; } if ( player->GetNoClip() ) { player->aasPullPlayer = false; return false; } idVec3 dir = goalOrigin - origin; float height = idMath::Fabs( dir.z ); float dist = dir.ToVec2().Length(); if ( dist < 32.0f && height < 128.0f ) { return false; } idVec3 org = origin; startAreaNum = PointReachableAreaNum( org, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); PushPointIntoArea( startAreaNum, org ); const aasReachability_t *reach; RouteToGoalArea( startAreaNum, org, goalAreaNum, TravelFlagForTeam(), travelTime, &reach ); ShowWalkPath( startAreaNum, org, goalAreaNum, goalOrigin, TravelFlagForTeam(), TravelFlagWalkForTeam() ); idAASPath path; if ( !WalkPathToGoal( path, startAreaNum, org, goalAreaNum, goalOrigin, TravelFlagForTeam(), TravelFlagWalkForTeam() ) ) { return false; } idObstacleAvoidance::obstaclePath_t obstaclePath; idObstacleAvoidance obstacleAvoidance; botThreadData.BuildObstacleList( obstacleAvoidance, org, startAreaNum, false ); obstacleAvoidance.FindPathAroundObstacles( file->GetSettings().boundingBox, file->GetSettings().obstaclePVSRadius, this, org, path.moveGoal, obstaclePath ); path.moveGoal = obstaclePath.seekPos; player->aasPullPlayer = true; usercmd_t usercmd; memset( &usercmd, 0, sizeof( usercmd ) ); usercmd.forwardmove = 127; usercmd.buttons.btn.run = true; usercmd.buttons.btn.sprint = false; idVec3 moveDir = path.moveGoal - org; idVec3 horizontalDir( moveDir.x, moveDir.y, 0.0f ); float horizontalDist = horizontalDir.Normalize(); moveDir.Normalize(); switch( path.type ) { case PATHTYPE_WALKOFFLEDGE: case PATHTYPE_WALKOFFBARRIER: { if ( horizontalDist < 80.0f ) { usercmd.buttons.btn.run = false; usercmd.forwardmove = 16 + horizontalDist; } break; } case PATHTYPE_BARRIERJUMP: case PATHTYPE_JUMP: { if ( horizontalDist < 24.0f ) { pullPlayerState.jumpNow = !pullPlayerState.jumpNow; if ( pullPlayerState.jumpNow ) { usercmd.upmove = 127; } } if ( player->GetPlayerPhysics().IsGrounded() ) { if ( horizontalDist < 100.0f ) { usercmd.buttons.btn.run = false; usercmd.forwardmove = 8 + horizontalDist; } } else { moveDir = path.reachability->GetEnd() - org; moveDir.Normalize(); } break; } case PATHTYPE_LADDER: { pullPlayerState.ladderDir = moveDir; pullPlayerState.ladderTime = gameLocal.time; #if 0 // test ladder physics code if ( !player->GetPlayerPhysics().IsGrounded() ) { trace_t trace; bool onLadder = false; if ( gameLocal.clip.Translation( CLIP_DEBUG_PARMS_CLIENTINFO( self ) trace, org, org + horizontalDir * 32.0f, NULL, mat3_identity, MASK_PLAYERSOLID, player ) ) { onLadder = ( gameLocal.entities[ trace.c.entityNum ]->Cast< sdLadderEntity >() != NULL ); } if ( onLadder && !player->GetPlayerPhysics().OnLadder() ) { usercmd.forwardmove = 0; } } #endif break; } } if ( player->GetPlayerPhysics().OnLadder() || pullPlayerState.ladderTime > gameLocal.time - 500 ) { moveDir = pullPlayerState.ladderDir; } idAngles viewAngles = moveDir.ToAngles(); player->Move( usercmd, viewAngles ); return true; } /* ============ idAASLocal::UnFreezePlayer ============ */ void idAASLocal::UnFreezePlayer() const { idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL ) { return; } player->aasPullPlayer = false; } /* ============ idAASLocal::RandomPullPlayer ============ */ void idAASLocal::RandomPullPlayer( const idVec3 &origin, int mode ) const { int areaNum, travelTime; static int bestTravelTime = 0; static int startAreaNum = 0; static int goalAreaNum = 0; static int failedCount; if ( goalAreaNum > file->GetNumAreas() ) { goalAreaNum = 0; } if ( !PullPlayer( origin, goalAreaNum, AreaCenter( goalAreaNum ), areaNum, travelTime ) ) { startAreaNum = 0; bestTravelTime = INT_MAX; int rnd = idMath::Ftoi( gameLocal.random.RandomFloat() * file->GetNumAreas() ); for ( int i = 0; i < file->GetNumAreas(); i++ ) { int n = ( rnd + i ) % file->GetNumAreas(); if ( ( file->GetArea( n ).flags & AAS_AREA_REACHABLE_WALK ) != 0 ) { goalAreaNum = n; } } } else if ( startAreaNum == 0 ) { startAreaNum = areaNum; bestTravelTime = travelTime; } if ( travelTime < bestTravelTime ) { bestTravelTime = travelTime; failedCount = 0; } else { failedCount++; } if ( failedCount > 10 * 1000 / USERCMD_MSEC ) { failedCount = 0; if ( mode > 1 ) { common->Warning( "failed to go from area %d to area %d at area %d", startAreaNum, goalAreaNum, areaNum ); goalAreaNum = 0; } } } /* ============ idAASLocal::ShowPushIntoArea ============ */ void idAASLocal::ShowPushIntoArea( const idVec3 &origin ) const { int areaNum; idVec3 target; target = origin; areaNum = PointReachableAreaNum( target, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); PushPointIntoArea( areaNum, target ); gameRenderWorld->DebugArrow( colorGreen, origin, target, 1, 0 ); } /* ============ idAASLocal::ShowFloorTrace ============ */ void idAASLocal::ShowFloorTrace( const idVec3 &origin ) const { idPlayer *player; player = gameLocal.GetLocalPlayer(); if ( !player ) { return; } idMat3 playerAxis = idAngles( 0.0f, player->GetViewAngles().yaw, 0.0f ).ToMat3(); idVec3 org = origin; int areaNum = PointReachableAreaNum( org, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); PushPointIntoArea( areaNum, org ); aasTraceFloor_t trace; TraceFloor( trace, org, areaNum, origin + playerAxis[0] * 1024, TFL_WALK|TFL_AIR ); gameRenderWorld->DebugArrow( colorCyan, org, trace.endpos, 1, 0 ); idVec3 up = trace.endpos + playerAxis[2] * 64; const idVec4 &color = ( trace.fraction >= 1.0f ) ? colorGreen : colorRed; gameRenderWorld->DebugArrow( color, trace.endpos, up + playerAxis[1] * 32, 1, 0, true ); gameRenderWorld->DebugArrow( color, trace.endpos, up - playerAxis[1] * 32, 1, 0, true ); } /* ============ idAASLocal::ShowObstaclePVS ============ */ void idAASLocal::ShowObstaclePVS( const int areaNum ) const { const byte *pvs = GetObstaclePVS( areaNum ); for ( int i = 0; i < file->GetNumAreas(); i++ ) { if ( !IsInObstaclePVS( pvs, i ) ) { continue; } DrawArea( i ); } } /* ============ idAASLocal::ShowManualReachabilities ============ */ void idAASLocal::ShowManualReachabilities() const { for ( int i = 0; i < file->GetNumReachabilityNames(); i++ ) { const aasName_t &name = file->GetReachabilityName( i ); int index = file->FindReachabilityByName( name.name ); if ( index >= 0 ) { DrawReachability( &file->GetReachability( index ), name.name ); } } } /* ================== idAASLocal::ShowAASObstacles ================== */ void idAASLocal::ShowAASObstacles() const { idPlayer *player = gameLocal.GetLocalPlayer(); if ( !player ) { return; } idMat3 viewAxis = player->GetViewAxis(); for( int i = MAX_CLIENTS; i < MAX_GENTITIES; i++ ) { idEntity* ent = gameLocal.entities[ i ]; if ( ent == NULL ) { continue; } idAASObstacleEntity* obstacle = ent->Cast< idAASObstacleEntity >(); if ( obstacle == NULL ) { continue; } idVec4 colorType = colorGreen; if ( !obstacle->IsEnabled() ) { colorType = colorRed; } idVec3 org = obstacle->GetPhysics()->GetAbsBounds().GetCenter(); gameRenderWorld->DebugBounds( colorType, obstacle->GetPhysics()->GetAbsBounds() ); gameRenderWorld->DrawText( va( "Team: %i", obstacle->GetTeam() ), org, 0.20f, colorWhite, viewAxis ); } } /* ============ idAASLocal::ShowAASBadAreas ============ */ void idAASLocal::ShowAASBadAreas( int mode ) const { if ( file == NULL ) { return; } float height = file->GetSettings().boundingBox[1][2] - file->GetSettings().boundingBox[0][2]; for ( int i = 0; i < file->GetNumAreas(); i++ ) { const aasArea_t &area = file->GetArea( i ); idVec3 mid; mid.Zero(); for ( int j = 0; j < area.numEdges; j++ ) { int edgeNum = file->GetEdgeIndex( area.firstEdge + j ); const aasEdge_t &edge = file->GetEdge( abs( edgeNum ) ); mid += file->GetVertex( edge.vertexNum[ INT32_SIGNBITSET( edgeNum ) ] ); } mid /= area.numEdges; bool bad = false; if ( mode == 1 || mode == 3 ) { int j; for ( j = 0; j < 4; j++ ) { int areaNum = file->PointAreaNum( mid + file->GetSettings().invGravityDir * ( j * height ) ); if ( areaNum == i ) { break; } } if ( j >= 4 ) { bad = true; } } if ( mode == 2 || mode == 3 ) { #if 1 if ( ( area.flags & AAS_AREA_NOPUSH ) != 0 ) { bad = true; } #else idVec3 pushed = mid; if ( file->PushPointIntoArea( i, pushed ) ) { bad = true; } #endif } if ( bad ) { DrawArea( i ); } } } /* ============ idAASLocal::GetAreaNumAndLocation ============ */ bool idAASLocal::GetAreaNumAndLocation( idCVar &cvar, const idVec3 &origin, int &areaNum, idVec3 &location ) const { areaNum = 0; location.Zero(); if ( cvar.GetString()[0] == '\0' ) { return false; } if ( idStr::Icmp( cvar.GetString(), "memory" ) == 0 ) { cvar.SetString( aas_locationMemory.GetString() ); } if ( idStr::Icmp( cvar.GetString(), "current" ) == 0 ) { cvar.SetString( origin.ToString() ); } idLexer src( LEXFL_NOERRORS|LEXFL_NOWARNINGS ); src.LoadMemory( cvar.GetString(), idStr::Length( cvar.GetString() ), "areaNum" ); bool error = false; location.x = src.ParseFloat( &error ); location.y = src.ParseFloat( &error ); location.z = src.ParseFloat( &error ); if ( !error ) { areaNum = PointReachableAreaNum( location, DefaultSearchBounds(), AAS_AREA_REACHABLE_WALK, TravelFlagInvalidForTeam() ); PushPointIntoArea( areaNum, location ); return true; } src.Reset(); areaNum = src.ParseInt(); if ( ( areaNum > 0 ) && ( areaNum < file->GetNumAreas() ) ) { location = AreaCenter( areaNum ); return true; } return false; } /* ============ idAASLocal::Test ============ */ void idAASLocal::Test( const idVec3 &origin ) { int areaNum; idVec3 location; if ( file == NULL ) { return; } if ( GetAreaNumAndLocation( aas_locationMemory, origin, areaNum, location ) ) { } if ( GetAreaNumAndLocation( aas_showPath, origin, areaNum, location ) ) { ShowWalkPath( origin, areaNum, location ); } if ( GetAreaNumAndLocation( aas_showHopPath, origin, areaNum, location ) ) { ShowHopPath( origin, areaNum, location ); } if ( GetAreaNumAndLocation( aas_pullPlayer, origin, areaNum, location ) ) { int startAreaNum, travelTime; ShowWalkPath( origin, areaNum, location ); PullPlayer( origin, areaNum, location, startAreaNum, travelTime ); } else { UnFreezePlayer(); } if ( aas_randomPullPlayer.GetInteger() != 0 ) { RandomPullPlayer( origin, aas_randomPullPlayer.GetInteger() ); } if ( aas_showAreas.GetInteger() != 0 ) { ShowArea( origin, aas_showAreas.GetInteger() ); } if ( aas_showAreaNumber.GetInteger() != 0 ) { DrawArea( aas_showAreaNumber.GetInteger() ); } if ( ( aas_showNearestCoverArea.GetInteger() > 0 ) && ( aas_showNearestCoverArea.GetInteger() < file->GetNumAreas() ) ) { ShowNearestCoverArea( origin, aas_showNearestCoverArea.GetInteger() ); } if ( aas_showNearestInsideArea.GetBool() ) { ShowNearestInsideArea( origin ); } if ( aas_showWallEdges.GetInteger() != 0 ) { ShowWallEdges( origin, aas_showWallEdges.GetInteger(), aas_showWallEdgeNums.GetBool() ); } if ( aas_showPushIntoArea.GetBool() ) { ShowPushIntoArea( origin ); } if ( aas_showFloorTrace.GetBool() ) { ShowFloorTrace( origin ); } if ( GetAreaNumAndLocation( aas_showObstaclePVS, origin, areaNum, location ) ) { ShowObstaclePVS( areaNum ); } if ( aas_showManualReachabilities.GetBool() ) { ShowManualReachabilities(); } if ( aas_showFuncObstacles.GetBool() ) { ShowAASObstacles(); } if ( aas_showBadAreas.GetInteger() != 0 ) { ShowAASBadAreas( aas_showBadAreas.GetInteger() ); } }
/*######################################################################## Filename: MenuWndHook.cpp ---------------------------------------------------- Remarks: ... ---------------------------------------------------- Author: 成真 Email: anyou@sina.com anyou@msn.com Created: 7/4/2003 17:38 6/20/2012 黄建雄,修改为使用SSkin皮肤绘制非客户区边框,支持边框大小配置 ########################################################################*/ #include "souistd.h" #include "helper/MenuWndHook.h" #include "res.mgr/Sskinpool.h" #include "core/Sskin.h" #ifdef _WIN64 #define GWL_WNDPROC GWLP_WNDPROC #endif//_WIN64 namespace SOUI { const TCHAR CoolMenu_oldProc[] = _T("CoolMenu_oldProc"); #define SM_CXMENUBORDER 3 //默认菜单边框大小 /*######################################################################## ------------------------------------------------ class CMenuWndHook ------------------------------------------------ ########################################################################*/ SMap <HWND,CMenuWndHook*> CMenuWndHook::m_WndMenuMap; HHOOK CMenuWndHook::m_hMenuHook = NULL; SStringW CMenuWndHook::m_strSkinName; CMenuWndHook::CMenuWndHook (HWND hWnd) : m_hWnd(hWnd) { } CMenuWndHook::~CMenuWndHook () { WNDPROC oldWndProc = (WNDPROC)::GetProp(m_hWnd, CoolMenu_oldProc); if (oldWndProc != NULL) { ::SetWindowLongPtr(m_hWnd, GWLP_WNDPROC, (LONG_PTR)oldWndProc); ::RemoveProp(m_hWnd, CoolMenu_oldProc); } m_WndMenuMap.RemoveKey(m_hWnd); } void CMenuWndHook::InstallHook(HINSTANCE hInst,LPCWSTR pszSkinName) { if (m_hMenuHook == NULL ) { m_hMenuHook = ::SetWindowsHookEx(WH_CALLWNDPROC, WindowHook, hInst, ::GetCurrentThreadId()); m_strSkinName=pszSkinName; } } void CMenuWndHook::UnInstallHook() { SPOSITION pos= m_WndMenuMap.GetStartPosition(); while(pos) { SMap<HWND,CMenuWndHook*>::CPair *p=m_WndMenuMap.GetNext(pos); delete p->m_value; } m_WndMenuMap.RemoveAll(); if (m_hMenuHook != NULL) { ::UnhookWindowsHookEx(m_hMenuHook); } } CMenuWndHook* CMenuWndHook::GetWndHook(HWND hwnd) { SMap<HWND,CMenuWndHook*>::CPair *p=m_WndMenuMap.Lookup(hwnd); if(!p) return NULL; return p->m_value; } CMenuWndHook* CMenuWndHook::AddWndHook(HWND hwnd) { CMenuWndHook* pWnd = GetWndHook(hwnd); if(pWnd) return pWnd; pWnd = new CMenuWndHook(hwnd); if (pWnd != NULL) { m_WndMenuMap[hwnd]=pWnd; } return pWnd; } /*######################################################################## ------------------------------------------------ 消息过程 ------------------------------------------------ ########################################################################*/ LRESULT CALLBACK CMenuWndHook::WindowHook(int code, WPARAM wParam, LPARAM lParam) { CWPSTRUCT* pStruct = (CWPSTRUCT*)lParam; while (code == HC_ACTION) { HWND hWnd = pStruct->hwnd; if (pStruct->message != WM_CREATE && pStruct->message != 0x01E2) { break; } // 是否为菜单类 ---------------------------------------- TCHAR strClassName[10]; int Count = ::GetClassName (hWnd, strClassName, sizeof(strClassName) / sizeof(strClassName[0])); if (Count != 6 || _tcscmp(strClassName, _T("#32768")) != 0 ) { break; } // 是否已经被子类化 ------------------------------------ if (::GetProp(hWnd, CoolMenu_oldProc) != NULL ) { break; } AddWndHook(pStruct->hwnd); // 取得原来的窗口过程 ---------------------------------- WNDPROC oldWndProc = (WNDPROC)::GetWindowLongPtr(hWnd, GWLP_WNDPROC); if (oldWndProc == NULL) { break; } SASSERT(oldWndProc != CoolMenuProc); // 保存到窗口的属性中 ---------------------------------- if (!SetProp(hWnd, CoolMenu_oldProc, oldWndProc) ) { break; } // 子类化 ---------------------------------------------- if (!SetWindowLongPtr(hWnd, GWLP_WNDPROC,(LONG_PTR)CoolMenuProc) ) { ::RemoveProp(hWnd, CoolMenu_oldProc); break; } break; } return CallNextHookEx (m_hMenuHook, code, wParam, lParam); } LRESULT CALLBACK CMenuWndHook::CoolMenuProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { WNDPROC oldWndProc = (WNDPROC)::GetProp(hWnd, CoolMenu_oldProc); CMenuWndHook* pWnd = NULL; switch (uMsg) { case WM_CREATE: { LRESULT lResult = CallWindowProc(oldWndProc, hWnd, uMsg, wParam, lParam); if ((pWnd = GetWndHook(hWnd)) != NULL) { lResult = (LRESULT)pWnd->OnCreate((LPCREATESTRUCT)lParam); } return lResult; } break; case WM_NCCALCSIZE: { LRESULT lResult = CallWindowProc(oldWndProc, hWnd, uMsg, wParam, lParam); if ((pWnd = GetWndHook(hWnd)) != NULL) { pWnd->OnNcCalcsize((BOOL)wParam,(NCCALCSIZE_PARAMS*)lParam); } return lResult; } break; case WM_WINDOWPOSCHANGING: { if ((pWnd = GetWndHook(hWnd)) != NULL) { pWnd->OnWindowPosChanging((LPWINDOWPOS)lParam); } } break; case WM_WINDOWPOSCHANGED: { LRESULT lResult = CallWindowProc(oldWndProc, hWnd, uMsg, wParam, lParam); if ((pWnd = GetWndHook(hWnd)) != NULL) { pWnd->OnWindowPosChanged(); } return lResult; } break; case WM_PRINT: { LRESULT lResult = CallWindowProc(oldWndProc, hWnd, uMsg, wParam, lParam); if ((pWnd = GetWndHook(hWnd)) != NULL) { pWnd->OnPrint((HDC)wParam); } return lResult; } break; case WM_NCPAINT: { if ((pWnd = GetWndHook(hWnd)) != NULL) { pWnd->OnNcPaint(); return 0; } } break; case WM_NCDESTROY: { if ((pWnd = GetWndHook(hWnd)) != NULL) { pWnd->OnNcDestroy(); } } break; } return CallWindowProc(oldWndProc, hWnd, uMsg, wParam, lParam); } /*######################################################################## ------------------------------------------------ 消息处理函数 ------------------------------------------------ ########################################################################*/ int CMenuWndHook::OnCreate(LPCREATESTRUCT lpCreateStruct) { SetClassLong(m_hWnd, GCL_STYLE, GetClassLong(m_hWnd, GCL_STYLE) & ~CS_DROPSHADOW); return 0; } void CMenuWndHook::OnWindowPosChanging(WINDOWPOS *pWindowPos) { if(m_strSkinName.IsEmpty()) return; ISkinObj *pSkin=GETSKIN(m_strSkinName,100); if(!pSkin || !pSkin->IsClass(SSkinImgFrame::GetClassName())) return; SSkinImgFrame *pBorderSkin=static_cast<SSkinImgFrame*>(pSkin); if(!pBorderSkin) return; pWindowPos->cx += pBorderSkin->GetMargin().left+pBorderSkin->GetMargin().right-SM_CXMENUBORDER*2; pWindowPos->cy += pBorderSkin->GetMargin().top+pBorderSkin->GetMargin().bottom-SM_CXMENUBORDER*2; } void CMenuWndHook::OnNcCalcsize(BOOL bValidCalc,NCCALCSIZE_PARAMS* lpncsp) { if(m_strSkinName.IsEmpty()) return; ISkinObj *pSkin=GETSKIN(m_strSkinName,100); if(!pSkin || !pSkin->IsClass(SSkinImgFrame::GetClassName())) return; SSkinImgFrame *pBorderSkin=static_cast<SSkinImgFrame*>(pSkin); if(!pBorderSkin) return; lpncsp->rgrc[0].left=lpncsp->lppos->x+pBorderSkin->GetMargin().left; lpncsp->rgrc[0].top=lpncsp->lppos->y+pBorderSkin->GetMargin().top; lpncsp->rgrc[0].right=lpncsp->lppos->x+lpncsp->lppos->cx-pBorderSkin->GetMargin().right; lpncsp->rgrc[0].bottom=lpncsp->lppos->y+lpncsp->lppos->cy-pBorderSkin->GetMargin().bottom; } void CMenuWndHook::OnNcPaint() { HDC dc=GetWindowDC(m_hWnd); OnPrint(dc); ReleaseDC(m_hWnd,dc); } void CMenuWndHook::OnPrint(HDC dc) { if(m_strSkinName.IsEmpty()) return; ISkinObj *pSkin=GETSKIN(m_strSkinName,100); if(!pSkin) return; SSkinImgFrame *pBorderSkin=static_cast<SSkinImgFrame*>(pSkin); if(!pBorderSkin) return; CRect rcClient; GetClientRect(m_hWnd,&rcClient); ClientToScreen(m_hWnd,(LPPOINT)&rcClient); ClientToScreen(m_hWnd,((LPPOINT)&rcClient)+1); CRect rcWnd; GetWindowRect(m_hWnd, &rcWnd); rcClient.OffsetRect(-rcWnd.TopLeft()); int nSave = ::SaveDC(dc); ::ExcludeClipRect(dc,rcClient.left,rcClient.top,rcClient.right,rcClient.bottom); rcWnd.MoveToXY(0,0); CAutoRefPtr<IRenderTarget> pRT; GETRENDERFACTORY->CreateRenderTarget(&pRT,rcWnd.Width(),rcWnd.Height()); pBorderSkin->Draw(pRT,rcWnd,0); HDC hmemdc=pRT->GetDC(0); ::BitBlt(dc,0,0,rcWnd.Width(),rcWnd.Height(),hmemdc,0,0,SRCCOPY); pRT->ReleaseDC(hmemdc); ::RestoreDC(dc,nSave); } void CMenuWndHook::OnNcDestroy() { delete this; } //不能设计窗口半透明,设置区域后,非客户区位置发生改变,不明白原因。 void CMenuWndHook::OnWindowPosChanged() { /* CRect rcWnd; GetWindowRect(m_hWnd,&rcWnd); rcWnd.MoveToXY(0,0); HRGN hRgn = ::CreateEllipticRgnIndirect(&rcWnd); SetWindowRgn(m_hWnd,hRgn,TRUE); DeleteObject(hRgn); */ } }//namespace SOUI
#include "oblivious_tree_bin_builder.h" #include <catboost/libs/helpers/set.h> namespace NCatboostCuda { namespace { template <class TDataSet, class TCtrSplitBuilder> class TSplitHelper: public IBinarySplitProvider { public: TSplitHelper(TScopedCacheHolder& scopedCache, TCtrSplitBuilder& builder, const TBinarizedFeaturesManager& featuresManager, const TDataSet& dataSet) : ScopedCache(scopedCache) , CtrSplitBuilder(builder) , FeaturesManager(featuresManager) , DataSet(dataSet) { } const TMirrorBuffer<ui64>& GetCompressedBits(const TBinarySplit& split) const final { const ui32 featureId = split.FeatureId; if (DataSet.HasFeatures() && DataSet.GetFeatures().HasFeature(featureId)) { return GetCompressedBitsFromGpuFeatures(DataSet.GetFeatures(), split, nullptr); } else if (DataSet.HasPermutationDependentFeatures() && DataSet.GetPermutationFeatures().HasFeature(featureId)) { return GetCompressedBitsFromGpuFeatures(DataSet.GetPermutationFeatures(), split, &DataSet.GetInverseIndices()); } else if (FeaturesManager.IsTreeCtr(split.FeatureId)) { return CtrSplitBuilder.ComputeAndCacheCtrSplit(DataSet, split); } else { ythrow TCatBoostException() << "Error: unknown feature"; } } void Split(const TBinarySplit& split, TMirrorBuffer<ui32>& bins, ui32 depth) final { const auto& compressedBits = GetCompressedBits(split); UpdateBinFromCompressedBits(compressedBits, bins, depth); } void SplitByExternalComputedFeature(const TBinarySplit& split, const TSingleBuffer<const ui64>& compressedBits, TMirrorBuffer<ui32>& dst, ui32 depth) { CB_ENSURE(FeaturesManager.IsTreeCtr(split.FeatureId), "Feature id should be combinations ctr"); const auto& ctr = FeaturesManager.GetCtr(split.FeatureId); const ui32 docCount = DataSet.GetSamplesMapping().GetObjectsSlice().Size(); const ui32 compressedSize = CompressedSize<ui64>(docCount, 2); auto broadcastFunction = [&]() -> TMirrorBuffer<ui64> { TMirrorBuffer<ui64> broadcastedBits = TMirrorBuffer<ui64>::Create(NCudaLib::TMirrorMapping(compressedSize)); Reshard(compressedBits, broadcastedBits); return broadcastedBits; }; const auto& mirrorCompressedBits = [&]() -> const TMirrorBuffer<ui64>& { if (FeaturesManager.IsPermutationDependent(ctr)) { return ScopedCache.Cache(DataSet.GetPermutationDependentScope(), split, broadcastFunction); } else { return ScopedCache.Cache(DataSet.GetPermutationIndependentScope(), split, broadcastFunction); } }(); UpdateBinFromCompressedBits(mirrorCompressedBits, dst, depth); } private: const TMirrorBuffer<ui64>& GetCompressedBitsFromGpuFeatures(const TCompressedDataSet<>& dataSet, const TBinarySplit& split, const TMirrorBuffer<ui32>* readIndices) const { const ui32 featureId = split.FeatureId; CB_ENSURE(dataSet.HasFeature(featureId), TStringBuilder() << "Error: can't get compressed bits for feature " << featureId); return ScopedCache.Cache(dataSet, split, [&]() -> TMirrorBuffer<ui64> { return BuildMirrorSplitForDataSet(dataSet, split, readIndices); }); } TMirrorBuffer<ui64> BuildMirrorSplitForDataSet(const TCompressedDataSet<>& ds, const TBinarySplit& split, const TMirrorBuffer<ui32>* readIndices = nullptr) const { auto feature = ds.GetTCFeature(split.FeatureId); const ui32 docCount = ds.GetDocCount(); const ui32 compressedSize = CompressedSize<ui64>(docCount, 2); TMirrorBuffer<ui64> broadcastedBits = TMirrorBuffer<ui64>::Create(NCudaLib::TMirrorMapping(compressedSize)); const ui32 devCount = GetDeviceCount(); for (ui32 dev = 0; dev < devCount; ++dev) { if (!feature.IsEmpty(dev)) { TSingleBuffer<ui64> compressedBits = TSingleBuffer<ui64>::Create(NCudaLib::TSingleMapping(dev, compressedSize)); TSingleBuffer<const ui32> indices; if (readIndices) { indices = readIndices->DeviceView(dev); } CreateCompressedSplit(ds, feature, split.BinIdx, compressedBits, readIndices ? &indices : nullptr); Reshard(compressedBits, broadcastedBits); break; } CB_ENSURE(dev + 1 != devCount, TStringBuilder() << "Error : feature was not found " << split.FeatureId); } return broadcastedBits; } TScopedCacheHolder& ScopedCache; TCtrSplitBuilder& CtrSplitBuilder; const TBinarizedFeaturesManager& FeaturesManager; const TDataSet& DataSet; }; } bool TFeatureTensorTracker::AddFeatureTensor(const TFeatureTensor& featureTensor) { const TFeatureTensor prevTensor = CurrentTensor; CurrentTensor.AddTensor(featureTensor); if (prevTensor == CurrentTensor) { return false; } TCtrBinBuilder<NCudaLib::TMirrorMapping> binBuilder(Stream); if (LearnSlice.Size() == 0) { binBuilder.SetIndices(LearnDataSet->GetIndices(), LinkedTest ? &(LinkedTest->GetIndices()) : nullptr); LearnSlice = binBuilder.GetLearnSlice(); } else { binBuilder.SetIndices(std::move(Indices), LearnSlice); //some ping-pong with buffer } auto catFeatures = NCB::RemoveExisting(CurrentTensor.GetCatFeatures(), prevTensor.GetCatFeatures()); auto binarySplits = NCB::RemoveExisting(CurrentTensor.GetSplits(), prevTensor.GetSplits()); TMirrorCatFeatureProvider broadcastedCatFeatures(LearnDataSet->GetCatFeatures(), *CacheHolder); for (ui32 catFeature : catFeatures) { const auto& compressedFeatures = broadcastedCatFeatures.BroadcastFeature(catFeature, Stream) .GetInStream(Stream); if (LinkedTest) { TMirrorCatFeatureProvider broadcastedTestCatFeatures( LinkedTest->GetCatFeatures(), *CacheHolder); const auto& compressedTest = broadcastedTestCatFeatures.BroadcastFeature(catFeature, Stream) .GetInStream(Stream); binBuilder.AddCompressedBins(compressedFeatures, compressedTest, FeaturesManager->GetBinCount(catFeature)); } else { binBuilder.AddCompressedBins(compressedFeatures, FeaturesManager->GetBinCount(catFeature)); } } //TODO(noxoomo): builder should merge several task in one for (const auto& binarySplit : binarySplits) { const auto& learnBits = LearnBinarySplitsProvider->GetCompressedBits(binarySplit); if (LinkedTest) { const auto& testBits = TestBinarySplitsProvider->GetCompressedBits(binarySplit); binBuilder.AddCompressedBins(learnBits, testBits, 2); } else { binBuilder.AddCompressedBins(learnBits, 2); } } Indices = binBuilder.MoveIndices(); return true; } TFeatureTensorTracker TFeatureTensorTracker::Copy() { TFeatureTensorTracker other(*CacheHolder, *FeaturesManager, *LearnDataSet, *LearnBinarySplitsProvider, LinkedTest, TestBinarySplitsProvider, Stream); other.CurrentTensor = CurrentTensor; other.LearnSlice = LearnSlice; other.Indices.Reset(Indices.GetMapping()); other.Indices.Copy(Indices, Stream); return other; } TTreeUpdater& TTreeUpdater::AddSplit(const TBinarySplit& split) { //TODO(noxoomo): current caching logic is too complicated. It should be easier SplitHelper->Split(split, LearnBins, (ui32)BinarySplits.size()); if (LinkedTest) { TestSplitHelper->Split(split, *TestBins, (ui32)BinarySplits.size()); } BinarySplits.push_back(split); return *this; } const TMirrorBuffer<ui64>& TTreeUpdater::ComputeAndCacheCtrSplit(const TTreeUpdater::TDataSet& dataSet, const TBinarySplit& split) { CB_ENSURE(&dataSet == &LearnDataSet || (&dataSet == LinkedTest)); using TCtrHelper = TCalcCtrHelper<NCudaLib::TMirrorMapping>; CB_ENSURE(FeaturesManager.IsCtr(split.FeatureId), "Error: split should be ctr"); const auto& ctr = FeaturesManager.GetCtr(split.FeatureId); bool floatCtrBuilderWasCalledFlag = false; auto floatCtrBuilder = [&]() -> TMirrorBuffer<float> { if (!CanContinueTensorTracker(ctr.FeatureTensor)) { TensorTracker = CreateEmptyTensorTracker(); } TensorTracker->AddFeatureTensor(ctr.FeatureTensor); TCtrHelper helper(CtrTargets, TensorTracker->GetIndices()); floatCtrBuilderWasCalledFlag = true; auto floatCtr = helper.ComputeCtr(ctr.Configuration); return floatCtr; }; TMirrorBuffer<float> floatCtr; auto& borders = FeaturesManager.GetBorders(split.FeatureId); auto buildLearnBitsFunction = [&]() -> TMirrorBuffer<ui64> { if (!floatCtrBuilderWasCalledFlag) { floatCtr = floatCtrBuilder(); } return CreateSplit(floatCtr, borders[split.BinIdx], CtrTargets.LearnSlice); }; auto buildTestBitsFunction = [&]() -> TMirrorBuffer<ui64> { if (!floatCtrBuilderWasCalledFlag) { floatCtr = floatCtrBuilder(); } return CreateSplit(floatCtr, borders[split.BinIdx], CtrTargets.TestSlice); }; const auto& compressedSplitLearn = CacheTreeCtrSplit(LearnDataSet, split, buildLearnBitsFunction); const TMirrorBuffer<ui64>* compressedSplitTest = LinkedTest ? &CacheTreeCtrSplit(*LinkedTest, split, buildTestBitsFunction) : nullptr; if (&dataSet == LinkedTest) { CB_ENSURE(compressedSplitTest); return *compressedSplitTest; } return compressedSplitLearn; } TMirrorBuffer<ui64> TTreeUpdater::CreateSplit(const TMirrorBuffer<float>& ctr, const float border, TSlice slice) { auto compressedSplit = TMirrorBuffer<ui64>::Create( NCudaLib::TMirrorMapping(CompressedSize<ui64>(static_cast<ui32>(slice.Size()), 2))); CreateCompressedSplitFloat(ctr.SliceView(slice), border, compressedSplit); return compressedSplit; } TTreeUpdater::TTreeUpdater(TScopedCacheHolder& cacheHolder, const TBinarizedFeaturesManager& featuresManager, const TCtrTargets<NCudaLib::TMirrorMapping>& ctrTargets, const TTreeUpdater::TDataSet& learnSet, TMirrorBuffer<ui32>& learnBins, const TTreeUpdater::TDataSet* testSet, TMirrorBuffer<unsigned int>* testBins) : FeaturesManager(featuresManager) , CacheHolder(cacheHolder) , CtrTargets(ctrTargets) , LearnDataSet(learnSet) , LinkedTest(testSet) , SplitHelper(new TSplitHelper<TDataSet, TTreeUpdater>(CacheHolder, *this, featuresManager, LearnDataSet)) , LearnBins(learnBins) , TestBins(testBins) { if (LinkedTest) { TestSplitHelper.Reset(new TSplitHelper<TDataSet, TTreeUpdater>(CacheHolder, *this, FeaturesManager, *LinkedTest)); } FillBuffer(LearnBins, 0u); if (LinkedTest) { FillBuffer(*TestBins, 0u); } } TTreeUpdater& TTreeUpdater::AddSplit(const TBinarySplit& split, const TSingleBuffer<const ui64>& compressedBins) { CB_ENSURE(LinkedTest == nullptr, "Error: need test bins to add externally-computed split"); SplitHelper->SplitByExternalComputedFeature(split, compressedBins.ConstCopyView(), LearnBins, (ui32)BinarySplits.size()); if (LinkedTest) { TestSplitHelper->Split(split, *TestBins, (ui32)BinarySplits.size()); } BinarySplits.push_back(split); return *this; } }
#include "stdafx.h" #include "shibari_tls_linker.h" shibari_tls_linker::shibari_tls_linker(std::vector<shibari_module*>* extended_modules, shibari_module* main_module) : extended_modules(extended_modules), main_module(main_module) {} shibari_tls_linker::~shibari_tls_linker() { } shibari_linker_errors shibari_tls_linker::link_modules() { for (auto& module : *extended_modules) { if (module->get_module_image().get_tls().get_callbacks().size()) { for (auto& item : module->get_module_image().get_tls().get_callbacks()) { main_module->get_module_image().get_tls().get_callbacks().push_back({ module->get_module_position().get_address_offset() + item.rva_callback ,item.use_relocation }); } } } return shibari_linker_errors::shibari_linker_ok; }
// -*- C++ -*- // // michael a.g. aïvázis // orthologue // (c) 1998-2021 all rights reserved // #include <portinfo> #include <Python.h> #include <pyre/journal.h> // my declarations #include "device.h" // local support #include "exceptions.h" // so I can build reasonable error messages #include <sstream> // access to the CUDA runtime #include <cuda.h> #include <cuda_runtime.h> // grab a device PyObject * pyre::extensions::cuda:: setDevice(PyObject *, PyObject *args) { // allocate storage for the arguments int did; // if I were not passed the expected arguments if (!PyArg_ParseTuple(args, "i:setDevice", &did)) { // raise an exception return nullptr; } // attempt to grab the device cudaError_t status = cudaSetDevice(did); // if anything went wrong if (status != cudaSuccess) { // make an error channel pyre::journal::error_t error("cuda"); // show me error << pyre::journal::at(__HERE__) << "while reserving device " << did << ": " << cudaGetErrorName(status) << " (" << status << ")" << pyre::journal::endl; // create an exception object // prep the constructor arguments PyObject * args = PyTuple_New(0); PyObject * kwds = Py_BuildValue("{s:s}", "description", cudaGetErrorName(status)); // build it PyObject * exception = PyObject_Call(Error, args, kwds); // mark it as the pending exception PyErr_SetObject(Error, exception); // and bail return nullptr; } // all done Py_INCREF(Py_None); return Py_None; } // reset a device PyObject * pyre::extensions::cuda:: resetDevice(PyObject *, PyObject *args) { // if I were not passed the expected arguments if (!PyArg_ParseTuple(args, ":resetDevice", &PyType_Type)) { // raise an exception return nullptr; } // attempt to grab the device cudaError_t status = cudaDeviceReset(); // if anything went wrong if (status != cudaSuccess) { // make an error channel pyre::journal::error_t error("cuda"); // show me error << pyre::journal::at(__HERE__) << "while resetting the current device: " << cudaGetErrorName(status) << " (" << status << ")" << pyre::journal::endl; // create an exception object // prep the constructor arguments PyObject * args = PyTuple_New(0); PyObject * kwds = Py_BuildValue("{s:s}", "description", cudaGetErrorName(status)); // build it PyObject * exception = PyObject_Call(Error, args, kwds); // mark it as the pending exception PyErr_SetObject(Error, exception); // and bail return nullptr; } // all done Py_INCREF(Py_None); return Py_None; } // end of file
#pragma once #include "Quasar/System/DllLoader.hpp" #include <dlfcn.h> namespace Quasar { template<typename T> class LinuxDllLoader : public DllLoader<T> { private: void *m_Handle; std::string m_Filepath; protected: void openDll() override; void closeDll() override; public: LinuxDllLoader(const std::string &filepath); ~LinuxDllLoader(); Ref<T> getClassInstance(const std::string &allocClassSymbol = "create", const std::string &destroyClassSymbol = "destroy") override; }; } // namespace Quasar
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #include "ash/ash_switches.h" #include "ash/display/display_controller.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_button.h" #include "ash/shelf/shelf_constants.h" #include "ash/shelf/shelf_model.h" #include "ash/shelf/shelf_util.h" #include "ash/shelf/shelf_view.h" #include "ash/shell.h" #include "ash/test/app_list_controller_test_api.h" #include "ash/test/shelf_test_api.h" #include "ash/test/shelf_view_test_api.h" #include "ash/test/shell_test_api.h" #include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/apps/app_browsertest_util.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/app_list_service.h" #include "chrome/browser/ui/ash/launcher/browser_shortcut_launcher_item_controller.h" #include "chrome/browser/ui/ash/launcher/launcher_application_menu_item_model.h" #include "chrome/browser/ui/ash/launcher/launcher_item_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/extensions/app_launch_params.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/settings_window_manager.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/app_window/native_app_window.h" #include "extensions/browser/extension_system.h" #include "extensions/common/constants.h" #include "extensions/common/switches.h" #include "extensions/test/extension_test_message_listener.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/app_list/app_list_switches.h" #include "ui/app_list/views/app_list_item_view.h" #include "ui/app_list/views/apps_grid_view.h" #include "ui/app_list/views/start_page_view.h" #include "ui/app_list/views/tile_item_view.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/base/window_open_disposition.h" #include "ui/events/event.h" #include "ui/events/test/event_generator.h" using extensions::AppWindow; using extensions::Extension; using content::WebContents; namespace { class TestEvent : public ui::Event { public: explicit TestEvent(ui::EventType type) : ui::Event(type, base::TimeDelta(), 0) { } ~TestEvent() override {} private: DISALLOW_COPY_AND_ASSIGN(TestEvent); }; class TestAppWindowRegistryObserver : public extensions::AppWindowRegistry::Observer { public: explicit TestAppWindowRegistryObserver(Profile* profile) : profile_(profile), icon_updates_(0) { extensions::AppWindowRegistry::Get(profile_)->AddObserver(this); } ~TestAppWindowRegistryObserver() override { extensions::AppWindowRegistry::Get(profile_)->RemoveObserver(this); } // Overridden from AppWindowRegistry::Observer: void OnAppWindowIconChanged(AppWindow* app_window) override { ++icon_updates_; } int icon_updates() { return icon_updates_; } private: Profile* profile_; int icon_updates_; DISALLOW_COPY_AND_ASSIGN(TestAppWindowRegistryObserver); }; // Click the "All Apps" button from the app launcher start page. Assumes that // the app launcher is open to the start page. On the non-experimental launcher, // does nothing. // |display_origin| is the top-left corner of the active display, in screen // coordinates. void ClickAllAppsButtonFromStartPage(ui::test::EventGenerator* generator, const gfx::Point& display_origin) { if (!app_list::switches::IsExperimentalAppListEnabled()) return; ash::test::AppListControllerTestApi controller_test( ash::Shell::GetInstance()); app_list::StartPageView* start_page_view = controller_test.GetStartPageView(); DCHECK(start_page_view); app_list::TileItemView* all_apps_button = start_page_view->all_apps_button(); gfx::Rect all_apps_rect = all_apps_button->GetBoundsInScreen(); all_apps_rect.Offset(-display_origin.x(), -display_origin.y()); generator->MoveMouseTo(all_apps_rect.CenterPoint().x(), all_apps_rect.CenterPoint().y()); generator->ClickLeftButton(); base::MessageLoop::current()->RunUntilIdle(); // Run Layout() to effectively complete the animation to the apps page. controller_test.LayoutContentsView(); } } // namespace class LauncherPlatformAppBrowserTest : public extensions::PlatformAppBrowserTest { protected: LauncherPlatformAppBrowserTest() : shelf_(NULL), controller_(NULL) { } ~LauncherPlatformAppBrowserTest() override {} void RunTestOnMainThreadLoop() override { shelf_ = ash::Shelf::ForPrimaryDisplay(); controller_ = ChromeLauncherController::instance(); return extensions::PlatformAppBrowserTest::RunTestOnMainThreadLoop(); } ash::ShelfModel* shelf_model() { return ash::test::ShellTestApi(ash::Shell::GetInstance()).shelf_model(); } ash::ShelfID CreateAppShortcutLauncherItem(const std::string& name) { return controller_->CreateAppShortcutLauncherItem( name, controller_->model()->item_count()); } const ash::ShelfItem& GetLastLauncherItem() { // Unless there are any panels, the item at index [count - 1] will be // the desired item. return shelf_model()->items()[shelf_model()->item_count() - 1]; } const ash::ShelfItem& GetLastLauncherPanelItem() { // Panels show up on the right side of the shelf, so the desired item // will be the last one. return shelf_model()->items()[shelf_model()->item_count() - 1]; } LauncherItemController* GetItemController(ash::ShelfID id) { return controller_->id_to_item_controller_map_[id]; } // Returns the number of menu items, ignoring separators. int GetNumApplicationMenuItems(const ash::ShelfItem& item) { const int event_flags = 0; scoped_ptr<ash::ShelfMenuModel> menu(new LauncherApplicationMenuItemModel( controller_->GetApplicationList(item, event_flags))); int num_items = 0; for (int i = 0; i < menu->GetItemCount(); ++i) { if (menu->GetTypeAt(i) != ui::MenuModel::TYPE_SEPARATOR) ++num_items; } return num_items; } // Activate the shelf item with the given |id|. void ActivateShelfItem(int id) { shelf_->ActivateShelfItem(id); } ash::Shelf* shelf_; ChromeLauncherController* controller_; private: DISALLOW_COPY_AND_ASSIGN(LauncherPlatformAppBrowserTest); }; enum RipOffCommand { // Drag the item off the shelf and let the mouse go. RIP_OFF_ITEM, // Drag the item off the shelf, move the mouse back and then let go. RIP_OFF_ITEM_AND_RETURN, // Drag the item off the shelf and then issue a cancel command. RIP_OFF_ITEM_AND_CANCEL, // Drag the item off the shelf and do not release the mouse. RIP_OFF_ITEM_AND_DONT_RELEASE_MOUSE, }; class ShelfAppBrowserTest : public ExtensionBrowserTest { protected: ShelfAppBrowserTest() : shelf_(NULL), model_(NULL), controller_(NULL) { } ~ShelfAppBrowserTest() override {} void RunTestOnMainThreadLoop() override { shelf_ = ash::Shelf::ForPrimaryDisplay(); model_ = ash::test::ShellTestApi(ash::Shell::GetInstance()).shelf_model(); controller_ = ChromeLauncherController::instance(); return ExtensionBrowserTest::RunTestOnMainThreadLoop(); } size_t NumberOfDetectedLauncherBrowsers(bool show_all_tabs) { LauncherItemController* item_controller = controller_->GetBrowserShortcutLauncherItemController(); int items = item_controller->GetApplicationList( show_all_tabs ? ui::EF_SHIFT_DOWN : 0).size(); // If we have at least one item, we have also a title which we remove here. return items ? (items - 1) : 0; } const Extension* LoadAndLaunchExtension( const char* name, extensions::LaunchContainer container, WindowOpenDisposition disposition) { EXPECT_TRUE(LoadExtension(test_data_dir_.AppendASCII(name))); ExtensionService* service = extensions::ExtensionSystem::Get( profile())->extension_service(); const Extension* extension = service->GetExtensionById(last_loaded_extension_id(), false); EXPECT_TRUE(extension); OpenApplication(AppLaunchParams(profile(), extension, container, disposition, extensions::SOURCE_TEST)); return extension; } ash::ShelfID CreateShortcut(const char* name) { ExtensionService* service = extensions::ExtensionSystem::Get( profile())->extension_service(); LoadExtension(test_data_dir_.AppendASCII(name)); // First get app_id. const Extension* extension = service->GetExtensionById(last_loaded_extension_id(), false); const std::string app_id = extension->id(); // Then create a shortcut. int item_count = model_->item_count(); ash::ShelfID shortcut_id = controller_->CreateAppShortcutLauncherItem( app_id, item_count); controller_->PersistPinnedState(); EXPECT_EQ(++item_count, model_->item_count()); const ash::ShelfItem& item = *model_->ItemByID(shortcut_id); EXPECT_EQ(ash::TYPE_APP_SHORTCUT, item.type); return item.id; } void RemoveShortcut(ash::ShelfID id) { controller_->Unpin(id); } // Activate the shelf item with the given |id|. void ActivateShelfItem(int id) { shelf_->ActivateShelfItem(id); } ash::ShelfID PinFakeApp(const std::string& name) { return controller_->CreateAppShortcutLauncherItem( name, model_->item_count()); } // Get the index of an item which has the given type. int GetIndexOfShelfItemType(ash::ShelfItemType type) { return model_->GetItemIndexForType(type); } // Try to rip off |item_index|. void RipOffItemIndex(int index, ui::test::EventGenerator* generator, ash::test::ShelfViewTestAPI* test, RipOffCommand command) { ash::ShelfButton* button = test->GetButton(index); gfx::Point start_point = button->GetBoundsInScreen().CenterPoint(); gfx::Point rip_off_point(start_point.x(), 0); generator->MoveMouseTo(start_point.x(), start_point.y()); base::MessageLoop::current()->RunUntilIdle(); generator->PressLeftButton(); base::MessageLoop::current()->RunUntilIdle(); generator->MoveMouseTo(rip_off_point.x(), rip_off_point.y()); base::MessageLoop::current()->RunUntilIdle(); test->RunMessageLoopUntilAnimationsDone(); if (command == RIP_OFF_ITEM_AND_RETURN) { generator->MoveMouseTo(start_point.x(), start_point.y()); base::MessageLoop::current()->RunUntilIdle(); test->RunMessageLoopUntilAnimationsDone(); } else if (command == RIP_OFF_ITEM_AND_CANCEL) { // This triggers an internal cancel. Using VKEY_ESCAPE was too unreliable. button->OnMouseCaptureLost(); } if (command != RIP_OFF_ITEM_AND_DONT_RELEASE_MOUSE) { generator->ReleaseLeftButton(); base::MessageLoop::current()->RunUntilIdle(); test->RunMessageLoopUntilAnimationsDone(); } } ash::Shelf* shelf_; ash::ShelfModel* model_; ChromeLauncherController* controller_; private: DISALLOW_COPY_AND_ASSIGN(ShelfAppBrowserTest); }; class ShelfAppBrowserTestNoDefaultBrowser : public ShelfAppBrowserTest { protected: ShelfAppBrowserTestNoDefaultBrowser() {} ~ShelfAppBrowserTestNoDefaultBrowser() override {} void SetUpCommandLine(base::CommandLine* command_line) override { ShelfAppBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kNoStartupWindow); } private: DISALLOW_COPY_AND_ASSIGN(ShelfAppBrowserTestNoDefaultBrowser); }; // Since the default for minimizing on click might change, I added both classes // to either get the minimize on click or not. class ShelfAppBrowserNoMinimizeOnClick : public LauncherPlatformAppBrowserTest { protected: ShelfAppBrowserNoMinimizeOnClick() {} ~ShelfAppBrowserNoMinimizeOnClick() override {} void SetUpCommandLine(base::CommandLine* command_line) override { LauncherPlatformAppBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitch( switches::kDisableMinimizeOnSecondLauncherItemClick); } private: DISALLOW_COPY_AND_ASSIGN(ShelfAppBrowserNoMinimizeOnClick); }; typedef LauncherPlatformAppBrowserTest ShelfAppBrowserMinimizeOnClick; // Test that we can launch a platform app and get a running item. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, LaunchUnpinned) { int item_count = shelf_model()->item_count(); const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow* window = CreateAppWindow(extension); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item = GetLastLauncherItem(); EXPECT_EQ(ash::TYPE_PLATFORM_APP, item.type); EXPECT_EQ(ash::STATUS_ACTIVE, item.status); CloseAppWindow(window); --item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); } // Test that we can launch a platform app that already has a shortcut. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, LaunchPinned) { int item_count = shelf_model()->item_count(); // First get app_id. const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); const std::string app_id = extension->id(); // Then create a shortcut. ash::ShelfID shortcut_id = CreateAppShortcutLauncherItem(app_id); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); ash::ShelfItem item = *shelf_model()->ItemByID(shortcut_id); EXPECT_EQ(ash::TYPE_APP_SHORTCUT, item.type); EXPECT_EQ(ash::STATUS_CLOSED, item.status); // Open a window. Confirm the item is now running. AppWindow* window = CreateAppWindow(extension); ash::wm::ActivateWindow(window->GetNativeWindow()); ASSERT_EQ(item_count, shelf_model()->item_count()); item = *shelf_model()->ItemByID(shortcut_id); EXPECT_EQ(ash::TYPE_APP_SHORTCUT, item.type); EXPECT_EQ(ash::STATUS_ACTIVE, item.status); // Then close it, make sure there's still an item. CloseAppWindow(window); ASSERT_EQ(item_count, shelf_model()->item_count()); item = *shelf_model()->ItemByID(shortcut_id); EXPECT_EQ(ash::TYPE_APP_SHORTCUT, item.type); EXPECT_EQ(ash::STATUS_CLOSED, item.status); } IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, PinRunning) { // Run. int item_count = shelf_model()->item_count(); const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow* window = CreateAppWindow(extension); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item1 = GetLastLauncherItem(); ash::ShelfID id = item1.id; EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); // Create a shortcut. The app item should be after it. ash::ShelfID foo_id = CreateAppShortcutLauncherItem("foo"); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); EXPECT_LT(shelf_model()->ItemIndexByID(foo_id), shelf_model()->ItemIndexByID(id)); // Pin the app. The item should remain. controller_->Pin(id); ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item2 = *shelf_model()->ItemByID(id); EXPECT_EQ(ash::TYPE_APP_SHORTCUT, item2.type); EXPECT_EQ(ash::STATUS_ACTIVE, item2.status); // New shortcuts should come after the item. ash::ShelfID bar_id = CreateAppShortcutLauncherItem("bar"); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); EXPECT_LT(shelf_model()->ItemIndexByID(id), shelf_model()->ItemIndexByID(bar_id)); // Then close it, make sure the item remains. CloseAppWindow(window); ASSERT_EQ(item_count, shelf_model()->item_count()); } IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, UnpinRunning) { int item_count = shelf_model()->item_count(); // First get app_id. const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); const std::string app_id = extension->id(); // Then create a shortcut. ash::ShelfID shortcut_id = CreateAppShortcutLauncherItem(app_id); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); ash::ShelfItem item = *shelf_model()->ItemByID(shortcut_id); EXPECT_EQ(ash::TYPE_APP_SHORTCUT, item.type); EXPECT_EQ(ash::STATUS_CLOSED, item.status); // Create a second shortcut. This will be needed to force the first one to // move once it gets unpinned. ash::ShelfID foo_id = CreateAppShortcutLauncherItem("foo"); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); EXPECT_LT(shelf_model()->ItemIndexByID(shortcut_id), shelf_model()->ItemIndexByID(foo_id)); // Open a window. Confirm the item is now running. AppWindow* window = CreateAppWindow(extension); ash::wm::ActivateWindow(window->GetNativeWindow()); ASSERT_EQ(item_count, shelf_model()->item_count()); item = *shelf_model()->ItemByID(shortcut_id); EXPECT_EQ(ash::TYPE_APP_SHORTCUT, item.type); EXPECT_EQ(ash::STATUS_ACTIVE, item.status); // Unpin the app. The item should remain. controller_->Unpin(shortcut_id); ASSERT_EQ(item_count, shelf_model()->item_count()); item = *shelf_model()->ItemByID(shortcut_id); EXPECT_EQ(ash::TYPE_PLATFORM_APP, item.type); EXPECT_EQ(ash::STATUS_ACTIVE, item.status); // The item should have moved after the other shortcuts. EXPECT_GT(shelf_model()->ItemIndexByID(shortcut_id), shelf_model()->ItemIndexByID(foo_id)); // Then close it, make sure the item's gone. CloseAppWindow(window); --item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); } // Test that we can launch a platform app with more than one window. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, MultipleWindows) { int item_count = shelf_model()->item_count(); // First run app. const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow* window1 = CreateAppWindow(extension); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item1 = GetLastLauncherItem(); ash::ShelfID item_id = item1.id; EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); EXPECT_EQ(2, GetNumApplicationMenuItems(item1)); // Title + 1 window // Add second window. AppWindow* window2 = CreateAppWindow(extension); // Confirm item stays. ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item2 = *shelf_model()->ItemByID(item_id); EXPECT_EQ(ash::STATUS_ACTIVE, item2.status); EXPECT_EQ(3, GetNumApplicationMenuItems(item2)); // Title + 2 windows // Close second window. CloseAppWindow(window2); // Confirm item stays. ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item3 = *shelf_model()->ItemByID(item_id); EXPECT_EQ(ash::STATUS_ACTIVE, item3.status); EXPECT_EQ(2, GetNumApplicationMenuItems(item3)); // Title + 1 window // Close first window. CloseAppWindow(window1); // Confirm item is removed. --item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); } IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, MultipleApps) { int item_count = shelf_model()->item_count(); // First run app. const Extension* extension1 = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow* window1 = CreateAppWindow(extension1); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item1 = GetLastLauncherItem(); ash::ShelfID item_id1 = item1.id; EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); // Then run second app. const Extension* extension2 = LoadAndLaunchPlatformApp("launch_2", "Launched"); AppWindow* window2 = CreateAppWindow(extension2); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item2 = GetLastLauncherItem(); ash::ShelfID item_id2 = item2.id; EXPECT_EQ(ash::TYPE_PLATFORM_APP, item2.type); EXPECT_EQ(ash::STATUS_ACTIVE, item2.status); EXPECT_NE(item_id1, item_id2); EXPECT_EQ(ash::STATUS_RUNNING, shelf_model()->ItemByID(item_id1)->status); // Close second app. CloseAppWindow(window2); --item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); // First app should be active again. EXPECT_EQ(ash::STATUS_ACTIVE, shelf_model()->ItemByID(item_id1)->status); // Close first app. CloseAppWindow(window1); --item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); } // Confirm that app windows can be reactivated by clicking their icons and that // the correct activation order is maintained. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, WindowActivation) { int item_count = shelf_model()->item_count(); // First run app. const Extension* extension1 = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow* window1 = CreateAppWindow(extension1); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item1 = GetLastLauncherItem(); ash::ShelfID item_id1 = item1.id; EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); // Then run second app. const Extension* extension2 = LoadAndLaunchPlatformApp("launch_2", "Launched"); AppWindow* window2 = CreateAppWindow(extension2); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item2 = GetLastLauncherItem(); ash::ShelfID item_id2 = item2.id; EXPECT_EQ(ash::TYPE_PLATFORM_APP, item2.type); EXPECT_EQ(ash::STATUS_ACTIVE, item2.status); EXPECT_NE(item_id1, item_id2); EXPECT_EQ(ash::STATUS_RUNNING, shelf_model()->ItemByID(item_id1)->status); // Activate first one. ActivateShelfItem(shelf_model()->ItemIndexByID(item_id1)); EXPECT_EQ(ash::STATUS_ACTIVE, shelf_model()->ItemByID(item_id1)->status); EXPECT_EQ(ash::STATUS_RUNNING, shelf_model()->ItemByID(item_id2)->status); EXPECT_TRUE(ash::wm::IsActiveWindow(window1->GetNativeWindow())); EXPECT_FALSE(ash::wm::IsActiveWindow(window2->GetNativeWindow())); // Activate second one. ActivateShelfItem(shelf_model()->ItemIndexByID(item_id2)); EXPECT_EQ(ash::STATUS_RUNNING, shelf_model()->ItemByID(item_id1)->status); EXPECT_EQ(ash::STATUS_ACTIVE, shelf_model()->ItemByID(item_id2)->status); EXPECT_FALSE(ash::wm::IsActiveWindow(window1->GetNativeWindow())); EXPECT_TRUE(ash::wm::IsActiveWindow(window2->GetNativeWindow())); // Add window for app1. This will activate it. AppWindow* window1b = CreateAppWindow(extension1); ash::wm::ActivateWindow(window1b->GetNativeWindow()); EXPECT_FALSE(ash::wm::IsActiveWindow(window1->GetNativeWindow())); EXPECT_FALSE(ash::wm::IsActiveWindow(window2->GetNativeWindow())); EXPECT_TRUE(ash::wm::IsActiveWindow(window1b->GetNativeWindow())); // Activate launcher item for app1, this will activate the first app window. ActivateShelfItem(shelf_model()->ItemIndexByID(item_id1)); EXPECT_TRUE(ash::wm::IsActiveWindow(window1->GetNativeWindow())); EXPECT_FALSE(ash::wm::IsActiveWindow(window1b->GetNativeWindow())); ActivateShelfItem(shelf_model()->ItemIndexByID(item_id1)); EXPECT_TRUE(ash::wm::IsActiveWindow(window1b->GetNativeWindow())); // Activate the second app again ActivateShelfItem(shelf_model()->ItemIndexByID(item_id2)); EXPECT_FALSE(ash::wm::IsActiveWindow(window1->GetNativeWindow())); EXPECT_TRUE(ash::wm::IsActiveWindow(window2->GetNativeWindow())); EXPECT_FALSE(ash::wm::IsActiveWindow(window1b->GetNativeWindow())); // Activate the first app again ActivateShelfItem(shelf_model()->ItemIndexByID(item_id1)); EXPECT_TRUE(ash::wm::IsActiveWindow(window1b->GetNativeWindow())); EXPECT_FALSE(ash::wm::IsActiveWindow(window2->GetNativeWindow())); EXPECT_FALSE(ash::wm::IsActiveWindow(window1->GetNativeWindow())); // Close second app. CloseAppWindow(window2); --item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); // First app should be active again. EXPECT_EQ(ash::STATUS_ACTIVE, shelf_model()->ItemByID(item_id1)->status); // Close first app. CloseAppWindow(window1b); CloseAppWindow(window1); --item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); } // Verify that ChromeLauncherController::CanInstall() returns true for ephemeral // apps and false when the app is promoted to a regular installed app. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, InstallEphemeralApp) { int item_count = shelf_model()->item_count(); // Sanity check to verify that ChromeLauncherController::CanInstall() returns // false for apps that are fully installed. const Extension* app = LoadAndLaunchPlatformApp("launch", "Launched"); ASSERT_TRUE(app); CreateAppWindow(app); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& app_item = GetLastLauncherItem(); ash::ShelfID app_id = app_item.id; EXPECT_FALSE(controller_->CanInstall(app_id)); // Add an ephemeral app. const Extension* ephemeral_app = InstallEphemeralAppWithSourceAndFlags( test_data_dir_.AppendASCII("platform_apps").AppendASCII("launch_2"), 1, extensions::Manifest::INTERNAL, Extension::NO_FLAGS); ASSERT_TRUE(ephemeral_app); CreateAppWindow(ephemeral_app); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& ephemeral_item = GetLastLauncherItem(); ash::ShelfID ephemeral_id = ephemeral_item.id; // Verify that the shelf item for the ephemeral app can be installed. EXPECT_TRUE(controller_->CanInstall(ephemeral_id)); // Promote the ephemeral app to a regular installed app. ExtensionService* service = extensions::ExtensionSystem::Get(profile())->extension_service(); service->PromoteEphemeralApp(ephemeral_app, false); // Verify that the shelf item for the app can no longer be installed. EXPECT_FALSE(controller_->CanInstall(ephemeral_id)); } // Confirm that Click behavior for app windows is correnct. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserNoMinimizeOnClick, AppClickBehavior) { // Launch a platform app and create a window for it. const Extension* extension1 = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow* window1 = CreateAppWindow(extension1); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); // Confirm that a controller item was created and is the correct state. const ash::ShelfItem& item1 = GetLastLauncherItem(); LauncherItemController* item1_controller = GetItemController(item1.id); EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); EXPECT_EQ(LauncherItemController::TYPE_APP, item1_controller->type()); // Clicking the item should have no effect. TestEvent click_event(ui::ET_MOUSE_PRESSED); item1_controller->ItemSelected(click_event); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); // Minimize the window and confirm that the controller item is updated. window1->GetBaseWindow()->Minimize(); EXPECT_FALSE(window1->GetNativeWindow()->IsVisible()); EXPECT_FALSE(window1->GetBaseWindow()->IsActive()); EXPECT_EQ(ash::STATUS_RUNNING, item1.status); // Clicking the item should activate the window. item1_controller->ItemSelected(click_event); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); // Maximizing a window should preserve state after minimize + click. window1->GetBaseWindow()->Maximize(); window1->GetBaseWindow()->Minimize(); item1_controller->ItemSelected(click_event); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); EXPECT_TRUE(window1->GetBaseWindow()->IsMaximized()); } // Confirm the minimizing click behavior for apps. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserMinimizeOnClick, PackagedAppClickBehaviorInMinimizeMode) { // Launch one platform app and create a window for it. const Extension* extension1 = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow* window1 = CreateAppWindow(extension1); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); // Confirm that a controller item was created and is the correct state. const ash::ShelfItem& item1 = GetLastLauncherItem(); LauncherItemController* item1_controller = GetItemController(item1.id); EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); EXPECT_EQ(LauncherItemController::TYPE_APP, item1_controller->type()); // Since it is already active, clicking it should minimize. TestEvent click_event(ui::ET_MOUSE_PRESSED); item1_controller->ItemSelected(click_event); EXPECT_FALSE(window1->GetNativeWindow()->IsVisible()); EXPECT_FALSE(window1->GetBaseWindow()->IsActive()); EXPECT_TRUE(window1->GetBaseWindow()->IsMinimized()); EXPECT_EQ(ash::STATUS_RUNNING, item1.status); // Clicking the item again should activate the window again. item1_controller->ItemSelected(click_event); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); // Maximizing a window should preserve state after minimize + click. window1->GetBaseWindow()->Maximize(); window1->GetBaseWindow()->Minimize(); item1_controller->ItemSelected(click_event); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); EXPECT_TRUE(window1->GetBaseWindow()->IsMaximized()); window1->GetBaseWindow()->Restore(); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); EXPECT_FALSE(window1->GetBaseWindow()->IsMaximized()); // Creating a second window of the same type should change the behavior so // that a click does not change the activation state. AppWindow* window1a = CreateAppWindow(extension1); EXPECT_TRUE(window1a->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1a->GetBaseWindow()->IsActive()); // The first click does nothing. item1_controller->ItemSelected(click_event); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1a->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); EXPECT_FALSE(window1a->GetBaseWindow()->IsActive()); // The second neither. item1_controller->ItemSelected(click_event); EXPECT_TRUE(window1->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1a->GetNativeWindow()->IsVisible()); EXPECT_TRUE(window1->GetBaseWindow()->IsActive()); EXPECT_FALSE(window1a->GetBaseWindow()->IsActive()); } // Confirm that click behavior for app panels is correct. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, AppPanelClickBehavior) { // Enable experimental APIs to allow panel creation. base::CommandLine::ForCurrentProcess()->AppendSwitch( extensions::switches::kEnableExperimentalExtensionApis); // Launch a platform app and create a panel window for it. const Extension* extension1 = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow::CreateParams params; params.window_type = AppWindow::WINDOW_TYPE_PANEL; params.focused = false; AppWindow* panel = CreateAppWindowFromParams(extension1, params); EXPECT_TRUE(panel->GetNativeWindow()->IsVisible()); // Panels should not be active by default. EXPECT_FALSE(panel->GetBaseWindow()->IsActive()); // Confirm that a controller item was created and is the correct state. const ash::ShelfItem& item1 = GetLastLauncherPanelItem(); LauncherItemController* item1_controller = GetItemController(item1.id); EXPECT_EQ(ash::TYPE_APP_PANEL, item1.type); EXPECT_EQ(ash::STATUS_RUNNING, item1.status); EXPECT_EQ(LauncherItemController::TYPE_APP_PANEL, item1_controller->type()); // Click the item and confirm that the panel is activated. TestEvent click_event(ui::ET_MOUSE_PRESSED); item1_controller->ItemSelected(click_event); EXPECT_TRUE(panel->GetBaseWindow()->IsActive()); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); // Click the item again and confirm that the panel is minimized. item1_controller->ItemSelected(click_event); EXPECT_TRUE(panel->GetBaseWindow()->IsMinimized()); EXPECT_EQ(ash::STATUS_RUNNING, item1.status); // Click the item again and confirm that the panel is activated. item1_controller->ItemSelected(click_event); EXPECT_TRUE(panel->GetNativeWindow()->IsVisible()); EXPECT_TRUE(panel->GetBaseWindow()->IsActive()); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); } IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, BrowserActivation) { int item_count = shelf_model()->item_count(); // First run app. const Extension* extension1 = LoadAndLaunchPlatformApp("launch", "Launched"); CreateAppWindow(extension1); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item1 = GetLastLauncherItem(); ash::ShelfID item_id1 = item1.id; EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); ash::wm::ActivateWindow(browser()->window()->GetNativeWindow()); EXPECT_EQ(ash::STATUS_RUNNING, shelf_model()->ItemByID(item_id1)->status); } // Test that opening an app sets the correct icon IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, SetIcon) { TestAppWindowRegistryObserver test_observer(browser()->profile()); // Enable experimental APIs to allow panel creation. base::CommandLine::ForCurrentProcess()->AppendSwitch( extensions::switches::kEnableExperimentalExtensionApis); int base_shelf_item_count = shelf_model()->item_count(); ExtensionTestMessageListener completed_listener("Completed", false); LoadAndLaunchPlatformApp("app_icon", "Launched"); ASSERT_TRUE(completed_listener.WaitUntilSatisfied()); // Now wait until the WebContent has decoded the icons and chrome has // processed it. This needs to be in a loop since the renderer runs in a // different process. while (test_observer.icon_updates() < 3) { base::RunLoop run_loop; run_loop.RunUntilIdle(); } // This test creates one app window and one panel window. int shelf_item_count = shelf_model()->item_count(); ASSERT_EQ(base_shelf_item_count + 2, shelf_item_count); // The Panel will be the last item, the app second-to-last. const ash::ShelfItem& app_item = shelf_model()->items()[shelf_item_count - 2]; const ash::ShelfItem& panel_item = shelf_model()->items()[shelf_item_count - 1]; const LauncherItemController* app_item_controller = GetItemController(app_item.id); const LauncherItemController* panel_item_controller = GetItemController(panel_item.id); // Icons for Apps are set by the AppWindowLauncherController, so // image_set_by_controller() should be set. EXPECT_TRUE(app_item_controller->image_set_by_controller()); EXPECT_TRUE(panel_item_controller->image_set_by_controller()); // Ensure icon heights are correct (see test.js in app_icon/ test directory) EXPECT_EQ(ash::kShelfSize, app_item.image.height()); EXPECT_EQ(64, panel_item.image.height()); } // Test that we can launch an app with a shortcut. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, LaunchPinned) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); ash::ShelfID shortcut_id = CreateShortcut("app1"); EXPECT_EQ(ash::STATUS_CLOSED, (*model_->ItemByID(shortcut_id)).status); ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(++tab_count, tab_strip->count()); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); WebContents* tab = tab_strip->GetActiveWebContents(); content::WebContentsDestroyedWatcher destroyed_watcher(tab); browser()->tab_strip_model()->CloseSelectedTabs(); destroyed_watcher.Wait(); EXPECT_EQ(--tab_count, tab_strip->count()); EXPECT_EQ(ash::STATUS_CLOSED, (*model_->ItemByID(shortcut_id)).status); } // Launch the app first and then create the shortcut. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, LaunchUnpinned) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); LoadAndLaunchExtension("app1", extensions::LAUNCH_CONTAINER_TAB, NEW_FOREGROUND_TAB); EXPECT_EQ(++tab_count, tab_strip->count()); ash::ShelfID shortcut_id = CreateShortcut("app1"); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); WebContents* tab = tab_strip->GetActiveWebContents(); content::WebContentsDestroyedWatcher destroyed_watcher(tab); browser()->tab_strip_model()->CloseSelectedTabs(); destroyed_watcher.Wait(); EXPECT_EQ(--tab_count, tab_strip->count()); EXPECT_EQ(ash::STATUS_CLOSED, (*model_->ItemByID(shortcut_id)).status); } // Launches an app in the background and then tries to open it. This is test for // a crash we had. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, LaunchInBackground) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); LoadAndLaunchExtension("app1", extensions::LAUNCH_CONTAINER_TAB, NEW_BACKGROUND_TAB); EXPECT_EQ(++tab_count, tab_strip->count()); ChromeLauncherController::instance()->LaunchApp(last_loaded_extension_id(), ash::LAUNCH_FROM_UNKNOWN, 0); } // Confirm that clicking a icon for an app running in one of 2 maxmized windows // activates the right window. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, LaunchMaximized) { aura::Window* window1 = browser()->window()->GetNativeWindow(); ash::wm::WindowState* window1_state = ash::wm::GetWindowState(window1); window1_state->Maximize(); content::WindowedNotificationObserver open_observer( chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::NotificationService::AllSources()); chrome::NewEmptyWindow(browser()->profile(), chrome::HOST_DESKTOP_TYPE_ASH); open_observer.Wait(); Browser* browser2 = content::Source<Browser>(open_observer.source()).ptr(); aura::Window* window2 = browser2->window()->GetNativeWindow(); TabStripModel* tab_strip = browser2->tab_strip_model(); int tab_count = tab_strip->count(); ash::wm::GetWindowState(window2)->Maximize(); ash::ShelfID shortcut_id = CreateShortcut("app1"); ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(++tab_count, tab_strip->count()); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); window1->Show(); window1_state->Activate(); EXPECT_EQ(ash::STATUS_RUNNING, (*model_->ItemByID(shortcut_id)).status); ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); } // Activating the same app multiple times should launch only a single copy. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, ActivateApp) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); const Extension* extension = LoadExtension(test_data_dir_.AppendASCII("app1")); ChromeLauncherController::instance()->ActivateApp(extension->id(), ash::LAUNCH_FROM_UNKNOWN, 0); EXPECT_EQ(++tab_count, tab_strip->count()); ChromeLauncherController::instance()->ActivateApp(extension->id(), ash::LAUNCH_FROM_UNKNOWN, 0); EXPECT_EQ(tab_count, tab_strip->count()); } // Launching the same app multiple times should launch a copy for each call. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, LaunchApp) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); const Extension* extension = LoadExtension(test_data_dir_.AppendASCII("app1")); ChromeLauncherController::instance()->LaunchApp(extension->id(), ash::LAUNCH_FROM_UNKNOWN, 0); EXPECT_EQ(++tab_count, tab_strip->count()); ChromeLauncherController::instance()->LaunchApp(extension->id(), ash::LAUNCH_FROM_UNKNOWN, 0); EXPECT_EQ(++tab_count, tab_strip->count()); } // Launch 2 apps and toggle which is active. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, MultipleApps) { int item_count = model_->item_count(); TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); ash::ShelfID shortcut1 = CreateShortcut("app1"); EXPECT_EQ(++item_count, model_->item_count()); ash::ShelfID shortcut2 = CreateShortcut("app2"); EXPECT_EQ(++item_count, model_->item_count()); // Launch first app. ActivateShelfItem(model_->ItemIndexByID(shortcut1)); EXPECT_EQ(++tab_count, tab_strip->count()); WebContents* tab1 = tab_strip->GetActiveWebContents(); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut1)).status); // Launch second app. ActivateShelfItem(model_->ItemIndexByID(shortcut2)); EXPECT_EQ(++tab_count, tab_strip->count()); WebContents* tab2 = tab_strip->GetActiveWebContents(); ASSERT_NE(tab1, tab2); EXPECT_EQ(ash::STATUS_RUNNING, (*model_->ItemByID(shortcut1)).status); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut2)).status); // Reactivate first app. ActivateShelfItem(model_->ItemIndexByID(shortcut1)); EXPECT_EQ(tab_count, tab_strip->count()); EXPECT_EQ(tab_strip->GetActiveWebContents(), tab1); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut1)).status); EXPECT_EQ(ash::STATUS_RUNNING, (*model_->ItemByID(shortcut2)).status); // Open second tab for second app. This should activate it. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example.com/path3/foo.html"), NEW_FOREGROUND_TAB, 0); EXPECT_EQ(++tab_count, tab_strip->count()); EXPECT_EQ(ash::STATUS_RUNNING, (*model_->ItemByID(shortcut1)).status); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut2)).status); // Reactivate first app. ActivateShelfItem(model_->ItemIndexByID(shortcut1)); EXPECT_EQ(tab_count, tab_strip->count()); EXPECT_EQ(tab_strip->GetActiveWebContents(), tab1); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut1)).status); EXPECT_EQ(ash::STATUS_RUNNING, (*model_->ItemByID(shortcut2)).status); // And second again. This time the second tab should become active. ActivateShelfItem(model_->ItemIndexByID(shortcut2)); EXPECT_EQ(tab_count, tab_strip->count()); EXPECT_EQ(tab_strip->GetActiveWebContents(), tab2); EXPECT_EQ(ash::STATUS_RUNNING, (*model_->ItemByID(shortcut1)).status); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut2)).status); } // Confirm that a page can be navigated from and to while maintaining the // correct running state. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, Navigation) { ash::ShelfID shortcut_id = CreateShortcut("app1"); EXPECT_EQ(ash::STATUS_CLOSED, (*model_->ItemByID(shortcut_id)).status); ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); // Navigate away. ui_test_utils::NavigateToURL( browser(), GURL("http://www.example.com/path0/bar.html")); EXPECT_EQ(ash::STATUS_CLOSED, (*model_->ItemByID(shortcut_id)).status); // Navigate back. ui_test_utils::NavigateToURL( browser(), GURL("http://www.example.com/path1/foo.html")); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); } // Confirm that a tab can be moved between browsers while maintaining the // correct running state. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, TabDragAndDrop) { TabStripModel* tab_strip_model1 = browser()->tab_strip_model(); EXPECT_EQ(1, tab_strip_model1->count()); int browser_index = GetIndexOfShelfItemType(ash::TYPE_BROWSER_SHORTCUT); EXPECT_TRUE(browser_index >= 0); EXPECT_EQ(1u, chrome::GetTotalBrowserCount()); // Create a shortcut for app1. ash::ShelfID shortcut_id = CreateShortcut("app1"); EXPECT_EQ(ash::STATUS_ACTIVE, model_->items()[browser_index].status); EXPECT_EQ(ash::STATUS_CLOSED, (*model_->ItemByID(shortcut_id)).status); // Activate app1 and check its item status. ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(2, tab_strip_model1->count()); EXPECT_EQ(ash::STATUS_RUNNING, model_->items()[browser_index].status); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); // Create a new browser with blank tab. Browser* browser2 = CreateBrowser(profile()); EXPECT_EQ(2u, chrome::GetTotalBrowserCount()); TabStripModel* tab_strip_model2 = browser2->tab_strip_model(); EXPECT_EQ(1, tab_strip_model2->count()); EXPECT_EQ(ash::STATUS_ACTIVE, model_->items()[browser_index].status); EXPECT_EQ(ash::STATUS_RUNNING, (*model_->ItemByID(shortcut_id)).status); // Detach a tab at index 1 (app1) from |tab_strip_model1| and insert it as an // active tab at index 1 to |tab_strip_model2|. content::WebContents* detached_tab = tab_strip_model1->DetachWebContentsAt(1); tab_strip_model2->InsertWebContentsAt(1, detached_tab, TabStripModel::ADD_ACTIVE); EXPECT_EQ(1, tab_strip_model1->count()); EXPECT_EQ(2, tab_strip_model2->count()); EXPECT_EQ(ash::STATUS_RUNNING, model_->items()[browser_index].status); EXPECT_EQ(ash::STATUS_ACTIVE, (*model_->ItemByID(shortcut_id)).status); tab_strip_model1->CloseAllTabs(); tab_strip_model2->CloseAllTabs(); } IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, MultipleOwnedTabs) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); ash::ShelfID shortcut_id = CreateShortcut("app1"); ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(++tab_count, tab_strip->count()); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); WebContents* first_tab = tab_strip->GetActiveWebContents(); // Create new tab owned by app. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example.com/path2/bar.html"), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(++tab_count, tab_strip->count()); // Confirm app is still active. EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); // Create new tab not owned by app. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example.com/path3/foo.html"), NEW_FOREGROUND_TAB, 0); EXPECT_EQ(++tab_count, tab_strip->count()); // No longer active. EXPECT_EQ(ash::STATUS_RUNNING, model_->ItemByID(shortcut_id)->status); // Activating app makes first tab active again. ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); EXPECT_EQ(tab_strip->GetActiveWebContents(), first_tab); } IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, RefocusFilter) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); ash::ShelfID shortcut_id = CreateShortcut("app1"); ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(++tab_count, tab_strip->count()); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); WebContents* first_tab = tab_strip->GetActiveWebContents(); controller_->SetRefocusURLPatternForTest( shortcut_id, GURL("http://www.example.com/path1/*")); // Create new tab owned by app. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example.com/path2/bar.html"), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(++tab_count, tab_strip->count()); // Confirm app is still active. EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); // Create new tab not owned by app. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example.com/path3/foo.html"), NEW_FOREGROUND_TAB, 0); EXPECT_EQ(++tab_count, tab_strip->count()); // No longer active. EXPECT_EQ(ash::STATUS_RUNNING, model_->ItemByID(shortcut_id)->status); // Activating app makes first tab active again, because second tab isn't // in its refocus url path. ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); EXPECT_EQ(tab_strip->GetActiveWebContents(), first_tab); } IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, RefocusFilterLaunch) { TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); ash::ShelfID shortcut_id = CreateShortcut("app1"); controller_->SetRefocusURLPatternForTest( shortcut_id, GURL("http://www.example.com/path1/*")); // Create new tab. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example2.com/path2/bar.html"), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(++tab_count, tab_strip->count()); WebContents* first_tab = tab_strip->GetActiveWebContents(); // Confirm app is not active. EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(shortcut_id)->status); // Activating app should launch new tab, because second tab isn't // in its refocus url path. ActivateShelfItem(model_->ItemIndexByID(shortcut_id)); EXPECT_EQ(++tab_count, tab_strip->count()); WebContents* second_tab = tab_strip->GetActiveWebContents(); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); EXPECT_NE(first_tab, second_tab); EXPECT_EQ(tab_strip->GetActiveWebContents(), second_tab); } // Check the launcher activation state for applications and browser. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, ActivationStateCheck) { TabStripModel* tab_strip = browser()->tab_strip_model(); // Get the browser item index int browser_index = GetIndexOfShelfItemType(ash::TYPE_BROWSER_SHORTCUT); EXPECT_TRUE(browser_index >= 0); // Even though we are just comming up, the browser should be active. EXPECT_EQ(ash::STATUS_ACTIVE, model_->items()[browser_index].status); ash::ShelfID shortcut_id = CreateShortcut("app1"); controller_->SetRefocusURLPatternForTest( shortcut_id, GURL("http://www.example.com/path1/*")); EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(shortcut_id)->status); EXPECT_EQ(ash::STATUS_ACTIVE, model_->items()[browser_index].status); // Create new tab which would be the running app. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example.com/path1/bar.html"), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // There should never be two items active at the same time. EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); EXPECT_EQ(ash::STATUS_RUNNING, model_->items()[browser_index].status); tab_strip->ActivateTabAt(0, false); EXPECT_EQ(ash::STATUS_RUNNING, model_->ItemByID(shortcut_id)->status); EXPECT_EQ(ash::STATUS_ACTIVE, model_->items()[browser_index].status); tab_strip->CloseWebContentsAt(1, TabStripModel::CLOSE_NONE); EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(shortcut_id)->status); EXPECT_EQ(ash::STATUS_ACTIVE, model_->items()[browser_index].status); ash::wm::DeactivateWindow(browser()->window()->GetNativeWindow()); EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(shortcut_id)->status); EXPECT_EQ(ash::STATUS_RUNNING, model_->items()[browser_index].status); } // Check that the launcher activation state for a V1 application stays closed // even after an asynchronous browser event comes in after the tab got // destroyed. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, AsyncActivationStateCheck) { TabStripModel* tab_strip = browser()->tab_strip_model(); ash::ShelfID shortcut_id = CreateShortcut("app1"); controller_->SetRefocusURLPatternForTest( shortcut_id, GURL("http://www.example.com/path1/*")); EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(shortcut_id)->status); // Create new tab which would be the running app. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.example.com/path1/bar.html"), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(shortcut_id)->status); // To address the issue of crbug.com/174050, the tab we are about to close // has to be active. tab_strip->ActivateTabAt(1, false); EXPECT_EQ(1, tab_strip->active_index()); // Close the web contents. tab_strip->CloseWebContentsAt(1, TabStripModel::CLOSE_NONE); // The status should now be set to closed. EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(shortcut_id)->status); } // Checks that a windowed application does not add an item to the browser list. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTestNoDefaultBrowser, WindowedAppDoesNotAddToBrowser) { // Get the number of items in the browser menu. size_t items = NumberOfDetectedLauncherBrowsers(false); size_t running_browser = chrome::GetTotalBrowserCount(); EXPECT_EQ(0u, items); EXPECT_EQ(0u, running_browser); LoadAndLaunchExtension( "app1", extensions::LAUNCH_CONTAINER_WINDOW, NEW_WINDOW); // No new browser should get detected, even though one more is running. EXPECT_EQ(0u, NumberOfDetectedLauncherBrowsers(false)); EXPECT_EQ(++running_browser, chrome::GetTotalBrowserCount()); LoadAndLaunchExtension("app1", extensions::LAUNCH_CONTAINER_TAB, NEW_WINDOW); // A new browser should get detected and one more should be running. EXPECT_EQ(NumberOfDetectedLauncherBrowsers(false), 1u); EXPECT_EQ(++running_browser, chrome::GetTotalBrowserCount()); } // Checks the functionality to enumerate all browsers vs. all tabs. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTestNoDefaultBrowser, EnumerateALlBrowsersAndTabs) { // Create at least one browser. LoadAndLaunchExtension("app1", extensions::LAUNCH_CONTAINER_TAB, NEW_WINDOW); size_t browsers = NumberOfDetectedLauncherBrowsers(false); size_t tabs = NumberOfDetectedLauncherBrowsers(true); // Create a second browser. LoadAndLaunchExtension("app1", extensions::LAUNCH_CONTAINER_TAB, NEW_WINDOW); EXPECT_EQ(++browsers, NumberOfDetectedLauncherBrowsers(false)); EXPECT_EQ(++tabs, NumberOfDetectedLauncherBrowsers(true)); // Create only a tab. LoadAndLaunchExtension("app1", extensions::LAUNCH_CONTAINER_TAB, NEW_FOREGROUND_TAB); EXPECT_EQ(browsers, NumberOfDetectedLauncherBrowsers(false)); EXPECT_EQ(++tabs, NumberOfDetectedLauncherBrowsers(true)); } // Check that the keyboard activation of a launcher item tabs properly through // the items at hand. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, AltNumberTabsTabbing) { TabStripModel* tab_strip = browser()->tab_strip_model(); ash::ShelfID shortcut_id = CreateShortcut("app"); controller_->SetRefocusURLPatternForTest( shortcut_id, GURL("http://www.example.com/path/*")); std::string url = "http://www.example.com/path/bla"; int shortcut_index = model_->ItemIndexByID(shortcut_id); // Create an application handled browser tab. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(url), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); content::WebContents* content1 = tab_strip->GetActiveWebContents(); // Create some other browser tab. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("http://www.test.com"), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); content::WebContents* content1a = tab_strip->GetActiveWebContents(); // Make sure that the active tab is now our handled tab. EXPECT_NE(content1a, content1); // The active tab should still be the unnamed tab. Then we switch and reach // the first app and stay there. EXPECT_EQ(content1a, tab_strip->GetActiveWebContents()); ActivateShelfItem(shortcut_index); EXPECT_EQ(content1, tab_strip->GetActiveWebContents()); ActivateShelfItem(shortcut_index); EXPECT_EQ(content1, tab_strip->GetActiveWebContents()); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(url), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); content::WebContents* content2 = tab_strip->GetActiveWebContents(); EXPECT_EQ(content2, browser()->tab_strip_model()->GetActiveWebContents()); ActivateShelfItem(shortcut_index); EXPECT_EQ(content1, browser()->tab_strip_model()->GetActiveWebContents()); ActivateShelfItem(shortcut_index); EXPECT_EQ(content2, browser()->tab_strip_model()->GetActiveWebContents()); } // Check that the keyboard activation of a launcher item tabs properly through // the items at hand. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, AltNumberAppsTabbing) { // First run app. const Extension* extension1 = LoadAndLaunchPlatformApp("launch", "Launched"); ui::BaseWindow* window1 = CreateAppWindow(extension1)->GetBaseWindow(); const ash::ShelfItem& item1 = GetLastLauncherItem(); ash::ShelfID app_id = item1.id; int app_index = shelf_model()->ItemIndexByID(app_id); EXPECT_EQ(ash::TYPE_PLATFORM_APP, item1.type); EXPECT_EQ(ash::STATUS_ACTIVE, item1.status); const Extension* extension2 = LoadAndLaunchPlatformApp("launch_2", "Launched"); ui::BaseWindow* window2 = CreateAppWindow(extension2)->GetBaseWindow(); // By now the browser should be active. Issue Alt keystrokes several times to // see that we stay on that application. EXPECT_TRUE(window2->IsActive()); ActivateShelfItem(app_index); EXPECT_TRUE(window1->IsActive()); ActivateShelfItem(app_index); EXPECT_TRUE(window1->IsActive()); ui::BaseWindow* window1a = CreateAppWindow(extension1)->GetBaseWindow(); EXPECT_TRUE(window1a->IsActive()); EXPECT_FALSE(window1->IsActive()); ActivateShelfItem(app_index); EXPECT_TRUE(window1->IsActive()); ActivateShelfItem(app_index); EXPECT_TRUE(window1a->IsActive()); } // Test that we can launch a platform app panel and get a running item. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, LaunchPanelWindow) { int item_count = shelf_model()->item_count(); const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow::CreateParams params; params.window_type = AppWindow::WINDOW_TYPE_PANEL; params.focused = false; AppWindow* window = CreateAppWindowFromParams(extension, params); ++item_count; ASSERT_EQ(item_count, shelf_model()->item_count()); const ash::ShelfItem& item = GetLastLauncherPanelItem(); EXPECT_EQ(ash::TYPE_APP_PANEL, item.type); // Opening a panel does not activate it. EXPECT_EQ(ash::STATUS_RUNNING, item.status); CloseAppWindow(window); --item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); } // Test that we get correct shelf presence with hidden app windows. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, HiddenAppWindows) { int item_count = shelf_model()->item_count(); const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow::CreateParams params; // Create a hidden window. params.hidden = true; AppWindow* window_1 = CreateAppWindowFromParams(extension, params); EXPECT_EQ(item_count, shelf_model()->item_count()); // Create a visible window. params.hidden = false; AppWindow* window_2 = CreateAppWindowFromParams(extension, params); ++item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); // Minimize the visible window. window_2->Minimize(); EXPECT_EQ(item_count, shelf_model()->item_count()); // Hide the visible window. window_2->Hide(); --item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); // Show the originally hidden window. window_1->Show(AppWindow::SHOW_ACTIVE); ++item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); // Close the originally hidden window. CloseAppWindow(window_1); --item_count; EXPECT_EQ(item_count, shelf_model()->item_count()); } // Test attention states of windows. IN_PROC_BROWSER_TEST_F(LauncherPlatformAppBrowserTest, WindowAttentionStatus) { const Extension* extension = LoadAndLaunchPlatformApp("launch", "Launched"); AppWindow::CreateParams params; params.window_type = AppWindow::WINDOW_TYPE_PANEL; params.focused = false; AppWindow* panel = CreateAppWindowFromParams(extension, params); EXPECT_TRUE(panel->GetNativeWindow()->IsVisible()); // Panels should not be active by default. EXPECT_FALSE(panel->GetBaseWindow()->IsActive()); // Confirm that a controller item was created and is the correct state. const ash::ShelfItem& item = GetLastLauncherPanelItem(); LauncherItemController* item_controller = GetItemController(item.id); EXPECT_EQ(ash::TYPE_APP_PANEL, item.type); EXPECT_EQ(ash::STATUS_RUNNING, item.status); EXPECT_EQ(LauncherItemController::TYPE_APP_PANEL, item_controller->type()); // App windows should go to attention state. panel->GetNativeWindow()->SetProperty(aura::client::kDrawAttentionKey, true); EXPECT_EQ(ash::STATUS_ATTENTION, item.status); // Click the item and confirm that the panel is activated. TestEvent click_event(ui::ET_MOUSE_PRESSED); item_controller->ItemSelected(click_event); EXPECT_TRUE(panel->GetBaseWindow()->IsActive()); EXPECT_EQ(ash::STATUS_ACTIVE, item.status); // Active windows don't show attention. panel->GetNativeWindow()->SetProperty(aura::client::kDrawAttentionKey, true); EXPECT_EQ(ash::STATUS_ACTIVE, item.status); } // Checks that the browser Alt "tabbing" is properly done. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTestNoDefaultBrowser, AltNumberBrowserTabbing) { // Get the number of items in the browser menu. EXPECT_EQ(0u, chrome::GetTotalBrowserCount()); // The first activation should create a browser at index 1 (App List @ 0). shelf_->ActivateShelfItem(1); EXPECT_EQ(1u, chrome::GetTotalBrowserCount()); // A second activation should not create a new instance. shelf_->ActivateShelfItem(1); Browser* browser1 = chrome::FindBrowserWithWindow(ash::wm::GetActiveWindow()); EXPECT_TRUE(browser1); aura::Window* window1 = browser1->window()->GetNativeWindow(); Browser* browser2 = CreateBrowser(profile()); aura::Window* window2 = browser2->window()->GetNativeWindow(); EXPECT_EQ(2u, chrome::GetTotalBrowserCount()); EXPECT_NE(window1, window2); EXPECT_EQ(window2, ash::wm::GetActiveWindow()); // Activate multiple times the switcher to see that the windows get activated. shelf_->ActivateShelfItem(1); EXPECT_EQ(window1, ash::wm::GetActiveWindow()); shelf_->ActivateShelfItem(1); EXPECT_EQ(window2, ash::wm::GetActiveWindow()); // Create a third browser - make sure that we do not toggle simply between // two windows. Browser* browser3 = CreateBrowser(profile()); aura::Window* window3 = browser3->window()->GetNativeWindow(); EXPECT_EQ(3u, chrome::GetTotalBrowserCount()); EXPECT_NE(window1, window3); EXPECT_NE(window2, window3); EXPECT_EQ(window3, ash::wm::GetActiveWindow()); shelf_->ActivateShelfItem(1); EXPECT_EQ(window1, ash::wm::GetActiveWindow()); shelf_->ActivateShelfItem(1); EXPECT_EQ(window2, ash::wm::GetActiveWindow()); shelf_->ActivateShelfItem(1); EXPECT_EQ(window3, ash::wm::GetActiveWindow()); shelf_->ActivateShelfItem(1); EXPECT_EQ(window1, ash::wm::GetActiveWindow()); // Create anther app and make sure that none of our browsers is active. LoadAndLaunchExtension("app1", extensions::LAUNCH_CONTAINER_TAB, NEW_WINDOW); EXPECT_NE(window1, ash::wm::GetActiveWindow()); EXPECT_NE(window2, ash::wm::GetActiveWindow()); // After activation our browser should be active again. shelf_->ActivateShelfItem(1); EXPECT_EQ(window1, ash::wm::GetActiveWindow()); } // Checks that after a session restore, we do not start applications on an // activation. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, ActivateAfterSessionRestore) { EXPECT_EQ(1u, chrome::GetTotalBrowserCount()); // Create a known application. ash::ShelfID shortcut_id = CreateShortcut("app1"); // Create a new browser - without activating it - and load an "app" into it. Browser::CreateParams params = Browser::CreateParams(profile(), chrome::GetActiveDesktop()); params.initial_show_state = ui::SHOW_STATE_INACTIVE; Browser* browser2 = new Browser(params); controller_->SetRefocusURLPatternForTest( shortcut_id, GURL("http://www.example.com/path/*")); std::string url = "http://www.example.com/path/bla"; ui_test_utils::NavigateToURLWithDisposition( browser2, GURL(url), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Remember the number of tabs for each browser. TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count1 = tab_strip->count(); TabStripModel* tab_strip2 = browser2->tab_strip_model(); int tab_count2 = tab_strip2->count(); // Check that we have two browsers and the inactive browser remained inactive. EXPECT_EQ(2u, chrome::GetTotalBrowserCount()); EXPECT_EQ(chrome::FindBrowserWithWindow(ash::wm::GetActiveWindow()), browser()); // Check that the LRU browser list does only contain the original browser. BrowserList* ash_browser_list = BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH); BrowserList::const_reverse_iterator it = ash_browser_list->begin_last_active(); EXPECT_EQ(*it, browser()); ++it; EXPECT_EQ(it, ash_browser_list->end_last_active()); // Now request to either activate an existing app or create a new one. LauncherItemController* item_controller = controller_->GetLauncherItemController(shortcut_id); item_controller->ItemSelected(ui::KeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_RETURN, ui::EF_NONE)); // Check that we have set focus on the existing application and nothing new // was created. EXPECT_EQ(2u, chrome::GetTotalBrowserCount()); EXPECT_EQ(tab_count1, tab_strip->count()); EXPECT_EQ(tab_count2, tab_strip2->count()); EXPECT_EQ(chrome::FindBrowserWithWindow(ash::wm::GetActiveWindow()), browser2); } // Do various drag and drop interaction tests between the application list and // the launcher. // TODO(skuhne): Test is flaky with a real compositor: crbug.com/331924 IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, DISABLED_DragAndDrop) { // Get a number of interfaces we need. ui::test::EventGenerator generator(ash::Shell::GetPrimaryRootWindow(), gfx::Point()); ash::test::ShelfViewTestAPI test( ash::test::ShelfTestAPI(shelf_).shelf_view()); AppListService* service = AppListService::Get(chrome::GetActiveDesktop()); // There should be two items in our launcher by this time. EXPECT_EQ(2, model_->item_count()); EXPECT_FALSE(service->IsAppListVisible()); // Open the app list menu and check that the drag and drop host was set. gfx::Rect app_list_bounds = test.shelf_view()->GetAppListButtonView()->GetBoundsInScreen(); generator.MoveMouseTo(app_list_bounds.CenterPoint().x(), app_list_bounds.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); generator.ClickLeftButton(); EXPECT_TRUE(service->IsAppListVisible()); app_list::AppsGridView* grid_view = ash::test::AppListControllerTestApi(ash::Shell::GetInstance()). GetRootGridView(); ASSERT_TRUE(grid_view); ASSERT_TRUE(grid_view->has_drag_and_drop_host_for_test()); // There should be 2 items in our application list. const views::ViewModelT<app_list::AppListItemView>* vm_grid = grid_view->view_model_for_test(); EXPECT_EQ(2, vm_grid->view_size()); // Test #1: Drag an app list which does not exist yet item into the // launcher. Keeping it dragged, see that a new item gets created. Continuing // to drag it out should remove it again. // Get over item #1 of the application list and press the mouse button. views::View* item1 = vm_grid->view_at(1); gfx::Rect bounds_grid_1 = item1->GetBoundsInScreen(); generator.MoveMouseTo(bounds_grid_1.CenterPoint().x(), bounds_grid_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); generator.PressLeftButton(); EXPECT_FALSE(grid_view->forward_events_to_drag_and_drop_host_for_test()); // Drag the item into the shelf and check that a new item gets created. const views::ViewModel* vm_shelf = test.shelf_view()->view_model_for_test(); views::View* shelf1 = vm_shelf->view_at(1); gfx::Rect bounds_shelf_1 = shelf1->GetBoundsInScreen(); generator.MoveMouseTo(bounds_shelf_1.CenterPoint().x(), bounds_shelf_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); // Check that a new item got created. EXPECT_EQ(3, model_->item_count()); EXPECT_TRUE(grid_view->forward_events_to_drag_and_drop_host_for_test()); // Move it where the item originally was and check that it disappears again. generator.MoveMouseTo(bounds_grid_1.CenterPoint().x(), bounds_grid_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(2, model_->item_count()); EXPECT_FALSE(grid_view->forward_events_to_drag_and_drop_host_for_test()); // Dropping it should keep the launcher as it originally was. generator.ReleaseLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(2, model_->item_count()); // There are a few animations which need finishing before we can continue. test.RunMessageLoopUntilAnimationsDone(); // Move the mouse outside of the launcher. generator.MoveMouseTo(0, 0); // Test #2: Check that the unknown item dropped into the launcher will // create a new item. generator.MoveMouseTo(bounds_grid_1.CenterPoint().x(), bounds_grid_1.CenterPoint().y()); generator.PressLeftButton(); generator.MoveMouseTo(bounds_shelf_1.CenterPoint().x(), bounds_shelf_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(3, model_->item_count()); EXPECT_TRUE(grid_view->forward_events_to_drag_and_drop_host_for_test()); generator.ReleaseLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_FALSE(grid_view->forward_events_to_drag_and_drop_host_for_test()); EXPECT_EQ(3, model_->item_count()); // It should be still there. test.RunMessageLoopUntilAnimationsDone(); // Test #3: Check that the now known item dropped into the launcher will // not create a new item. generator.MoveMouseTo(bounds_grid_1.CenterPoint().x(), bounds_grid_1.CenterPoint().y()); generator.PressLeftButton(); generator.MoveMouseTo(bounds_shelf_1.CenterPoint().x(), bounds_shelf_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(3, model_->item_count()); // No new item got added. EXPECT_TRUE(grid_view->forward_events_to_drag_and_drop_host_for_test()); generator.ReleaseLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_FALSE(grid_view->forward_events_to_drag_and_drop_host_for_test()); EXPECT_EQ(3, model_->item_count()); // And it remains that way. // Test #4: Check that by pressing ESC the operation gets cancelled. generator.MoveMouseTo(bounds_grid_1.CenterPoint().x(), bounds_grid_1.CenterPoint().y()); generator.PressLeftButton(); generator.MoveMouseTo(bounds_shelf_1.CenterPoint().x(), bounds_shelf_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); // Issue an ESC and see that the operation gets cancelled. generator.PressKey(ui::VKEY_ESCAPE, 0); generator.ReleaseKey(ui::VKEY_ESCAPE, 0); EXPECT_FALSE(grid_view->dragging()); EXPECT_FALSE(grid_view->has_dragged_view()); generator.ReleaseLeftButton(); } #if !defined(OS_WIN) // Used to test drag & drop an item between app list and shelf with multi // display environment. class ShelfAppBrowserTestWithMultiMonitor : public ShelfAppBrowserTestNoDefaultBrowser { protected: ShelfAppBrowserTestWithMultiMonitor() {} ~ShelfAppBrowserTestWithMultiMonitor() override {} void SetUpCommandLine(base::CommandLine* command_line) override { ShelfAppBrowserTestNoDefaultBrowser::SetUpCommandLine(command_line); command_line->AppendSwitchASCII("ash-host-window-bounds", "800x800,801+0-800x800"); } private: DISALLOW_COPY_AND_ASSIGN(ShelfAppBrowserTestWithMultiMonitor); }; // Do basic drag and drop interaction tests between the application list and // the launcher in the secondary monitor. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTestWithMultiMonitor, BasicDragAndDrop) { // Get a number of interfaces we need. DCHECK_EQ(ash::Shell::GetAllRootWindows().size(), 2U); aura::Window* secondary_root_window = ash::Shell::GetAllRootWindows()[1]; ash::Shelf* secondary_shelf = ash::Shelf::ForWindow(secondary_root_window); ui::test::EventGenerator generator(secondary_root_window, gfx::Point()); ash::test::ShelfViewTestAPI test( ash::test::ShelfTestAPI(secondary_shelf).shelf_view()); AppListService* service = AppListService::Get(chrome::GetActiveDesktop()); // There should be two items in our shelf by this time. EXPECT_EQ(2, model_->item_count()); EXPECT_FALSE(service->IsAppListVisible()); // Open the app list menu and check that the drag and drop host was set. gfx::Rect app_list_bounds = test.shelf_view()->GetAppListButtonView()->GetBoundsInScreen(); gfx::Display display = ash::Shell::GetScreen()->GetDisplayNearestWindow(secondary_root_window); const gfx::Point& origin = display.bounds().origin(); app_list_bounds.Offset(-origin.x(), -origin.y()); generator.MoveMouseTo(app_list_bounds.CenterPoint().x(), app_list_bounds.CenterPoint().y()); generator.ClickLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_TRUE(service->IsAppListVisible()); // Click the "all apps" button on the start page. ClickAllAppsButtonFromStartPage(&generator, origin); EXPECT_TRUE(service->IsAppListVisible()); app_list::AppsGridView* grid_view = ash::test::AppListControllerTestApi(ash::Shell::GetInstance()). GetRootGridView(); ASSERT_TRUE(grid_view); ASSERT_TRUE(grid_view->has_drag_and_drop_host_for_test()); // There should be 2 items in our application list. const views::ViewModelT<app_list::AppListItemView>* vm_grid = grid_view->view_model_for_test(); EXPECT_EQ(2, vm_grid->view_size()); // Drag an app list item which does not exist yet in the shelf. // Keeping it dragged, see that a new item gets created. // Continuing to drag it out should remove it again. // Get over item #1 of the application list and press the mouse button. views::View* item1 = vm_grid->view_at(1); gfx::Rect bounds_grid_1 = item1->GetBoundsInScreen(); bounds_grid_1.Offset(-origin.x(), -origin.y()); generator.MoveMouseTo(bounds_grid_1.CenterPoint().x(), bounds_grid_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); generator.PressLeftButton(); EXPECT_FALSE(grid_view->forward_events_to_drag_and_drop_host_for_test()); // Drag the item into the shelf and check that a new item gets created. const views::ViewModel* vm_shelf = test.shelf_view()->view_model_for_test(); views::View* shelf1 = vm_shelf->view_at(1); gfx::Rect bounds_shelf_1 = shelf1->GetBoundsInScreen(); bounds_shelf_1.Offset(-origin.x(), -origin.y()); generator.MoveMouseTo(bounds_shelf_1.CenterPoint().x(), bounds_shelf_1.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); // Check that a new item got created. EXPECT_EQ(3, model_->item_count()); EXPECT_TRUE(grid_view->forward_events_to_drag_and_drop_host_for_test()); // Move it to an empty slot on grid_view. gfx::Rect empty_slot_rect = bounds_grid_1; empty_slot_rect.Offset(0, grid_view->GetTotalTileSize().height()); generator.MoveMouseTo(empty_slot_rect.CenterPoint().x(), empty_slot_rect.CenterPoint().y()); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(2, model_->item_count()); EXPECT_FALSE(grid_view->forward_events_to_drag_and_drop_host_for_test()); // Dropping it should keep the shelf as it originally was. generator.ReleaseLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(2, model_->item_count()); } #endif // Do tests for removal of items from the shelf by dragging. // Disabled due to flake: http://crbug.com/448482 IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, DISABLED_DragOffShelf) { ui::test::EventGenerator generator(ash::Shell::GetPrimaryRootWindow(), gfx::Point()); ash::test::ShelfViewTestAPI test( ash::test::ShelfTestAPI(shelf_).shelf_view()); test.SetAnimationDuration(1); // Speed up animations for test. // Create a known application and check that we have 3 items in the shelf. CreateShortcut("app1"); test.RunMessageLoopUntilAnimationsDone(); EXPECT_EQ(3, model_->item_count()); // Test #1: Ripping out the browser item should not change anything. int browser_index = GetIndexOfShelfItemType(ash::TYPE_BROWSER_SHORTCUT); EXPECT_LE(0, browser_index); RipOffItemIndex(browser_index, &generator, &test, RIP_OFF_ITEM); // => It should not have been removed and the location should be unchanged. EXPECT_EQ(3, model_->item_count()); EXPECT_EQ(browser_index, GetIndexOfShelfItemType(ash::TYPE_BROWSER_SHORTCUT)); // Make sure that the hide state has been unset after the snap back animation // finished. ash::ShelfButton* button = test.GetButton(browser_index); EXPECT_FALSE(button->state() & ash::ShelfButton::STATE_HIDDEN); // Test #2: Ripping out the application and canceling the operation should // not change anything. int app_index = GetIndexOfShelfItemType(ash::TYPE_APP_SHORTCUT); EXPECT_LE(0, app_index); RipOffItemIndex(app_index, &generator, &test, RIP_OFF_ITEM_AND_CANCEL); // => It should not have been removed and the location should be unchanged. ASSERT_EQ(3, model_->item_count()); EXPECT_EQ(app_index, GetIndexOfShelfItemType(ash::TYPE_APP_SHORTCUT)); // Test #3: Ripping out the application and moving it back in should not // change anything. RipOffItemIndex(app_index, &generator, &test, RIP_OFF_ITEM_AND_RETURN); // => It should not have been removed and the location should be unchanged. ASSERT_EQ(3, model_->item_count()); // Through the operation the index might have changed. app_index = GetIndexOfShelfItemType(ash::TYPE_APP_SHORTCUT); // Test #4: Ripping out the application should remove the item. RipOffItemIndex(app_index, &generator, &test, RIP_OFF_ITEM); // => It should not have been removed and the location should be unchanged. EXPECT_EQ(2, model_->item_count()); EXPECT_EQ(-1, GetIndexOfShelfItemType(ash::TYPE_APP_SHORTCUT)); // Test #5: Uninstalling an application while it is being ripped off should // not crash. ash::ShelfID app_id = CreateShortcut("app2"); test.RunMessageLoopUntilAnimationsDone(); int app2_index = GetIndexOfShelfItemType(ash::TYPE_APP_SHORTCUT); EXPECT_EQ(3, model_->item_count()); // And it remains that way. RipOffItemIndex(app2_index, &generator, &test, RIP_OFF_ITEM_AND_DONT_RELEASE_MOUSE); RemoveShortcut(app_id); test.RunMessageLoopUntilAnimationsDone(); EXPECT_EQ(2, model_->item_count()); // The item should now be gone. generator.ReleaseLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(2, model_->item_count()); // And it remains that way. EXPECT_EQ(-1, GetIndexOfShelfItemType(ash::TYPE_APP_SHORTCUT)); // Test #6: Ripping out the application when the overflow button exists. // After ripping out, overflow button should be removed. int items_added = 0; EXPECT_FALSE(test.IsOverflowButtonVisible()); // Create fake app shortcuts until overflow button is created. while (!test.IsOverflowButtonVisible()) { std::string fake_app_id = base::StringPrintf("fake_app_%d", items_added); PinFakeApp(fake_app_id); test.RunMessageLoopUntilAnimationsDone(); ++items_added; ASSERT_LT(items_added, 10000); } // Make one more item after creating a overflow button. std::string fake_app_id = base::StringPrintf("fake_app_%d", items_added); PinFakeApp(fake_app_id); test.RunMessageLoopUntilAnimationsDone(); int total_count = model_->item_count(); app_index = GetIndexOfShelfItemType(ash::TYPE_APP_SHORTCUT); RipOffItemIndex(app_index, &generator, &test, RIP_OFF_ITEM); // When an item is ripped off from the shelf that has overflow button // (see crbug.com/3050787), it was hidden accidentally and was then // suppressing any further events. If handled correctly the operation will // however correctly done and the item will get removed (as well as the // overflow button). EXPECT_EQ(total_count - 1, model_->item_count()); EXPECT_TRUE(test.IsOverflowButtonVisible()); // Rip off again and the overflow button should has disappeared. RipOffItemIndex(app_index, &generator, &test, RIP_OFF_ITEM); EXPECT_EQ(total_count - 2, model_->item_count()); EXPECT_FALSE(test.IsOverflowButtonVisible()); } // Check that clicking on an app shelf item launches a new browser. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, ClickItem) { // Get a number of interfaces we need. ui::test::EventGenerator generator(ash::Shell::GetPrimaryRootWindow(), gfx::Point()); ash::test::ShelfViewTestAPI test( ash::test::ShelfTestAPI(shelf_).shelf_view()); AppListService* service = AppListService::Get(chrome::GetActiveDesktop()); // There should be two items in our shelf by this time. EXPECT_EQ(2, model_->item_count()); EXPECT_FALSE(service->IsAppListVisible()); // Open the app list menu and check that the drag and drop host was set. gfx::Rect app_list_bounds = test.shelf_view()->GetAppListButtonView()->GetBoundsInScreen(); generator.MoveMouseTo(app_list_bounds.CenterPoint().x(), app_list_bounds.CenterPoint().y()); generator.ClickLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_TRUE(service->IsAppListVisible()); // Click the "all apps" button on the start page. ClickAllAppsButtonFromStartPage(&generator, gfx::Point()); EXPECT_TRUE(service->IsAppListVisible()); // Click an app icon in the app grid view. app_list::AppsGridView* grid_view = ash::test::AppListControllerTestApi(ash::Shell::GetInstance()). GetRootGridView(); ASSERT_TRUE(grid_view); const views::ViewModelT<app_list::AppListItemView>* vm_grid = grid_view->view_model_for_test(); EXPECT_EQ(2, vm_grid->view_size()); gfx::Rect bounds_grid_1 = vm_grid->view_at(1)->GetBoundsInScreen(); // Test now that a click does create a new application tab. TabStripModel* tab_strip = browser()->tab_strip_model(); int tab_count = tab_strip->count(); generator.MoveMouseTo(bounds_grid_1.CenterPoint().x(), bounds_grid_1.CenterPoint().y()); generator.ClickLeftButton(); base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(tab_count + 1, tab_strip->count()); } // Check LauncherItemController of Browser Shortcut functionality. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTestNoDefaultBrowser, BrowserShortcutLauncherItemController) { LauncherItemController* item_controller = controller_->GetBrowserShortcutLauncherItemController(); // Get the number of browsers. size_t running_browser = chrome::GetTotalBrowserCount(); EXPECT_EQ(0u, running_browser); EXPECT_FALSE(item_controller->IsOpen()); // Activate. This creates new browser item_controller->Activate(ash::LAUNCH_FROM_UNKNOWN); // New Window is created. running_browser = chrome::GetTotalBrowserCount(); EXPECT_EQ(1u, running_browser); EXPECT_TRUE(item_controller->IsOpen()); // Minimize Window. ash::wm::WindowState* window_state = ash::wm::GetActiveWindowState(); window_state->Minimize(); EXPECT_TRUE(window_state->IsMinimized()); // Activate again. This doesn't create new browser. // It activates window. item_controller->Activate(ash::LAUNCH_FROM_UNKNOWN); running_browser = chrome::GetTotalBrowserCount(); EXPECT_EQ(1u, running_browser); EXPECT_TRUE(item_controller->IsOpen()); EXPECT_FALSE(window_state->IsMinimized()); } // Check that GetShelfIDForWindow() returns |ShelfID| of the active tab. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, MatchingShelfIDandActiveTab) { EXPECT_EQ(1u, chrome::GetTotalBrowserCount()); EXPECT_EQ(1, browser()->tab_strip_model()->count()); EXPECT_EQ(0, browser()->tab_strip_model()->active_index()); EXPECT_EQ(2, model_->item_count()); aura::Window* window = browser()->window()->GetNativeWindow(); int browser_index = GetIndexOfShelfItemType(ash::TYPE_BROWSER_SHORTCUT); ash::ShelfID browser_id = model_->items()[browser_index].id; EXPECT_EQ(browser_id, ash::GetShelfIDForWindow(window)); ash::ShelfID app_id = CreateShortcut("app1"); EXPECT_EQ(3, model_->item_count()); // Creates a new tab for "app1" and checks that GetShelfIDForWindow() // returns |ShelfID| of "app1". ActivateShelfItem(model_->ItemIndexByID(app_id)); EXPECT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(1, browser()->tab_strip_model()->active_index()); EXPECT_EQ(app_id, ash::GetShelfIDForWindow(window)); // Makes tab at index 0(NTP) as an active tab and checks that // GetShelfIDForWindow() returns |ShelfID| of browser shortcut. browser()->tab_strip_model()->ActivateTabAt(0, false); EXPECT_EQ(0, browser()->tab_strip_model()->active_index()); EXPECT_EQ(browser_id, ash::GetShelfIDForWindow(window)); } IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, OverflowBubble) { // Make sure to have a browser window chrome::NewTab(browser()); // No overflow yet. EXPECT_FALSE(shelf_->IsShowingOverflowBubble()); ash::test::ShelfViewTestAPI test( ash::test::ShelfTestAPI(shelf_).shelf_view()); int items_added = 0; while (!test.IsOverflowButtonVisible()) { std::string fake_app_id = base::StringPrintf("fake_app_%d", items_added); PinFakeApp(fake_app_id); ++items_added; ASSERT_LT(items_added, 10000); } // Now show overflow bubble. test.ShowOverflowBubble(); EXPECT_TRUE(shelf_->IsShowingOverflowBubble()); // Unpin first pinned app and there should be no crash. controller_->UnpinAppWithID(std::string("fake_app_0")); test.RunMessageLoopUntilAnimationsDone(); EXPECT_FALSE(shelf_->IsShowingOverflowBubble()); } // Check that a windowed V1 application can navigate away from its domain, but // still gets detected properly. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, V1AppNavigation) { // We assume that the web store is always there (which it apparently is). controller_->PinAppWithID(extensions::kWebStoreAppId); ash::ShelfID id = controller_->GetShelfIDForAppID( extensions::kWebStoreAppId); ASSERT_NE(0, id); EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(id)->status); // Create a windowed application. AppLaunchParams params( profile(), controller_->GetExtensionForAppID(extensions::kWebStoreAppId), CURRENT_TAB, chrome::HOST_DESKTOP_TYPE_ASH, extensions::SOURCE_TEST); params.container = extensions::LAUNCH_CONTAINER_WINDOW; OpenApplication(params); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(id)->status); // Find the browser which holds our app. Browser* app_browser = NULL; const BrowserList* ash_browser_list = BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH); for (BrowserList::const_reverse_iterator it = ash_browser_list->begin_last_active(); it != ash_browser_list->end_last_active() && !app_browser; ++it) { if ((*it)->is_app()) { app_browser = *it; break; } } ASSERT_TRUE(app_browser); // After navigating away in the app, we should still be active. ui_test_utils::NavigateToURL(app_browser, GURL("http://www.foo.com/bar.html")); // Make sure the navigation was entirely performed. base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(ash::STATUS_ACTIVE, model_->ItemByID(id)->status); app_browser->tab_strip_model()->CloseWebContentsAt(0, TabStripModel::CLOSE_NONE); // Make sure that the app is really gone. base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(ash::STATUS_CLOSED, model_->ItemByID(id)->status); } // Checks that a opening a settings window creates a new launcher item. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, SettingsWindow) { chrome::SettingsWindowManager* settings_manager = chrome::SettingsWindowManager::GetInstance(); ash::ShelfModel* shelf_model = ash::Shell::GetInstance()->shelf_model(); // Get the number of items in the shelf and browser menu. int item_count = shelf_model->item_count(); size_t browser_count = NumberOfDetectedLauncherBrowsers(false); // Open a settings window. Number of browser items should remain unchanged, // number of shelf items should increase. settings_manager->ShowChromePageForProfile( browser()->profile(), chrome::GetSettingsUrl(std::string())); Browser* settings_browser = settings_manager->FindBrowserForProfile(browser()->profile()); ASSERT_TRUE(settings_browser); EXPECT_EQ(browser_count, NumberOfDetectedLauncherBrowsers(false)); EXPECT_EQ(item_count + 1, shelf_model->item_count()); // TODO(stevenjb): Test multiprofile on Chrome OS when test support is addded. // crbug.com/230464. }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/bluetooth/bluetooth_gatt_service.h" #include "build/build_config.h" #include "device/bluetooth/bluetooth_remote_gatt_characteristic.h" #include "device/bluetooth/test/test_bluetooth_adapter_observer.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_ANDROID) #include "device/bluetooth/test/bluetooth_test_android.h" #elif defined(OS_MACOSX) #include "device/bluetooth/test/bluetooth_test_mac.h" #elif defined(OS_WIN) #include "device/bluetooth/test/bluetooth_test_win.h" #endif namespace device { #if defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) class BluetoothRemoteGattServiceTest : public BluetoothTest {}; #endif #if defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) TEST_F(BluetoothRemoteGattServiceTest, GetIdentifier) { if (!PlatformSupportsLowEnergy()) { LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; return; } InitWithFakeAdapter(); StartLowEnergyDiscoverySession(); // 2 devices to verify unique IDs across them. BluetoothDevice* device1 = SimulateLowEnergyDevice(3); BluetoothDevice* device2 = SimulateLowEnergyDevice(4); device1->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED), GetConnectErrorCallback(Call::NOT_EXPECTED)); device2->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED), GetConnectErrorCallback(Call::NOT_EXPECTED)); SimulateGattConnection(device1); SimulateGattConnection(device2); // 2 duplicate UUIDs creating 2 service instances on each device. std::vector<std::string> services; std::string uuid = "00000000-0000-1000-8000-00805f9b34fb"; services.push_back(uuid); services.push_back(uuid); SimulateGattServicesDiscovered(device1, services); SimulateGattServicesDiscovered(device2, services); BluetoothRemoteGattService* service1 = device1->GetGattServices()[0]; BluetoothRemoteGattService* service2 = device1->GetGattServices()[1]; BluetoothRemoteGattService* service3 = device2->GetGattServices()[0]; BluetoothRemoteGattService* service4 = device2->GetGattServices()[1]; // All IDs are unique, even though they have the same UUID. EXPECT_NE(service1->GetIdentifier(), service2->GetIdentifier()); EXPECT_NE(service1->GetIdentifier(), service3->GetIdentifier()); EXPECT_NE(service1->GetIdentifier(), service4->GetIdentifier()); EXPECT_NE(service2->GetIdentifier(), service3->GetIdentifier()); EXPECT_NE(service2->GetIdentifier(), service4->GetIdentifier()); EXPECT_NE(service3->GetIdentifier(), service4->GetIdentifier()); } #endif // defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) TEST_F(BluetoothRemoteGattServiceTest, GetUUID) { if (!PlatformSupportsLowEnergy()) { LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; return; } InitWithFakeAdapter(); StartLowEnergyDiscoverySession(); BluetoothDevice* device = SimulateLowEnergyDevice(3); device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED), GetConnectErrorCallback(Call::NOT_EXPECTED)); SimulateGattConnection(device); // Create multiple instances with the same UUID. BluetoothUUID uuid("00000000-0000-1000-8000-00805f9b34fb"); std::vector<std::string> services; services.push_back(uuid.canonical_value()); services.push_back(uuid.canonical_value()); SimulateGattServicesDiscovered(device, services); // Each has the same UUID. EXPECT_EQ(uuid, device->GetGattServices()[0]->GetUUID()); EXPECT_EQ(uuid, device->GetGattServices()[1]->GetUUID()); } #endif // defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) TEST_F(BluetoothRemoteGattServiceTest, GetCharacteristics_FindNone) { if (!PlatformSupportsLowEnergy()) { LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; return; } InitWithFakeAdapter(); StartLowEnergyDiscoverySession(); BluetoothDevice* device = SimulateLowEnergyDevice(3); device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED), GetConnectErrorCallback(Call::NOT_EXPECTED)); SimulateGattConnection(device); // Simulate a service, with no Characteristics: std::vector<std::string> services; services.push_back("00000000-0000-1000-8000-00805f9b34fb"); SimulateGattServicesDiscovered(device, services); BluetoothRemoteGattService* service = device->GetGattServices()[0]; EXPECT_EQ(0u, service->GetCharacteristics().size()); } #endif // defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) TEST_F(BluetoothRemoteGattServiceTest, GetCharacteristics_and_GetCharacteristic) { if (!PlatformSupportsLowEnergy()) { LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; return; } InitWithFakeAdapter(); StartLowEnergyDiscoverySession(); BluetoothDevice* device = SimulateLowEnergyDevice(3); device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED), GetConnectErrorCallback(Call::NOT_EXPECTED)); SimulateGattConnection(device); // Simulate a service, with several Characteristics: std::vector<std::string> services; services.push_back("00000000-0000-1000-8000-00805f9b34fb"); SimulateGattServicesDiscovered(device, services); BluetoothRemoteGattService* service = device->GetGattServices()[0]; std::string characteristic_uuid1 = "11111111-0000-1000-8000-00805f9b34fb"; std::string characteristic_uuid2 = "22222222-0000-1000-8000-00805f9b34fb"; std::string characteristic_uuid3 = characteristic_uuid2; // Duplicate UUID. std::string characteristic_uuid4 = "33333333-0000-1000-8000-00805f9b34fb"; SimulateGattCharacteristic(service, characteristic_uuid1, /* properties */ 0); SimulateGattCharacteristic(service, characteristic_uuid2, /* properties */ 0); SimulateGattCharacteristic(service, characteristic_uuid3, /* properties */ 0); SimulateGattCharacteristic(service, characteristic_uuid4, /* properties */ 0); // Verify that GetCharacteristic can retrieve characteristics again by ID, // and that the same Characteristics come back. EXPECT_EQ(4u, service->GetCharacteristics().size()); std::string char_id1 = service->GetCharacteristics()[0]->GetIdentifier(); std::string char_id2 = service->GetCharacteristics()[1]->GetIdentifier(); std::string char_id3 = service->GetCharacteristics()[2]->GetIdentifier(); std::string char_id4 = service->GetCharacteristics()[3]->GetIdentifier(); BluetoothUUID char_uuid1 = service->GetCharacteristics()[0]->GetUUID(); BluetoothUUID char_uuid2 = service->GetCharacteristics()[1]->GetUUID(); BluetoothUUID char_uuid3 = service->GetCharacteristics()[2]->GetUUID(); BluetoothUUID char_uuid4 = service->GetCharacteristics()[3]->GetUUID(); EXPECT_EQ(char_uuid1, service->GetCharacteristic(char_id1)->GetUUID()); EXPECT_EQ(char_uuid2, service->GetCharacteristic(char_id2)->GetUUID()); EXPECT_EQ(char_uuid3, service->GetCharacteristic(char_id3)->GetUUID()); EXPECT_EQ(char_uuid4, service->GetCharacteristic(char_id4)->GetUUID()); // GetCharacteristics & GetCharacteristic return the same object for the same // ID: EXPECT_EQ(service->GetCharacteristics()[0], service->GetCharacteristic(char_id1)); EXPECT_EQ(service->GetCharacteristic(char_id1), service->GetCharacteristic(char_id1)); } #endif // defined(OS_ANDROID) || defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_MACOSX) || defined(OS_WIN) TEST_F(BluetoothRemoteGattServiceTest, GattCharacteristics_ObserversCalls) { if (!PlatformSupportsLowEnergy()) { LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; return; } InitWithFakeAdapter(); StartLowEnergyDiscoverySession(); BluetoothDevice* device = SimulateLowEnergyDevice(3); device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED), GetConnectErrorCallback(Call::NOT_EXPECTED)); SimulateGattConnection(device); TestBluetoothAdapterObserver observer(adapter_); // Simulate a service, with several Characteristics: std::vector<std::string> services; services.push_back("00000000-0000-1000-8000-00805f9b34fb"); SimulateGattServicesDiscovered(device, services); BluetoothRemoteGattService* service = device->GetGattServices()[0]; std::string characteristic_uuid1 = "11111111-0000-1000-8000-00805f9b34fb"; std::string characteristic_uuid2 = "22222222-0000-1000-8000-00805f9b34fb"; std::string characteristic_uuid3 = characteristic_uuid2; // Duplicate UUID. std::string characteristic_uuid4 = "33333333-0000-1000-8000-00805f9b34fb"; SimulateGattCharacteristic(service, characteristic_uuid1, /* properties */ 0); SimulateGattCharacteristic(service, characteristic_uuid2, /* properties */ 0); SimulateGattCharacteristic(service, characteristic_uuid3, /* properties */ 0); SimulateGattCharacteristic(service, characteristic_uuid4, /* properties */ 0); #if !defined(OS_WIN) // TODO(620895) GattCharacteristicAdded has to be implemented for Windows. EXPECT_EQ(4, observer.gatt_characteristic_added_count()); #endif // !defined(OS_WIN) // Simulate remove of characteristics one by one. EXPECT_EQ(4u, service->GetCharacteristics().size()); std::string removed_char = service->GetCharacteristics()[0]->GetIdentifier(); SimulateGattCharacteristicRemoved(service, service->GetCharacteristic(removed_char)); EXPECT_EQ(1, observer.gatt_characteristic_removed_count()); EXPECT_FALSE(service->GetCharacteristic(removed_char)); EXPECT_EQ(3u, service->GetCharacteristics().size()); removed_char = service->GetCharacteristics()[0]->GetIdentifier(); SimulateGattCharacteristicRemoved(service, service->GetCharacteristic(removed_char)); EXPECT_EQ(2, observer.gatt_characteristic_removed_count()); EXPECT_FALSE(service->GetCharacteristic(removed_char)); EXPECT_EQ(2u, service->GetCharacteristics().size()); removed_char = service->GetCharacteristics()[0]->GetIdentifier(); SimulateGattCharacteristicRemoved(service, service->GetCharacteristic(removed_char)); EXPECT_EQ(3, observer.gatt_characteristic_removed_count()); EXPECT_FALSE(service->GetCharacteristic(removed_char)); EXPECT_EQ(1u, service->GetCharacteristics().size()); removed_char = service->GetCharacteristics()[0]->GetIdentifier(); SimulateGattCharacteristicRemoved(service, service->GetCharacteristic(removed_char)); EXPECT_EQ(4, observer.gatt_characteristic_removed_count()); EXPECT_FALSE(service->GetCharacteristic(removed_char)); EXPECT_EQ(0u, service->GetCharacteristics().size()); #if defined(OS_MACOSX) // SimulateGattServicesDiscovered // 4 * SimulateGattCharacteristic // 4 * SimulateGattCharacteristicRemoved EXPECT_EQ(9, observer.gatt_service_changed_count()); #else // defined(OS_MACOSX) EXPECT_EQ(4, observer.gatt_service_changed_count()); #endif // defined(OS_MACOSX) } #endif // defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_WIN) || defined(OS_MACOSX) TEST_F(BluetoothRemoteGattServiceTest, SimulateGattServiceRemove) { if (!PlatformSupportsLowEnergy()) { LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; return; } InitWithFakeAdapter(); StartLowEnergyDiscoverySession(); BluetoothDevice* device = SimulateLowEnergyDevice(3); device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED), GetConnectErrorCallback(Call::NOT_EXPECTED)); SimulateGattConnection(device); TestBluetoothAdapterObserver observer(adapter_); // Simulate two primary GATT services. std::vector<std::string> services; services.push_back("00000000-0000-1000-8000-00805f9b34fb"); services.push_back("01010101-0101-1000-8000-00805f9b34fb"); SimulateGattServicesDiscovered(device, services); EXPECT_EQ(2u, device->GetGattServices().size()); // Simulate remove of a primary service. BluetoothRemoteGattService* service1 = device->GetGattServices()[0]; BluetoothRemoteGattService* service2 = device->GetGattServices()[1]; std::string removed_service = service1->GetIdentifier(); SimulateGattServiceRemoved(device->GetGattService(removed_service)); EXPECT_EQ(1, observer.gatt_service_removed_count()); EXPECT_EQ(1u, device->GetGattServices().size()); EXPECT_FALSE(device->GetGattService(removed_service)); EXPECT_EQ(device->GetGattServices()[0], service2); } #endif // defined(OS_WIN) || defined(OS_MACOSX) } // namespace device
#include "ocr.h" #include <iostream> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <stdarg.h> #include <stdlib.h> #include <sys/timeb.h> #include <stdint.h> #include <stdio.h> using namespace std; pthread_mutex_t piReadSection; // 互斥锁 int SearchFiles(const char * pszPath, string * pFileName) { DIR *dir = opendir(pszPath); if (dir == NULL) { return 0; } int FileNum = 0; while (true) { struct dirent *s_dir = readdir(dir); if (s_dir == NULL) break; if ((strcmp(s_dir->d_name, ".") == 0)||(strcmp(s_dir->d_name, "..") == 0)) continue; char currfile[_MAX_PATH]; sprintf(currfile, "%s/%s", pszPath, s_dir->d_name); struct stat file_stat; stat(currfile, &file_stat); if (!S_ISDIR(file_stat.st_mode)) { int nLen = strlen(s_dir->d_name); if (nLen >= 3) { char * pszExt = strrchr(s_dir->d_name, '.'); if (pszExt != NULL) { pFileName[FileNum++] = currfile; } } } } closedir(dir); return FileNum; } void UnicodeToUTF8(const unsigned char *src_unicode_str, unsigned long src_unicode_str_len, char *&dest_utf8_str, unsigned long &dest_utf8_str_len) { dest_utf8_str = new char[src_unicode_str_len * 3 + 1]; memset(dest_utf8_str, 0, src_unicode_str_len * 3 + 1); unsigned short *InPutStr = (unsigned short *)src_unicode_str; int i = 0, offset = 0; for (i = 0; i < src_unicode_str_len; i++) { if (InPutStr[i] <= 0x0000007f) { dest_utf8_str[offset++] = (char)(InPutStr[i] & 0x0000007f); } else if (InPutStr[i] >= 0x00000080 && InPutStr[i] <= 0x000007ff) { dest_utf8_str[offset++] = (char)(0xC0 | ((InPutStr[i] >> 6) & 0x1F)); dest_utf8_str[offset++] = (char)((InPutStr[i] & 0x0000003f) | 0x00000080); } else if (InPutStr[i] >= 0x00000800 && InPutStr[i] <= 0x0000ffff) { dest_utf8_str[offset++] = (char)(((InPutStr[i] & 0x0000f000) >> 12) | 0x000000e0); dest_utf8_str[offset++] = (char)(((InPutStr[i] & 0x00000fc0) >> 6) | 0x00000080); dest_utf8_str[offset++] = (char)((InPutStr[i] & 0x0000003f) | 0x00000080); } } dest_utf8_str[offset] = 0; dest_utf8_str_len = offset; return; } IREAD_ERR_CODE SetParam(IREAD_HANDLE hOCR, const OCR_PARAM & ocrParam) { IREAD_ERR_CODE errorCode; //Set image type errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_IMAGE_TYPE, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_IMAGE_TYPE); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set image binarize method errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_IMAGE_BINARIZE_METHOD, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_IMAGE_BINARIZE_METHOD); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set layout method errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_LAYOUT_METHOD, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_LAYOUT_METHOD); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set recog lang errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_RECOG_LANG, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_RECOG_LANG); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set recog range errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_RECOG_RANGE, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_RECOG_RANGE); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set recog range custom errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_RECOG_CUSTOM_CHARS, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_RECOG_CUSTOM_CHARS); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set output full half errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_OUTPUT_FULL_HALF, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_OUTPUT_FULL_HALF); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set output vert punc errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_OUTPUT_VERT_PUNC, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_OUTPUT_VERT_PUNC); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set output disp code errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_OUTPUT_DISP_CODE, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_OUTPUT_DISP_CODE); if (IREAD_ERR_NONE != errorCode) { return errorCode; } //Set output result option errorCode = iRead_SessionSetParam(hOCR, iREAD_PARAM_OUTPUT_RESULT_OPTION, (IREAD_PARAM_VALUE)ocrParam.iREAD_PARAM_OUTPUT_RESULT_OPTION); return errorCode; } IREAD_ERR_CODE RecognizeRegions(const char * szFileName, const OCR_PARAM & ocrParam, const IREAD_HANDLE engine_handle, const IREAD_REGION * pRegions, IREAD_INT nRegionCount) { IREAD_HANDLE hOCR; IREAD_IMAGE image; IREAD_RESULT pResult; IREAD_ERR_CODE errorCode = iRead_SessionStart(engine_handle, &hOCR); if (IREAD_ERR_NONE != errorCode) { return errorCode; } printf("iRead_SessionStart\n"); errorCode = iRead_LoadImage(szFileName, &image); if (IREAD_ERR_NONE != errorCode) { iRead_SessionStop(hOCR); return errorCode; } printf("iRead_LoadImage\n"); errorCode = SetParam(hOCR, ocrParam); if (IREAD_ERR_NONE != errorCode) { iRead_FreeImage(&image); iRead_SessionStop(hOCR); return errorCode; } printf("SetParam\n"); errorCode = iRead_SetImage(hOCR, &image); if (IREAD_ERR_NONE != errorCode) { iRead_FreeImage(&image); iRead_SessionStop(hOCR); return errorCode; } printf("iRead_SetImage\n"); errorCode = iRead_ResetRegions(hOCR, pRegions, nRegionCount); if (IREAD_ERR_NONE != errorCode) { iRead_FreeImage(&image); iRead_SessionStop(hOCR); return errorCode; } printf("iRead_ResetRegions\n"); errorCode = iRead_Recognize(hOCR, NULL, &pResult); if (IREAD_ERR_NONE != errorCode) { iRead_FreeImage(&image); iRead_SessionStop(hOCR); return errorCode; } printf("iRead_Recognize\n"); char *text_utf8 = NULL; unsigned long text_utf8_len = 0; UnicodeToUTF8((const unsigned char *)pResult.pTextBuf, pResult.nTextBufLen / 2 + 1, text_utf8, text_utf8_len); printf("len:%d, content:%s\n", text_utf8_len, text_utf8); delete[] text_utf8; IREAD_ERR_CODE errorCode1 = iRead_FreeImage(&image); errorCode1 = iRead_FreeResult(&pResult); errorCode1 = iRead_SessionStop(hOCR); return errorCode; } int main(int argc, char** argv) { srand(time(NULL)); //srand(737337); const char * pcszLibPath = "../Data/ResData"; const char * pcszDataPath = "../Data/TestData"; nFilesize = SearchFiles(pcszDataPath, strDataFileName); printf("********Test start!******\n"); if (0 == nFilesize) { printf("No file in directory: %s .\nPlease add images to the directory.", pcszDataPath ); getchar(); return 0; } IREAD_HANDLE engine_handle = NULL; IREAD_ERR_CODE errorCode = iRead_Init(pcszLibPath, &engine_handle); if (errorCode != IREAD_ERR_NONE) { printf("Initial failed!\n"); return 0; } IREAD_REGION regions[] = {{{0, 0, 1599, 1199}, IREAD_RGNTYPE_HORZTEXT, IREAD_LANGUAGE_CHINESE_CN, 0}}; OCR_PARAM ocrParam = {IREAD_IMAGE_TYPE_NORMAL, IREAD_BINARIZE_ADAPTIVE, IREAD_LAYOUT_NEWSPAPER, IREAD_LANGUAGE_CHINESE_CN, IREAD_RECOG_RANGE_ALL, paramRecogCustomChars[0], IREAD_FH_FULL, IREAD_VP_NO_CHANGE, IREAD_DP_NO_CHANGE, IREAD_RESULT_TEXTBUF}; RecognizeRegions("../Data/TestData/aa.jpg", ocrParam, engine_handle, regions, 1); errorCode = iRead_End(engine_handle); return 0; }
// stdafx.cpp : source file that includes just the standard includes // LockScreen.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
//--------------------------------------------*-C++-*---------------------------------------------// /*! * \file ds++/test/tstSortPermutation.cc * \author Randy M. Roberts * \date Mon Feb 14 14:20:45 2000 * \note Copyright (c) 2016-2020 Triad National Security, LLC. * All rights reserved. */ //------------------------------------------------------------------------------------------------// #include "ds++/Release.hh" #include "ds++/SortPermutation.hh" #include <array> #include <iostream> #include <list> namespace { using std::array; using std::cout; using std::endl; //------------------------------------------------------------------------------------------------// // TESTS //------------------------------------------------------------------------------------------------// void printStatus(const std::string &name, bool passed) { // Print the status of the test. std::string stars; for (size_t i = 0; i < name.length(); i++) stars += '*'; cout << "\n********" << stars << "********************\n"; if (passed) cout << "**** " << name << " Self Test: PASSED ****\n"; else cout << "**** " << name << " Self Test: FAILED ****\n"; cout << "********" << stars << "********************\n"; cout << endl; } //------------------------------------------------------------------------------------------------// template <typename IT> inline bool testit(const std::string & /*name*/, IT first, IT last) { rtt_dsxx::SortPermutation lfsp(first, last); using value_type = typename std::iterator_traits<IT>::value_type; std::vector<value_type> vv1(first, last); std::vector<value_type> vv2; for (unsigned i = 0; i < vv1.size(); i++) vv2.push_back(vv1[lfsp[i]]); IT lfi = first; for (unsigned i = 0; lfi != last; i++, ++lfi) vv1[lfsp.inv(i)] = *lfi; std::copy(first, last, std::ostream_iterator<value_type>(cout, " ")); cout << endl; std::copy(lfsp.begin(), lfsp.end(), std::ostream_iterator<int>(cout, " ")); cout << endl; std::copy(vv2.begin(), vv2.end(), std::ostream_iterator<value_type>(cout, " ")); cout << endl; std::copy(lfsp.inv_begin(), lfsp.inv_end(), std::ostream_iterator<int>(cout, " ")); cout << endl; using rtt_dsxx::isSorted; bool passed = isSorted(vv2.begin(), vv2.end()) && isSorted(vv1.begin(), vv1.end()); return passed; } //------------------------------------------------------------------------------------------------// template <typename IT, typename CMP> inline bool testit(const std::string & /*name*/, IT first, IT last, const CMP &comp) { rtt_dsxx::SortPermutation lfsp(first, last, comp); using value_type = typename std::iterator_traits<IT>::value_type; std::vector<value_type> vv1(first, last); std::vector<value_type> vv2; for (unsigned i = 0; i < vv1.size(); i++) vv2.push_back(vv1[lfsp[i]]); IT lfi = first; for (unsigned i = 0; lfi != last; i++, ++lfi) vv1[lfsp.inv(i)] = *lfi; std::copy(first, last, std::ostream_iterator<value_type>(cout, " ")); cout << endl; std::copy(lfsp.begin(), lfsp.end(), std::ostream_iterator<int>(cout, " ")); cout << endl; std::copy(vv2.begin(), vv2.end(), std::ostream_iterator<value_type>(cout, " ")); cout << endl; using rtt_dsxx::isSorted; bool passed = isSorted(vv2.begin(), vv2.end(), comp) && isSorted(vv1.begin(), vv1.end(), comp); return passed; } } // end unnamed namespace //------------------------------------------------------------------------------------------------// struct Foo { double d; Foo(double d_) : d(d_) { /* empty */ } bool operator<(const Foo &rhs) const { return d < rhs.d; } friend std::ostream &operator<<(std::ostream &os, const Foo &f) { return os << f.d; } }; //------------------------------------------------------------------------------------------------// struct FooGT { double d; FooGT(double d_) : d(d_) { /* empty */ } bool operator>(const FooGT &rhs) const noexcept { return d > rhs.d; } friend std::ostream &operator<<(std::ostream &os, const FooGT &f) { return os << f.d; } }; //------------------------------------------------------------------------------------------------// template <typename F> struct evenIsLess { bool operator()(const F &f1, const F &f2) const { auto i1 = static_cast<int>(f1.d); auto i2 = static_cast<int>(f2.d); return i1 % 2 == 0 ? ((i2 % 2 == 0 ? i1 < i2 : true)) : (i2 % 2 == 0 ? false : i1 < i2); } }; //------------------------------------------------------------------------------------------------// int main(int /*argc*/, char * /*argv*/ []) { cout << "Initiating test of the SortPermutation.\n"; std::string name = "SortPermutation"; try { bool passed = false; name = "SortPermutation(empty vector<Foo>)"; std::vector<Foo> evf; passed = testit("empty vector<Foo>", evf.begin(), evf.end()); printStatus(name, passed); array<Foo, 8> caf = {64, 89, 64, 73, 14, 90, 63, 14}; name = "SortPermutation(const list<Foo>)"; const std::list<Foo> lf(caf.begin(), caf.end()); passed = testit("const list<Foo>", lf.begin(), lf.end()); printStatus(name, passed); name = "SortPermutation(vector<Foo>)"; std::vector<Foo> vf(caf.begin(), caf.end()); passed = testit("vector<Foo>", vf.begin(), vf.end()); printStatus(name, passed); name = "SortPermutation(C-Array<Foo>)"; passed = testit("C-Array<Foo>", caf.begin(), caf.end()); printStatus(name, passed); name = "SortPermutation(const list<Foo>, evenIsLess<Foo>)"; const std::list<Foo> lfeven(caf.begin(), caf.end()); passed = testit("const list<Foo>", lfeven.begin(), lfeven.end(), evenIsLess<Foo>()); printStatus(name, passed); array<FooGT, 8> const cafg = {64, 89, 64, 73, 14, 90, 63, 14}; name = "SortPermutation(list<FooGT>, greater<FooGT>)"; std::list<FooGT> lfg(cafg.begin(), cafg.end()); passed = testit("list<FooGT>", lfg.begin(), lfg.end(), std::greater<>()); printStatus(name, passed); name = "SortPermutation(const vector<FooGT>, greater<FooGT>)"; const std::vector<FooGT> vfg(cafg.begin(), cafg.end()); passed = testit("const vector<FooGT>", vfg.begin(), vfg.end(), std::greater<>()); printStatus(name, passed); name = "SortPermutation(const C-Array<FooGT>, greater<FooGT>)"; passed = testit("const C-Array<FooGT>", cafg.begin(), cafg.begin() + caf.size(), std::greater<>()); printStatus(name, passed); } catch (rtt_dsxx::assertion &a) { cout << "Failed assertion: " << a.what() << endl; printStatus(name, false); return 1; } catch (...) { cout << "tstSortPermulation: Caught unknown exception." << endl; printStatus(name, false); return 1; } cout << "Done testing SortPermutation container.\n"; return 0; } //------------------------------------------------------------------------------------------------// // end of tstSortPermutation.cc //------------------------------------------------------------------------------------------------//
#ifndef INT2D_LINE_HPP #define INT2D_LINE_HPP // Generic Bressenham line algorithm code. #include <cassert> #include <cstdlib> #include <functional> #include <iterator> #include "geometry.hpp" #include "units.hpp" namespace i2d { // A wrapper around the state of Bressenham's line algorithm. // NOTE: A direction vector of {0,0} is considered invalid. struct line_state_t { coord_t position; coord_t direction; int error; // Use these to construct 'line_state_t'. // Aggregate initialization isn't recommended because 'error' needs // to be set. static line_state_t pos_dir(coord_t pos, coord_t dir); static line_state_t from_to(coord_t from, coord_t to); // The starting 'error' value for a given direction. // Starts the line right in the middle. static int dir_err(coord_t direction); static line_state_t next(line_state_t line); static line_state_t next(line_state_t line, int_t n); static line_state_t prev(line_state_t line); static line_state_t prev(line_state_t line, int_t n); static line_state_t hflipped(line_state_t line); static line_state_t vflipped(line_state_t line); void advance() { *this = next(*this); } void advance(int_t n) { *this = next(*this, n); } void radvance() { *this = prev(*this); } void radvance(int_t n) { *this = prev(*this, n); } void hflip() { *this = hflipped(*this); } void vflip() { *this = vflipped(*this); } explicit operator bool() const { return direction != coord_t{0,0}; } }; constexpr bool operator==(line_state_t lhs, line_state_t rhs) { return (lhs.position == rhs.position && lhs.direction == rhs.direction && lhs.error == rhs.error); } constexpr bool operator!=(line_state_t lhs, line_state_t rhs) { return !(lhs == rhs); } class line_iterator : public std::iterator<std::random_access_iteratorag, coord_t const> { friend class line_range; public: line_iterator() : m_state{} {} explicit line_iterator(line_state_t state) : m_state(state) {} coord_t operator*() const { return m_state.position; } coord_t const* operator->() const { return &m_state.position; } line_iterator& operator+=(int_t n) { m_state.advance(n); return *this; } line_iterator& operator++() { m_state.advance(); return *this; } line_iterator operator++(int_t) { line_iterator ret(*this); ++(*this); return ret; } line_iterator& operator-=(int_t n) { m_state.radvance(n); return *this; } line_iterator& operator--() { m_state.radvance(); return *this; } line_iterator operator--(int_t) { line_iterator ret(*this); --(*this); return ret; } line_iterator operator+(int_t rhs) const { line_iterator lhs = *this; lhs += rhs; return lhs; } line_iterator operator-(int_t rhs) const { line_iterator lhs = *this; lhs -= rhs; return lhs; } coord_t operator[](std::size_t i) { return *(*this + i); } line_state_t state() const { return m_state; } private: line_state_t m_state; }; std::size_t operator-(line_iterator lhs, line_iterator rhs); inline bool operator==(line_iterator lhs, line_iterator rhs) { assert(*lhs != *rhs || lhs.state() == rhs.state()); return *lhs == *rhs; } inline bool operator!=(line_iterator lhs, line_iterator rhs) { return !(lhs == rhs); } bool operator<(line_iterator lhs, line_iterator rhs); bool operator<=(line_iterator lhs, line_iterator rhs); bool operator>(line_iterator lhs, line_iterator rhs); bool operator>=(line_iterator lhs, line_iterator rhs); class line_range { public: using const_iterator = line_iterator; line_range() = default; explicit line_range(coord_t crd) : m_begin({ crd, { 1, 0 }, 0 }) , m_end({ crd + coord_t{ 1, 0 }, { 1, 0 }, 0 }) {} line_range(coord_t from, coord_t to) : line_range(line_state_t::from_to(from, to), cdistance(from, to) + 1) {} // NOTE: A direction vector of {0,0} is considered invalid. line_range(coord_t pos, coord_t dir, int_t steps) : line_range(line_state_t::pos_dir(pos, dir), steps) { assert(dir != {0,0}); } line_range(line_state_t begin, int_t steps) : m_begin(begin) , m_end(line_state_t::next(begin, steps)) {} line_iterator begin() const { return m_begin; } line_iterator end() const { return m_end; } line_iterator cbegin() const { return m_begin; } line_iterator cend() const { return m_end; } std::size_t size() const { return cend() - cbegin(); } coord_t first() const { return *m_begin; } coord_t last() const { return *(m_end - 1); } void lengthen() { ++m_end; } void shorten() { --m_end; } private: line_iterator m_begin; line_iterator m_end; }; namespace impl { constexpr bool is_steep(coord_t dir) { return sqr(dir.y) > sqr(dir.x); } inline coord_t coord_abs(coord_t direction) { return { std::abs(direction.x), std::abs(direction.y) }; } // The version of Bressenham being used requires x and y to swap when // the line is steeper than 45 degrees. // This function simplifies the swapping. template<typename Func> auto steep_swap(line_state_t line, Func func) { if(is_steep(line.direction)) return func(line, component_index<1>{}, component_index<0>{}); else return func(line, component_index<0>{}, component_index<1>{}); } template<typename T> constexpr int_t _signum(T x, std::false_type) { return T(0) < x; } template<typename T> constexpr int_t _signum(T x, std::true_type) { return (T(0) < x) - (x < T(0)); } // Returns either -1, 0, or 1, depending on sign of val. template<typename T> constexpr int_t signum(T x) { static_assert(std::is_arithmetic<T>::value, "only implemented for arithmetic"); return _signum(x, std::is_signed<T>()); } } // namespace impl // Calls 'it_func' with each coordinate of the line. // This may be slightly faster than line_state_t and line_range. template<typename Func> void iterate_line(coord_t from, coord_t to, Func it_func) { // Using a slightly different algorithm than line_state_t. // This version doesn't need to swap x or y. coord_t const direction = to - from; coord_t const d = impl::coord_abs(direction); coord_t const s = mapc(direction, &impl::signum<int_t>); for(int_t err = d.x - d.y; it_func(from), from != to;) { int_t const err2 = 2 * err; if(err2 > -d.y) { err -= d.y; from.x += s.x; } if(err2 < d.x) { err += d.x; from.y += s.y; } } } line_state_t line_state_t::pos_dir(coord_t pos, coord_t dir) { return { pos, dir, dir_err(dir) }; } line_state_t line_state_t::from_to(coord_t from, coord_t to) { if(from == to) return pos_dir(from, {1,0}); else return pos_dir(from, to - from); } int_t line_state_t::dir_err(coord_t direction) { using namespace impl; return std::abs(is_steep(direction) ? direction.y : direction.x); } line_state_t line_state_t::next(line_state_t line) { using namespace impl; assert((line.direction != coord_t{0,0})); // This is 1 iteration of Bressenham's line algorithm. return impl::steep_swap(line, [](line_state_t line, auto cx, auto cy) { coord_t const d = impl::coord_abs(line.direction); line.position[cx] += impl::signum(line.direction[cx]); line.error -= d[cy] * 2; if(line.error < 0) { line.position[cy] += impl::signum(line.direction[cy]); line.error += d[cx] * 2; } return line; }); } line_state_t line_state_t::prev(line_state_t line) { assert((line.direction != coord_t{0,0})); return impl::steep_swap(line, [](line_state_t line, auto cx, auto cy) { coord_t const d = impl::coord_abs(line.direction); line.position[cx] -= impl::signum(line.direction[cx]); line.error += d[cy] * 2; if(line.error > d[cx] * 2) { line.position[cy] -= impl::signum(line.direction[cy]); line.error -= d[cx] * 2; } return line; }); } static line_state_t next_impl(line_state_t line, int_t n) { assert((line.direction != coord_t{0,0})); return impl::steep_swap(line, [n](line_state_t line, auto cx, auto cy) { coord_t const d2 = vec_mul(impl::coord_abs(line.direction), 2); line.position[cx] += n * impl::signum(line.direction[cx]); line.error -= d2[cy] * n; int_t const y_change = (d2[cx] - line.error - 1) / d2[cx]; assert(y_change >= 0); line.position[cy] += y_change * impl::signum(line.direction[cy]); line.error += y_change * d2[cx]; return line; }); } static line_state_t prev_impl(line_state_t line, int_t n) { assert((line.direction != coord_t{0,0})); return impl::steep_swap(line, [n](line_state_t line, auto cx, auto cy) { coord_t const d2 = vec_mul(impl::coord_abs(line.direction), 2); line.position[cx] -= n * impl::signum(line.direction[cx]); line.error += d2[cy] * n; int_t const y_change = (line.error - 1) / d2[cx]; assert(y_change >= 0); line.position[cy] -= y_change * impl::signum(line.direction[cy]); line.error -= y_change * d2[cx]; return line; }); } // This is the same as repeatedly calling next(line) n times, // except this function has O(1) complexity instead of O(1). line_state_t line_state_t::next(line_state_t line, int_t n) { if(n < 0) return prev_impl(line, -n); else return next_impl(line, n); } line_state_t line_state_t::prev(line_state_t line, int_t n) { if(n < 0) return next_impl(line, -n); else return prev_impl(line, n); } line_state_t line_state_t::hflipped(line_state_t line) { // TODO: Should error be updated? line.direction.x *= -1; return line; } line_state_t line_state_t::vflipped(line_state_t line) { // TODO: Should error be changed? line.direction.y *= -1; return line; } std::size_t operator-(line_iterator lhs, line_iterator rhs) { return cdistance(*lhs, *rhs); } static int_t iter_cmp(line_iterator lhs, line_iterator rhs) { coord_t p2 = *rhs; return impl::steep_swap(lhs.state(), [p2](line_state_t l1, auto cx, auto cy) { return (l1.position[cx] - p2[cx]) * l1.direction[cx]; }); } bool operator<(line_iterator lhs, line_iterator rhs) { return iter_cmp(lhs, rhs) < 0; } bool operator<=(line_iterator lhs, line_iterator rhs) { return iter_cmp(lhs, rhs) <= 0; } bool operator>(line_iterator lhs, line_iterator rhs) { return iter_cmp(lhs, rhs) > 0; } bool operator>=(line_iterator lhs, line_iterator rhs) { return iter_cmp(lhs, rhs) >= 0; } } // namespace i2d #endif