text
stringlengths
5
1.04M
// Copyright (c) 2007-2017 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach, Katelyn Kufahl // Copyright (c) 2008-2009 Chirag Dekate, Anshul Tandon // Copyright (c) 2015 Patricia Grubel // Copyright (c) 2017 Shoshana Jakobovits // // SPDX-License-Identifier: BSL-1.0 // 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) #include <hpx/local/config.hpp> #include <hpx/coroutines/thread_enums.hpp> #include <cstddef> namespace hpx { namespace threads { /////////////////////////////////////////////////////////////////////// namespace strings { // clang-format off char const* const thread_state_names[] = { "unknown", "active", "pending", "suspended", "depleted", "terminated", "staged", "pending_do_not_schedule", "pending_boost" }; // clang-format on } // namespace strings char const* get_thread_state_name(thread_schedule_state state) { if (state > thread_schedule_state::pending_boost) return "unknown"; return strings::thread_state_names[static_cast<std::size_t>(state)]; } char const* get_thread_state_name(thread_state state) { return get_thread_state_name(state.state()); } std::ostream& operator<<(std::ostream& os, thread_schedule_state const t) { os << get_thread_state_name(t) << " (" << static_cast<std::size_t>(t) << ")"; return os; } /////////////////////////////////////////////////////////////////////// namespace strings { // clang-format off char const* const thread_state_ex_names[] = { "wait_unknown", "wait_signaled", "wait_timeout", "wait_terminate", "wait_abort" }; // clang-format on } // namespace strings char const* get_thread_state_ex_name(thread_restart_state state_ex) { if (state_ex > thread_restart_state::abort) return "wait_unknown"; return strings::thread_state_ex_names[static_cast<std::size_t>( state_ex)]; } std::ostream& operator<<(std::ostream& os, thread_restart_state const t) { os << get_thread_state_ex_name(t) << " (" << static_cast<std::size_t>(t) << ")"; return os; } /////////////////////////////////////////////////////////////////////// namespace strings { // clang-format off char const* const thread_priority_names[] = { "default", "low", "normal", "high (recursive)", "boost", "high (non-recursive)", }; // clang-format on } // namespace strings char const* get_thread_priority_name(thread_priority priority) { if (priority < thread_priority::default_ || priority > thread_priority::high) { return "unknown"; } return strings::thread_priority_names[static_cast<std::size_t>( priority)]; } std::ostream& operator<<(std::ostream& os, thread_priority const t) { os << get_thread_priority_name(t) << " (" << static_cast<std::size_t>(t) << ")"; return os; } namespace strings { // clang-format off char const* const stack_size_names[] = { "small", "medium", "large", "huge", "nostack", }; // clang-format on } // namespace strings char const* get_stack_size_enum_name(thread_stacksize size) { if (size == thread_stacksize::unknown) return "unknown"; if (size < thread_stacksize::small_ || size > thread_stacksize::nostack) return "custom"; return strings::stack_size_names[static_cast<std::size_t>(size) - 1]; } std::ostream& operator<<(std::ostream& os, thread_stacksize const t) { os << get_stack_size_enum_name(t) << " (" << static_cast<std::size_t>(t) << ")"; return os; } }} // namespace hpx::threads
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "arrow/array/concatenate.h" #include <algorithm> #include <limits> #include <memory> #include <utility> #include <vector> #include "arrow/array.h" #include "arrow/memory_pool.h" #include "arrow/status.h" #include "arrow/util/logging.h" #include "arrow/util/visibility.h" #include "arrow/visitor_inline.h" namespace arrow { /// offset, length pair for representing a Range of a buffer or array struct Range { int64_t offset, length; Range() : offset(-1), length(0) {} Range(int64_t o, int64_t l) : offset(o), length(l) {} }; /// non-owning view into a range of bits struct Bitmap { Bitmap() = default; Bitmap(const uint8_t* d, Range r) : data(d), range(r) {} explicit Bitmap(const std::shared_ptr<Buffer>& buffer, Range r) : Bitmap(buffer ? buffer->data() : nullptr, r) {} const uint8_t* data; Range range; bool AllSet() const { return data == nullptr; } }; // Allocate a buffer and concatenate bitmaps into it. static Status ConcatenateBitmaps(const std::vector<Bitmap>& bitmaps, MemoryPool* pool, std::shared_ptr<Buffer>* out) { int64_t out_length = 0; for (size_t i = 0; i < bitmaps.size(); ++i) { out_length += bitmaps[i].range.length; } RETURN_NOT_OK(AllocateBitmap(pool, out_length, out)); uint8_t* dst = (*out)->mutable_data(); int64_t bitmap_offset = 0; for (size_t i = 0; i < bitmaps.size(); ++i) { auto bitmap = bitmaps[i]; if (bitmap.AllSet()) { BitUtil::SetBitsTo(dst, bitmap_offset, bitmap.range.length, true); } else { internal::CopyBitmap(bitmap.data, bitmap.range.offset, bitmap.range.length, dst, bitmap_offset, false); } bitmap_offset += bitmap.range.length; } // finally (if applicable) zero out any trailing bits if (auto preceding_bits = BitUtil::kPrecedingBitmask[out_length % 8]) { dst[out_length / 8] &= preceding_bits; } return Status::OK(); } // Write offsets in src into dst, adjusting them such that first_offset // will be the first offset written. template <typename Offset> static Status PutOffsets(const std::shared_ptr<Buffer>& src, Offset first_offset, Offset* dst, Range* values_range); // Concatenate buffers holding offsets into a single buffer of offsets, // also computing the ranges of values spanned by each buffer of offsets. template <typename Offset> static Status ConcatenateOffsets(const BufferVector& buffers, MemoryPool* pool, std::shared_ptr<Buffer>* out, std::vector<Range>* values_ranges) { values_ranges->resize(buffers.size()); // allocate output buffer int64_t out_length = 0; for (size_t i = 0; i < buffers.size(); ++i) { out_length += buffers[i]->size() / sizeof(Offset); } RETURN_NOT_OK(AllocateBuffer(pool, (out_length + 1) * sizeof(Offset), out)); auto dst = reinterpret_cast<Offset*>((*out)->mutable_data()); int64_t elements_length = 0; Offset values_length = 0; for (size_t i = 0; i < buffers.size(); ++i) { // the first offset from buffers[i] will be adjusted to values_length // (the cumulative length of values spanned by offsets in previous buffers) RETURN_NOT_OK(PutOffsets<Offset>(buffers[i], values_length, &dst[elements_length], &values_ranges->at(i))); elements_length += buffers[i]->size() / sizeof(Offset); values_length += static_cast<Offset>(values_ranges->at(i).length); } // the final element in dst is the length of all values spanned by the offsets dst[out_length] = values_length; return Status::OK(); } template <typename Offset> static Status PutOffsets(const std::shared_ptr<Buffer>& src, Offset first_offset, Offset* dst, Range* values_range) { // Get the range of offsets to transfer from src auto src_begin = reinterpret_cast<const Offset*>(src->data()); auto src_end = reinterpret_cast<const Offset*>(src->data() + src->size()); // Compute the range of values which is spanned by this range of offsets values_range->offset = src_begin[0]; values_range->length = *src_end - values_range->offset; if (first_offset > std::numeric_limits<Offset>::max() - values_range->length) { return Status::Invalid("offset overflow while concatenating arrays"); } // Write offsets into dst, ensuring that the first offset written is // first_offset auto adjustment = first_offset - src_begin[0]; std::transform(src_begin, src_end, dst, [adjustment](Offset offset) { return offset + adjustment; }); return Status::OK(); } class ConcatenateImpl { public: ConcatenateImpl(const std::vector<ArrayData>& in, MemoryPool* pool) : in_(in), pool_(pool) { out_.type = in[0].type; for (size_t i = 0; i < in_.size(); ++i) { out_.length += in[i].length; if (out_.null_count == kUnknownNullCount || in[i].null_count == kUnknownNullCount) { out_.null_count = kUnknownNullCount; continue; } out_.null_count += in[i].null_count; } out_.buffers.resize(in[0].buffers.size()); out_.child_data.resize(in[0].child_data.size()); for (auto& data : out_.child_data) { data = std::make_shared<ArrayData>(); } } Status Concatenate(ArrayData* out) && { if (out_.null_count != 0) { RETURN_NOT_OK(ConcatenateBitmaps(Bitmaps(0), pool_, &out_.buffers[0])); } RETURN_NOT_OK(VisitTypeInline(*out_.type, this)); *out = std::move(out_); return Status::OK(); } Status Visit(const NullType&) { return Status::OK(); } Status Visit(const BooleanType&) { return ConcatenateBitmaps(Bitmaps(1), pool_, &out_.buffers[1]); } Status Visit(const FixedWidthType& fixed) { // handles numbers, decimal128, fixed_size_binary return ConcatenateBuffers(Buffers(1, fixed), pool_, &out_.buffers[1]); } Status Visit(const BinaryType&) { std::vector<Range> value_ranges; RETURN_NOT_OK(ConcatenateOffsets<int32_t>(Buffers(1, *offset_type), pool_, &out_.buffers[1], &value_ranges)); return ConcatenateBuffers(Buffers(2, value_ranges), pool_, &out_.buffers[2]); } Status Visit(const ListType&) { std::vector<Range> value_ranges; RETURN_NOT_OK(ConcatenateOffsets<int32_t>(Buffers(1, *offset_type), pool_, &out_.buffers[1], &value_ranges)); return ConcatenateImpl(ChildData(0, value_ranges), pool_) .Concatenate(out_.child_data[0].get()); } Status Visit(const FixedSizeListType&) { return ConcatenateImpl(ChildData(0), pool_).Concatenate(out_.child_data[0].get()); } Status Visit(const StructType& s) { for (int i = 0; i < s.num_children(); ++i) { RETURN_NOT_OK( ConcatenateImpl(ChildData(i), pool_).Concatenate(out_.child_data[i].get())); } return Status::OK(); } Status Visit(const DictionaryType& d) { auto fixed = internal::checked_cast<const FixedWidthType*>(d.index_type().get()); // Two cases: all the dictionaries are the same, or unification is // required bool dictionaries_same = true; const Array& dictionary0 = *in_[0].dictionary; for (size_t i = 1; i < in_.size(); ++i) { if (!in_[i].dictionary->Equals(dictionary0)) { dictionaries_same = false; break; } } if (dictionaries_same) { out_.dictionary = in_[0].dictionary; return ConcatenateBuffers(Buffers(1, *fixed), pool_, &out_.buffers[1]); } else { return Status::NotImplemented("Concat with dictionary unification NYI"); } } Status Visit(const UnionType& u) { return Status::NotImplemented("concatenation of ", u); } Status Visit(const ExtensionType& e) { // XXX can we just concatenate their storage? return Status::NotImplemented("concatenation of ", e); } private: // Gather the index-th buffer of each input into a vector. // Bytes are sliced with that input's offset and length. BufferVector Buffers(size_t index) { BufferVector buffers(in_.size()); for (size_t i = 0; i < in_.size(); ++i) { buffers[i] = SliceBuffer(in_[i].buffers[index], in_[i].offset, in_[i].length); } return buffers; } // Gather the index-th buffer of each input into a vector. // Bytes are sliced with the explicitly passed ranges. BufferVector Buffers(size_t index, const std::vector<Range>& ranges) { DCHECK_EQ(in_.size(), ranges.size()); BufferVector buffers(in_.size()); for (size_t i = 0; i < in_.size(); ++i) { buffers[i] = SliceBuffer(in_[i].buffers[index], ranges[i].offset, ranges[i].length); } return buffers; } // Gather the index-th buffer of each input into a vector. // Buffers are assumed to contain elements of fixed.bit_width(), // those elements are sliced with that input's offset and length. BufferVector Buffers(size_t index, const FixedWidthType& fixed) { DCHECK_EQ(fixed.bit_width() % 8, 0); auto byte_width = fixed.bit_width() / 8; BufferVector buffers(in_.size()); for (size_t i = 0; i < in_.size(); ++i) { buffers[i] = SliceBuffer(in_[i].buffers[index], in_[i].offset * byte_width, in_[i].length * byte_width); } return buffers; } // Gather the index-th buffer of each input as a Bitmap // into a vector of Bitmaps. std::vector<Bitmap> Bitmaps(size_t index) { std::vector<Bitmap> bitmaps(in_.size()); for (size_t i = 0; i < in_.size(); ++i) { Range range(in_[i].offset, in_[i].length); bitmaps[i] = Bitmap(in_[i].buffers[index], range); } return bitmaps; } // Gather the index-th child_data of each input into a vector. // Elements are sliced with that input's offset and length. std::vector<ArrayData> ChildData(size_t index) { std::vector<ArrayData> child_data(in_.size()); for (size_t i = 0; i < in_.size(); ++i) { child_data[i] = in_[i].child_data[index]->Slice(in_[i].offset, in_[i].length); } return child_data; } // Gather the index-th child_data of each input into a vector. // Elements are sliced with the explicitly passed ranges. std::vector<ArrayData> ChildData(size_t index, const std::vector<Range>& ranges) { DCHECK_EQ(in_.size(), ranges.size()); std::vector<ArrayData> child_data(in_.size()); for (size_t i = 0; i < in_.size(); ++i) { child_data[i] = in_[i].child_data[index]->Slice(ranges[i].offset, ranges[i].length); } return child_data; } static const std::shared_ptr<FixedWidthType> offset_type; const std::vector<ArrayData>& in_; MemoryPool* pool_; ArrayData out_; }; const std::shared_ptr<FixedWidthType> ConcatenateImpl::offset_type = std::static_pointer_cast<FixedWidthType>(int32()); Status Concatenate(const ArrayVector& arrays, MemoryPool* pool, std::shared_ptr<Array>* out) { if (arrays.size() == 0) { return Status::Invalid("Must pass at least one array"); } // gather ArrayData of input arrays std::vector<ArrayData> data(arrays.size()); for (size_t i = 0; i < arrays.size(); ++i) { if (!arrays[i]->type()->Equals(*arrays[0]->type())) { return Status::Invalid("arrays to be concatenated must be identically typed, but ", *arrays[0]->type(), " and ", *arrays[i]->type(), " were encountered."); } data[i] = *arrays[i]->data(); } ArrayData out_data; RETURN_NOT_OK(ConcatenateImpl(data, pool).Concatenate(&out_data)); *out = MakeArray(std::make_shared<ArrayData>(std::move(out_data))); return Status::OK(); } } // namespace arrow
#pragma once #include "../../SdkCore/_InterfaceExt.hpp"
//***************************************************************************** // Copyright 2017-2019 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. //***************************************************************************** #include "ngraph/op/embedding_lookup.hpp" using namespace std; using namespace ngraph; const string op::EmbeddingLookup::type_name{"EmbeddingLookup"}; void op::EmbeddingLookup::validate_and_infer_types() { element::Type result_et = get_input_element_type(1); const PartialShape& arg0_shape = get_input_partial_shape(0); const PartialShape& arg1_shape = get_input_partial_shape(1); NODE_VALIDATION_CHECK(this, arg1_shape.rank().is_dynamic() || static_cast<size_t>(arg1_shape.rank()) == 2, "weights are expected to be a matrix"); PartialShape result_shape; if (arg0_shape.rank().is_static()) { std::vector<Dimension> result_dims(static_cast<size_t>(arg0_shape.rank()) + 1); for (size_t i = 0; i < static_cast<size_t>(arg0_shape.rank()); i++) { result_dims[i] = arg0_shape[i]; } result_dims[result_dims.size() - 1] = arg1_shape.rank().is_static() ? arg1_shape[1] : Dimension::dynamic(); result_shape = PartialShape(result_dims); } else { result_shape = PartialShape::dynamic(); } set_output_type(0, result_et, result_shape); } shared_ptr<Node> op::EmbeddingLookup::copy_with_new_args(const NodeVector& new_args) const { check_new_args_count(this, new_args); return make_shared<EmbeddingLookup>(new_args.at(0), new_args.at(1)); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util.h" #include "chainparams.h" #include "sync.h" #include "ui_interface.h" #include "uint256.h" #include "version.h" #include <algorithm> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION namespace boost { namespace program_options { std::string to_internal(const std::string&); } } #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <stdarg.h> #ifdef WIN32 #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include "shlobj.h" #elif defined(__linux__) # include <sys/prctl.h> #endif using namespace std; map<string, string> mapArgs; map<string, string> mapCoinArgs; map<string, vector<string> > mapMultiArgs; bool fDebug = false; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fDaemon = false; bool fServer = false; bool fCommandLine = false; string strMiscWarning; bool fNoListen = false; bool fLogTimestamps = false; volatile bool fReopenDebugLog = false; // Init OpenSSL library multithreading support static CCriticalSection** ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } } LockedPageManager LockedPageManager::instance; // Init class CInit { public: CInit() { // Init OpenSSL library multithreading support ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*)); for (int i = 0; i < CRYPTO_num_locks(); i++) ppmutexOpenSSL[i] = new CCriticalSection(); CRYPTO_set_locking_callback(locking_callback); #ifdef WIN32 // Seed OpenSSL PRNG with current contents of the screen RAND_screen(); #endif // Seed OpenSSL PRNG with performance counter RandAddSeed(); } ~CInit() { // Securely erase the memory used by the PRNG RAND_cleanup(); // Shutdown OpenSSL library multithreading support CRYPTO_set_locking_callback(NULL); for (int i = 0; i < CRYPTO_num_locks(); i++) delete ppmutexOpenSSL[i]; OPENSSL_free(ppmutexOpenSSL); } } instance_of_cinit; void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memset(&nCounter, 0, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data unsigned char pdata[250000]; memset(pdata, 0, sizeof(pdata)); unsigned long nSize = sizeof(pdata); long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize); RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(pdata, nSize, nSize/100.0); OPENSSL_cleanse(pdata, nSize); LogPrint("rand", "RandAddSeed() %lu bytes\n", nSize); } #endif } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do RAND_bytes((unsigned char*)&nRand, sizeof(nRand)); while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; RAND_bytes((unsigned char*)&hash, sizeof(hash)); return hash; } // LogPrintf() has been broken a couple of times now // by well-meaning people adding mutexes in the most straightforward way. // It breaks because it may be called by global destructors during shutdown. // Since the order of destruction of static/global objects is undefined, // defining a mutex as a global object doesn't work (the mutex gets // destroyed, and then some later destructor calls OutputDebugStringF, // maybe indirectly, and you get a core dump at shutdown trying to lock // the mutex). static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT; // We use boost::call_once() to make sure these are initialized in // in a thread-safe manner the first time it is called: static FILE* fileout = NULL; static boost::mutex* mutexDebugLog = NULL; static void DebugPrintInit() { assert(fileout == NULL); assert(mutexDebugLog == NULL); boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; fileout = fopen(pathDebug.string().c_str(), "a"); if (fileout) setbuf(fileout, NULL); // unbuffered mutexDebugLog = new boost::mutex(); } bool LogAcceptCategory(const char* category) { if (category != NULL) { if (!fDebug) return false; // Give each thread quick access to -debug settings. // This helps prevent issues debugging global destructors, // where mapMultiArgs might be deleted before another // global destructor calls LogPrint() static boost::thread_specific_ptr<set<string> > ptrCategory; if (ptrCategory.get() == NULL) { const vector<string>& categories = mapMultiArgs["-debug"]; ptrCategory.reset(new set<string>(categories.begin(), categories.end())); // thread_specific_ptr automatically deletes the set when the thread ends. } const set<string>& setCategories = *ptrCategory.get(); // if not debugging everything and not debugging specific category, LogPrint does nothing. if (setCategories.count(string("")) == 0 && setCategories.count(string(category)) == 0) return false; } return true; } int LogPrintStr(const std::string &str) { int ret = 0; // Returns total number of characters written if (fPrintToConsole) { // print to console ret = fwrite(str.data(), 1, str.size(), stdout); } else if (fPrintToDebugLog) { static bool fStartedNewLine = true; boost::call_once(&DebugPrintInit, debugPrintInitFlag); if (fileout == NULL) return ret; boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL) setbuf(fileout, NULL); // unbuffered } // Debug print useful for profiling if (fLogTimestamps && fStartedNewLine) ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str()); if (!str.empty() && str[str.size()-1] == '\n') fStartedNewLine = true; else fStartedNewLine = false; ret = fwrite(str.data(), 1, str.size(), fileout); } return ret; } void ParseString(const string& str, char c, vector<string>& v) { if (str.empty()) return; string::size_type i1 = 0; string::size_type i2; while (true) { i2 = str.find(c, i1); if (i2 == str.npos) { v.push_back(str.substr(i1)); return; } v.push_back(str.substr(i1, i2-i1)); i1 = i2+1; } } string FormatMoney(int64_t n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. int64_t n_abs = (n > 0 ? n : -n); int64_t quotient = n_abs/COIN; int64_t remainder = n_abs%COIN; string str = strprintf("%d.%08d", quotient, remainder); // Right-trim excess zeros before the decimal point: int nTrim = 0; for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i) ++nTrim; if (nTrim) str.erase(str.size()-nTrim, nTrim); if (n < 0) str.insert((unsigned int)0, 1, '-'); else if (fPlus && n > 0) str.insert((unsigned int)0, 1, '+'); return str; } bool ParseMoney(const string& str, int64_t& nRet) { return ParseMoney(str.c_str(), nRet); } bool ParseMoney(const char* pszIn, int64_t& nRet) { string strWhole; int64_t nUnits = 0; const char* p = pszIn; while (isspace(*p)) p++; for (; *p; p++) { if (*p == '.') { p++; int64_t nMult = CENT*10; while (isdigit(*p) && (nMult > 0)) { nUnits += nMult * (*p++ - '0'); nMult /= 10; } break; } if (isspace(*p)) break; if (!isdigit(*p)) return false; strWhole.insert(strWhole.end(), *p); } for (; *p; p++) if (!isspace(*p)) return false; if (strWhole.size() > 10) // guard against 63 bit overflow return false; if (nUnits < 0 || nUnits > COIN) return false; int64_t nWhole = atoi64(strWhole); int64_t nValue = nWhole*COIN + nUnits; nRet = nValue; return true; } // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything // even possibly remotely dangerous like & or > static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@"); string SanitizeString(const string& str) { string strResult; for (std::string::size_type i = 0; i < str.size(); i++) { if (safeChars.find(str[i]) != std::string::npos) strResult.push_back(str[i]); } return strResult; } static const signed char phexdigit[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; bool IsHex(const string& str) { BOOST_FOREACH(unsigned char c, str) { if (phexdigit[c] < 0) return false; } return (str.size() > 0) && (str.size()%2 == 0); } vector<unsigned char> ParseHex(const char* psz) { // convert hex dump to vector vector<unsigned char> vch; while (true) { while (isspace(*psz)) psz++; signed char c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; unsigned char n = (c << 4); c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; n |= c; vch.push_back(n); } return vch; } vector<unsigned char> ParseHex(const string& str) { return ParseHex(str.c_str()); } static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet) { // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set if (name.find("-no") == 0) { std::string positive("-"); positive.append(name.begin()+3, name.end()); if (mapSettingsRet.count(positive) == 0) { bool value = !GetBoolArg(name, false); mapSettingsRet[positive] = (value ? "1" : "0"); } } } void ParseParameters(int argc, const char* const argv[]) { mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { std::string str(argv[i]); std::string strValue; size_t is_index = str.find('='); if (is_index != std::string::npos) { strValue = str.substr(is_index+1); str = str.substr(0, is_index); } #ifdef WIN32 boost::to_lower(str); if (boost::algorithm::starts_with(str, "/")) str = "-" + str.substr(1); #endif if (str[0] != '-') break; if (boost::algorithm::starts_with(str, "-coin:")) { mapCoinArgs["-" + str.substr(6)] = strValue; } else { mapArgs[str] = strValue; } mapMultiArgs[str].push_back(strValue); } // New 0.6 features: BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs) { string name = entry.first; // interpret --foo as -foo (as long as both are not set) if (name.find("--") == 0) { std::string singleDash(name.begin()+1, name.end()); if (mapArgs.count(singleDash) == 0) mapArgs[singleDash] = entry.second; name = singleDash; } // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set InterpretNegativeSetting(name, mapArgs); } } std::string GetArg(const std::string& strArg, const std::string& strDefault) { if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } std::string GetCoinArg(const std::string& strArg, const std::string& strDefault) { if (mapCoinArgs.count(strArg)) return mapCoinArgs[strArg]; return strDefault; } int64_t GetArg(const std::string& strArg, int64_t nDefault) { if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } int64_t GetCoinArg(const std::string& strArg, int64_t nDefault) { if (mapCoinArgs.count(strArg)) return atoi64(mapCoinArgs[strArg]); return nDefault; } bool GetBoolArg(const std::string& strArg, bool fDefault) { if (mapArgs.count(strArg)) { if (mapArgs[strArg].empty()) return true; return (atoi(mapArgs[strArg]) != 0); } return fDefault; } bool GetCoinBoolArg(const std::string& strArg, bool fDefault) { if (mapCoinArgs.count(strArg)) { if (mapCoinArgs[strArg].empty()) return true; return (atoi(mapCoinArgs[strArg]) != 0); } return fDefault; } bool SoftSetCoinArg(const std::string& strArg, const std::string& strValue) { if (mapCoinArgs.count(strArg)) return false; mapCoinArgs[strArg] = strValue; return true; } bool SoftSetArg(const std::string& strArg, const std::string& strValue) { if (mapArgs.count(strArg)) return false; mapArgs[strArg] = strValue; return true; } bool SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } string EncodeBase64(const unsigned char* pch, size_t len) { static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; string strRet=""; strRet.reserve((len+2)/3*4); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase64[enc >> 2]; left = (enc & 3) << 4; mode = 1; break; case 1: // we have two bits strRet += pbase64[left | (enc >> 4)]; left = (enc & 15) << 2; mode = 2; break; case 2: // we have four bits strRet += pbase64[left | (enc >> 6)]; strRet += pbase64[enc & 63]; mode = 0; break; } } if (mode) { strRet += pbase64[left]; strRet += '='; if (mode == 1) strRet += '='; } return strRet; } string EncodeBase64(const string& str) { return EncodeBase64((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid) { static const int decode64_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve(strlen(p)*3/4); int mode = 0; int left = 0; while (1) { int dec = decode64_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 6 left = dec; mode = 1; break; case 1: // we have 6 bits and keep 4 vchRet.push_back((left<<2) | (dec>>4)); left = dec & 15; mode = 2; break; case 2: // we have 4 bits and get 6, we keep 2 vchRet.push_back((left<<4) | (dec>>2)); left = dec & 3; mode = 3; break; case 3: // we have 2 bits and get 6 vchRet.push_back((left<<6) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 4n base64 characters processed: ok break; case 1: // 4n+1 base64 character processed: impossible *pfInvalid = true; break; case 2: // 4n+2 base64 characters processed: require '==' if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1) *pfInvalid = true; break; case 3: // 4n+3 base64 characters processed: require '=' if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase64(const string& str) { vector<unsigned char> vchRet = DecodeBase64(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } string EncodeBase32(const unsigned char* pch, size_t len) { static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; string strRet=""; strRet.reserve((len+4)/5*8); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase32[enc >> 3]; left = (enc & 7) << 2; mode = 1; break; case 1: // we have three bits strRet += pbase32[left | (enc >> 6)]; strRet += pbase32[(enc >> 1) & 31]; left = (enc & 1) << 4; mode = 2; break; case 2: // we have one bit strRet += pbase32[left | (enc >> 4)]; left = (enc & 15) << 1; mode = 3; break; case 3: // we have four bits strRet += pbase32[left | (enc >> 7)]; strRet += pbase32[(enc >> 2) & 31]; left = (enc & 3) << 3; mode = 4; break; case 4: // we have two bits strRet += pbase32[left | (enc >> 5)]; strRet += pbase32[enc & 31]; mode = 0; } } static const int nPadding[5] = {0, 6, 4, 3, 1}; if (mode) { strRet += pbase32[left]; for (int n=0; n<nPadding[mode]; n++) strRet += '='; } return strRet; } string EncodeBase32(const string& str) { return EncodeBase32((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid) { static const int decode32_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve((strlen(p))*5/8); int mode = 0; int left = 0; while (1) { int dec = decode32_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 5 left = dec; mode = 1; break; case 1: // we have 5 bits and keep 2 vchRet.push_back((left<<3) | (dec>>2)); left = dec & 3; mode = 2; break; case 2: // we have 2 bits and keep 7 left = left << 5 | dec; mode = 3; break; case 3: // we have 7 bits and keep 4 vchRet.push_back((left<<1) | (dec>>4)); left = dec & 15; mode = 4; break; case 4: // we have 4 bits, and keep 1 vchRet.push_back((left<<4) | (dec>>1)); left = dec & 1; mode = 5; break; case 5: // we have 1 bit, and keep 6 left = left << 5 | dec; mode = 6; break; case 6: // we have 6 bits, and keep 3 vchRet.push_back((left<<2) | (dec>>3)); left = dec & 7; mode = 7; break; case 7: // we have 3 bits, and keep 0 vchRet.push_back((left<<5) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 8n base32 characters processed: ok break; case 1: // 8n+1 base32 characters processed: impossible case 3: // +3 case 6: // +6 *pfInvalid = true; break; case 2: // 8n+2 base32 characters processed: require '======' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1) *pfInvalid = true; break; case 4: // 8n+4 base32 characters processed: require '====' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1) *pfInvalid = true; break; case 5: // 8n+5 base32 characters processed: require '===' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1) *pfInvalid = true; break; case 7: // 8n+7 base32 characters processed: require '=' if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase32(const string& str) { vector<unsigned char> vchRet = DecodeBase32(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } bool WildcardMatch(const char* psz, const char* mask) { while (true) { switch (*mask) { case '\0': return (*psz == '\0'); case '*': return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask)); case '?': if (*psz == '\0') return false; break; default: if (*psz != *mask) return false; break; } psz++; mask++; } } bool WildcardMatch(const string& str, const string& mask) { return WildcardMatch(str.c_str(), mask.c_str()); } static std::string FormatException(std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); #else const char* pszModule = "blackcoin"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void PrintException(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; throw; } void PrintExceptionContinue(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; } boost::filesystem::path GetDefaultDataDir() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\BlackCoin // Windows >= Vista: C:\Users\Username\AppData\Roaming\BlackCoin // Mac: ~/Library/Application Support/BlackCoin // Unix: ~/.blackcoin #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "BlackShares"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; fs::create_directory(pathRet); return pathRet / "BlackShares"; #else // Unix return pathRet / ".blackshares"; #endif #endif } static boost::filesystem::path pathCached[CChainParams::MAX_NETWORK_TYPES+1]; static CCriticalSection csPathCached; const boost::filesystem::path &GetDataDir(bool fNetSpecific) { namespace fs = boost::filesystem; LOCK(csPathCached); int nNet = CChainParams::MAX_NETWORK_TYPES; if (fNetSpecific) nNet = Params().NetworkID(); fs::path &path = pathCached[nNet]; // This can be called during exceptions by LogPrintf(), so we cache the // value so we don't have to do memory allocations after that. if (!path.empty()) return path; if (mapArgs.count("-datadir")) { path = fs::system_complete(mapArgs["-datadir"]); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific) path /= Params().DataDir(); fs::create_directory(path); return path; } void ClearDatadirCache() { std::fill(&pathCached[0], &pathCached[CChainParams::MAX_NETWORK_TYPES+1], boost::filesystem::path()); } boost::filesystem::path GetConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-conf", "blackshares.conf")); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()) return; // No bitcoin.conf file is OK set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override bitcoin.conf string strKey = string("-") + it->string_key; if (mapSettingsRet.count(strKey) == 0) { mapSettingsRet[strKey] = it->value[0]; // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set) InterpretNegativeSetting(strKey, mapSettingsRet); } mapMultiSettingsRet[strKey].push_back(it->value[0]); } // If datadir is changed in .conf file: ClearDatadirCache(); } void ReadCoinConfigFile(string filename, map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(filename); if (!streamConfig.good()) return; // No bitcoin.conf file is OK set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override bitcoin.conf string strKey = string("-") + it->string_key; if (mapSettingsRet.count(strKey) == 0) { mapSettingsRet[strKey] = it->value[0]; // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set) InterpretNegativeSetting(strKey, mapSettingsRet); } mapMultiSettingsRet[strKey].push_back(it->value[0]); } // If datadir is changed in .conf file: ClearDatadirCache(); } boost::filesystem::path GetPidFile() { boost::filesystem::path pathPidFile(GetArg("-pid", "blackcoind.pid")); if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile; return pathPidFile; } #ifndef WIN32 void CreatePidFile(const boost::filesystem::path &path, pid_t pid) { FILE* file = fopen(path.string().c_str(), "w"); if (file) { fprintf(file, "%d\n", pid); fclose(file); } } #endif bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest) { #ifdef WIN32 return MoveFileExA(src.string().c_str(), dest.string().c_str(), MOVEFILE_REPLACE_EXISTING); #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } void FileCommit(FILE *fileout) { fflush(fileout); // harmless if redundantly called #ifdef WIN32 _commit(_fileno(fileout)); #else fsync(fileno(fileout)); #endif } void ShrinkDebugFile() { // Scroll debug.log if it's getting too big boost::filesystem::path pathLog = GetDataDir() / "debug.log"; FILE* file = fopen(pathLog.string().c_str(), "r"); if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000) { // Restart the file with some of the end char pch[200000]; fseek(file, -sizeof(pch), SEEK_END); int nBytes = fread(pch, 1, sizeof(pch), file); fclose(file); file = fopen(pathLog.string().c_str(), "w"); if (file) { fwrite(pch, 1, nBytes, file); fclose(file); } } } static int64_t nMockTime = 0; // For unit testing int64_t GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64_t nMockTimeIn) { nMockTime = nMockTimeIn; } uint32_t insecure_rand_Rz = 11; uint32_t insecure_rand_Rw = 11; void seed_insecure_rand(bool fDeterministic) { //The seed values have some unlikely fixed points which we avoid. if(fDeterministic) { insecure_rand_Rz = insecure_rand_Rw = 11; } else { uint32_t tmp; do{ RAND_bytes((unsigned char*)&tmp,4); }while(tmp==0 || tmp==0x9068ffffU); insecure_rand_Rz=tmp; do{ RAND_bytes((unsigned char*)&tmp,4); }while(tmp==0 || tmp==0x464fffffU); insecure_rand_Rw=tmp; } } string FormatVersion(int nVersion) { if (nVersion%100 == 0) return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100); else return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100); } string FormatFullVersion() { return CLIENT_BUILD; } // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014) std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) ss << "(" << boost::algorithm::join(comments, "; ") << ")"; ss << "/"; return ss.str(); } #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate) { namespace fs = boost::filesystem; char pszPath[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n"); return fs::path(""); } #endif void runCommand(std::string strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__)) // TODO: This is currently disabled because it needs to be verified to work // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be // removed. pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED) // pthread_setname_np is XCode 10.6-and-later #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 pthread_setname_np(name); #endif #else // Prevent warnings for unused parameters... (void)name; #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { // std::locale takes ownership of the pointer std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); }
#include "JuceHeader.h" #include "HandleEditor.h" #include "Utilities.h" //============================================================================== HandleEditor::HandleEditor (AudioProcessorValueTreeState& s) : state (s) { for (auto i {0}; i < 8; ++i) { const auto bandEnabledParameterName = ParameterNames::enabled + "_band" + std::to_string (i); state.addParameterListener (bandEnabledParameterName, this); if (*dynamic_cast<AudioParameterBool*> (state.getParameter (bandEnabledParameterName)) == true) addAndMakeVisible (handles.add (new BandHandle (i, state))); } } HandleEditor::~HandleEditor() { for (auto i {0}; i < 8; ++i) state.removeParameterListener (ParameterNames::enabled + "_band" + std::to_string (i), this); } //============================================================================== void HandleEditor::paint (Graphics& g) { } //============================================================================== void HandleEditor::parameterChanged (const String& parameterId, float newValue) { const auto bandId = parameterId.getLastCharacters (1).getIntValue(); if (MessageManager::getInstance()->isThisTheMessageThread()) updateHandle (bandId, newValue > 0.5 ? true : false); else { MessageManager::callAsync ([this, bandId, newValue] { updateHandle (bandId, newValue > 0.5 ? true : false); }); } } void HandleEditor::updateHandle (int bandId, bool shouldAdd) { if (shouldAdd == true) addAndMakeVisible (handles.add (new BandHandle (bandId, state))); else { handles.removeObject (*std::find_if (handles.begin(), handles.end(), [bandId] (BandHandle* handle) { return handle->getBandId() == bandId; })); resized(); } } //============================================================================== void HandleEditor::mouseDown (const MouseEvent& event) { mouseDownPosition = event.position; } void HandleEditor::mouseDoubleClick (const MouseEvent& event) { if (event.originalComponent != this) return; for (auto i {0}; i < 8; ++i) { const auto enabledParamName = ParameterNames::enabled + "_band" + std::to_string (i); if (auto* enabledParam = dynamic_cast<AudioParameterBool*> (state.getParameter (enabledParamName)); *enabledParam == false) { enabledParam->setValueNotifyingHost (true); const auto proportionalWidth = event.position.x / double (getWidth()); const auto proportionalHeight = event.position.y / (double) getHeight(); auto* frequencyParam = static_cast<AudioParameterFloat*> (state.getParameter (ParameterNames::frequency + "_band" + std::to_string (i))); auto* gainParam = static_cast<AudioParameterFloat*> (state.getParameter (ParameterNames::gain + "_band" + std::to_string (i))); frequencyParam->setValueNotifyingHost (proportionalWidth); gainParam->setValueNotifyingHost (1.0f - proportionalHeight); return; } } }
/*============================================================================= Copyright (c) 2001-2003 Joel de Guzman Copyright (c) 2002-2003 Hartmut Kaiser http://spirit.sourceforge.net/ 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) =============================================================================*/ #if !defined(BOOST_SPIRIT_ATTRIBUTE_MAIN_HPP) #define BOOST_SPIRIT_ATTRIBUTE_MAIN_HPP #include <boost/spirit/home/classic/version.hpp> /////////////////////////////////////////////////////////////////////////////// // // Master header for Spirit.Attributes // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // Phoenix predefined maximum limit. This limit defines the maximum // number of elements a tuple can hold. This number defaults to 3. The // actual maximum is rounded up in multiples of 3. Thus, if this value // is 4, the actual limit is 6. The ultimate maximum limit in this // implementation is 15. // /////////////////////////////////////////////////////////////////////////////// #if !defined(PHOENIX_LIMIT) #define PHOENIX_LIMIT 6 #endif // !defined(PHOENIX_LIMIT) /////////////////////////////////////////////////////////////////////////////// #include <boost/spirit/home/classic/attribute/closure.hpp> #include <boost/spirit/home/classic/attribute/parametric.hpp> #endif // !defined(BOOST_SPIRIT_ATTRIBUTE_MAIN_HPP)
#include <bits/stdc++.h> using namespace std; /* * par[i] = parent of i in the centroid tree * level[i] = depth of the i'th node in the original tree * sz[i] = sz of the subtree rooted at i * erased[i] = if i has already been chosen as the centroid in the past, it is erased * jump[i][j] = 2^ith ancestor of j * g[i] = original adjacency list of i * cg[i] = centroid tree adjacency list * st, tp = stack and pointer to the top */ const int LOGN = 17; const int N = 1<<LOGN; int par[N], level[N], sz[N], erased[N]; int jump[LOGN][N]; vector<int> g[N]; vector<int> cg[N]; int st[N], tp; void dfs(int u){ jump[0][u] = u, level[u] = 0, tp = 0; st[tp++] = u; while(tp-1 >= 0){ u = st[--tp]; foreach(it, g[u]){ if(*it == dp[0][u]) continue; dp[0][*it] = u; level[*it] = level[u] + 1; st[tp++] = *it; } } return; } int totalNodes; void getSize(int u, int prev){ sz[u] = 1, ++totalNodes; foreach(it, g[u]){ if(*it == prev or erased[*it]) continue; getSize(*it, u); sz[u] += sz[*it]; } return; } int getCentroid(int u, int prev){ foreach(it, g[u]) if(!erased[*it] and *it != prev and sz[*it] > totalNodes/2) return getCentroid(*it, u); return u; } void decompose(int root, int prev){ totalNodes = 0; getSize(root, root); int centroid = getCentroid(root, root); if(prev == -1) par[centroid] = centroid; else{ par[centroid] = prev; cg[prev].pb(centroid); } erased[centroid] = 1; foreach(it, g[centroid]) if(!erased[*it]) decompose(*it, centroid); return; } void preprocess(int u){ dfs(u); for(int i = 1; i < LOGN; i++) for(int j = 1; j <= n; j++) jump[i][j] = jump[i-1][jump[i-1][j]]; return; } int lca(int u, int v){ if(level[u] > level[v]) swap(u,v); int diff = level[v]-level[u]; for(int i = 0; i < LOGN; i++) if((diff&(1<<i))) v = jump[i][v]; if(u == v) return u; for(int i = LOGN-1; i >= 0; i--) if(jump[i][u] != jump[i][v]) u = jump[i][u], v = jump[i][v]; return jump[0][u]; } int dist(int u, int v){ return level[u] + level[v] - 2*level[lca(u,v)]; } int main(){ // TODO - 1 is the root, -1 is the prev preprocess(1); decompose(1, -1); return 0; }
/* * File: spi.cpp * Author: Purinda Gunasekara <purinda@gmail.com> * * Created on 24 June 2012, 11:00 AM * * Patched for exception handling and selectable SPI SPEED by ldiaz 2018. * * Inspired from spidev test in linux kernel documentation * www.kernel.org/doc/Documentation/spi/spidev_test.c */ #include "spi.h" #include <fcntl.h> #include <linux/spi/spidev.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <unistd.h> #define RF24_SPIDEV_BITS 8 SPI::SPI() :fd(-1), _spi_speed(RF24_SPIDEV_SPEED) { } bool spiIsInitialized = 0; void SPI::begin(int busNo, uint32_t spi_speed) { if (spiIsInitialized) { return; } /* set spidev accordingly to busNo like: * busNo = 23 -> /dev/spidev2.3 * * a bit messy but simple * */ char device[] = "/dev/spidev0.0"; device[11] += (busNo / 10) % 10; device[13] += busNo % 10; if (this->fd >= 0) // check whether spi is already open { close(this->fd); this->fd = -1; } this->fd = open(device, O_RDWR); if (this->fd < 0) { throw SPIException("can't open device"); } /* { perror("can't open device"); abort(); }*/ spiIsInitialized = true; init(spi_speed); } void SPI::init(uint32_t speed) { uint8_t bits = RF24_SPIDEV_BITS; uint8_t mode = 0; int ret; /* * spi mode */ ret = ioctl(this->fd, SPI_IOC_WR_MODE, &mode); if (ret == -1) { throw SPIException("cant set WR spi mode"); } /*{ perror("can't set spi mode"); abort(); }*/ ret = ioctl(this->fd, SPI_IOC_RD_MODE, &mode); if (ret == -1) { throw SPIException("can't set RD spi mode"); } /*{ perror("can't set spi mode"); abort(); }*/ /* * bits per word */ ret = ioctl(this->fd, SPI_IOC_WR_BITS_PER_WORD, &bits); if (ret == -1) { throw SPIException("can't set WR bits per word"); } /*{ perror("can't set bits per word"); abort(); }*/ ret = ioctl(this->fd, SPI_IOC_RD_BITS_PER_WORD, &bits); if (ret == -1) { throw SPIException("can't set RD bits per word"); } /*{ perror("can't set bits per word"); abort(); }*/ /* * max speed hz */ ret = ioctl(this->fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed); if (ret == -1) { throw SPIException("can't WR set max speed hz"); } /*{ perror("can't set max speed hz"); abort(); }*/ ret = ioctl(this->fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed); if (ret == -1) { throw SPIException("can't RD set max speed hz"); } /*{ perror("can't set max speed hz"); abort(); }*/ _spi_speed = speed; } uint8_t SPI::transfer(uint8_t tx) { struct spi_ioc_transfer tr; memset(&tr, 0, sizeof(tr)); tr.tx_buf = (unsigned long) &tx; uint8_t rx; tr.rx_buf = (unsigned long) &rx; tr.len = sizeof(tx); tr.speed_hz = _spi_speed; //RF24_SPIDEV_SPEED; tr.delay_usecs = 0; tr.bits_per_word = RF24_SPIDEV_BITS; tr.cs_change = 0; int ret; ret = ioctl(this->fd, SPI_IOC_MESSAGE(1), &tr); if (ret < 1) { throw SPIException("can't send spi message"); } /*{ perror("can't send spi message"); abort(); }*/ return rx; } void SPI::transfernb(char* tbuf, char* rbuf, uint32_t len) { struct spi_ioc_transfer tr; memset(&tr, 0, sizeof(tr)); tr.tx_buf = (unsigned long) tbuf; tr.rx_buf = (unsigned long) rbuf; tr.len = len; tr.speed_hz = _spi_speed; //RF24_SPIDEV_SPEED; tr.delay_usecs = 0; tr.bits_per_word = RF24_SPIDEV_BITS; tr.cs_change = 0; int ret; ret = ioctl(this->fd, SPI_IOC_MESSAGE(1), &tr); if (ret < 1) { throw SPIException("can't send spi message"); } /*{ perror("can't send spi message"); abort(); }*/ } SPI::~SPI() { if (this->fd >= 0) { close(this->fd); } }
// Copyright 2020 Google LLC // // 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 // // https://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. // ----------------------------------------------------------------------------- // // WebP encode. // // Author: Yannis Guyon (yguyon@google.com) #include <cstdio> #include <cmath> #ifdef HAVE_CONFIG_H #include "wp2/config.h" #endif #include "./image_enc.h" #include "./imageio_util.h" #include "src/dsp/math.h" #include "src/utils/utils.h" #include "src/wp2/format_constants.h" #ifdef WP2_HAVE_WEBP #include "webp/encode.h" #endif namespace WP2 { // ----------------------------------------------------------------------------- #if defined(WP2_HAVE_WEBP) static int WriterFunc(const uint8_t* data, size_t data_size, const WebPPicture* picture) { Writer* const writer = reinterpret_cast<Writer*>(picture->custom_ptr); return writer->Append(data, data_size) ? 1 : 0; } WP2Status CompressWebP(const ArgbBuffer& buffer, const WebPConfig& config, Writer* const output) { WP2_CHECK_OK(!buffer.IsEmpty(), WP2_STATUS_INVALID_PARAMETER); WP2_CHECK_OK(output != nullptr, WP2_STATUS_NULL_PARAMETER); WP2_CHECK_OK(WebPValidateConfig(&config), WP2_STATUS_INVALID_CONFIGURATION); // Convert WP2::ArgbBuffer to WebPPicture WebPPicture picture; WP2_CHECK_STATUS(ConvertToWebPPicture(buffer, &picture)); picture.writer = WriterFunc; picture.custom_ptr = reinterpret_cast<void*>(output); WP2_CHECK_OK(WebPEncode(&config, &picture), WP2_STATUS_INVALID_PARAMETER); WebPPictureFree(&picture); return WP2_STATUS_OK; } WP2Status CompressWebP(const ArgbBuffer& buffer, float quality, int speed, Writer* const output) { WebPConfig config; WP2_CHECK_OK(WebPConfigInit(&config), WP2_STATUS_VERSION_MISMATCH); // Map wp2 'quality' in [lossy:kMaxLossyQuality:kMaxQuality] // to WebP in [lossy:near-lossless:lossless]. if (quality <= (float)kMaxLossyQuality) { config.quality = Clamp((quality / kMaxLossyQuality) * 100.f, 0.f, 100.f); } else { WP2_CHECK_OK(WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, quality), WP2_STATUS_VERSION_MISMATCH); config.lossless = 1; config.near_lossless = Clamp<int>(std::lround(((quality - kMaxLossyQuality) / (kMaxQuality - kMaxLossyQuality)) * 100.f), 0, 100); config.exact = (config.near_lossless == 100); config.quality = Clamp(speed / 9.f * 100.f, 0.f, 100.f); } config.method = Clamp(DivRound(speed * 6, 9), 0, 6); WP2_CHECK_STATUS(CompressWebP(buffer, config, output)); return WP2_STATUS_OK; } #else WP2Status CompressWebP(const ArgbBuffer&, float, int, Writer*) { return WP2_STATUS_UNSUPPORTED_FEATURE; } #endif // defined(WP2_HAVE_WEBP) // ----------------------------------------------------------------------------- } // namespace WP2
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/unittest_embed_optimize_for.proto #include "google/protobuf/unittest_embed_optimize_for.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace protobuf_unittest { constexpr TestEmbedOptimizedForSize::TestEmbedOptimizedForSize( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : repeated_message_() , optional_message_(nullptr){} struct TestEmbedOptimizedForSizeDefaultTypeInternal { constexpr TestEmbedOptimizedForSizeDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~TestEmbedOptimizedForSizeDefaultTypeInternal() {} union { TestEmbedOptimizedForSize _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT TestEmbedOptimizedForSizeDefaultTypeInternal _TestEmbedOptimizedForSize_default_instance_; } // namespace protobuf_unittest static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestEmbedOptimizedForSize, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestEmbedOptimizedForSize, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestEmbedOptimizedForSize, optional_message_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestEmbedOptimizedForSize, repeated_message_), 0, ~0u, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 8, -1, sizeof(::protobuf_unittest::TestEmbedOptimizedForSize)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::protobuf_unittest::_TestEmbedOptimizedForSize_default_instance_), }; const char descriptor_table_protodef_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n1google/protobuf/unittest_embed_optimiz" "e_for.proto\022\021protobuf_unittest\032+google/p" "rotobuf/unittest_optimize_for.proto\"\241\001\n\031" "TestEmbedOptimizedForSize\022A\n\020optional_me" "ssage\030\001 \001(\0132\'.protobuf_unittest.TestOpti" "mizedForSize\022A\n\020repeated_message\030\002 \003(\0132\'" ".protobuf_unittest.TestOptimizedForSizeB" "\002H\001" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto_deps[1] = { &::descriptor_table_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto = { false, false, 283, descriptor_table_protodef_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto, "google/protobuf/unittest_embed_optimize_for.proto", &descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto_once, descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto_deps, 1, 1, schemas, file_default_instances, TableStruct_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto::offsets, file_level_metadata_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto, file_level_enum_descriptors_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto, file_level_service_descriptors_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto(&descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto); namespace protobuf_unittest { // =================================================================== class TestEmbedOptimizedForSize::_Internal { public: using HasBits = decltype(std::declval<TestEmbedOptimizedForSize>()._has_bits_); static const ::protobuf_unittest::TestOptimizedForSize& optional_message(const TestEmbedOptimizedForSize* msg); static void set_has_optional_message(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; const ::protobuf_unittest::TestOptimizedForSize& TestEmbedOptimizedForSize::_Internal::optional_message(const TestEmbedOptimizedForSize* msg) { return *msg->optional_message_; } void TestEmbedOptimizedForSize::clear_optional_message() { if (optional_message_ != nullptr) optional_message_->Clear(); _has_bits_[0] &= ~0x00000001u; } void TestEmbedOptimizedForSize::clear_repeated_message() { repeated_message_.Clear(); } TestEmbedOptimizedForSize::TestEmbedOptimizedForSize(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), repeated_message_(arena) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestEmbedOptimizedForSize) } TestEmbedOptimizedForSize::TestEmbedOptimizedForSize(const TestEmbedOptimizedForSize& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), repeated_message_(from.repeated_message_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_optional_message()) { optional_message_ = new ::protobuf_unittest::TestOptimizedForSize(*from.optional_message_); } else { optional_message_ = nullptr; } // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestEmbedOptimizedForSize) } inline void TestEmbedOptimizedForSize::SharedCtor() { optional_message_ = nullptr; } TestEmbedOptimizedForSize::~TestEmbedOptimizedForSize() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestEmbedOptimizedForSize) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void TestEmbedOptimizedForSize::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete optional_message_; } void TestEmbedOptimizedForSize::ArenaDtor(void* object) { TestEmbedOptimizedForSize* _this = reinterpret_cast< TestEmbedOptimizedForSize* >(object); (void)_this; } void TestEmbedOptimizedForSize::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TestEmbedOptimizedForSize::SetCachedSize(int size) const { _cached_size_.Set(size); } void TestEmbedOptimizedForSize::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestEmbedOptimizedForSize) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; repeated_message_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(optional_message_ != nullptr); optional_message_->Clear(); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* TestEmbedOptimizedForSize::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .protobuf_unittest.TestOptimizedForSize optional_message = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_optional_message(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .protobuf_unittest.TestOptimizedForSize repeated_message = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_repeated_message(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<18>(ptr)); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TestEmbedOptimizedForSize::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestEmbedOptimizedForSize) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .protobuf_unittest.TestOptimizedForSize optional_message = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 1, _Internal::optional_message(this), target, stream); } // repeated .protobuf_unittest.TestOptimizedForSize repeated_message = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_repeated_message_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(2, this->_internal_repeated_message(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestEmbedOptimizedForSize) return target; } size_t TestEmbedOptimizedForSize::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestEmbedOptimizedForSize) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .protobuf_unittest.TestOptimizedForSize repeated_message = 2; total_size += 1UL * this->_internal_repeated_message_size(); for (const auto& msg : this->repeated_message_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // optional .protobuf_unittest.TestOptimizedForSize optional_message = 1; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *optional_message_); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData TestEmbedOptimizedForSize::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, TestEmbedOptimizedForSize::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*TestEmbedOptimizedForSize::GetClassData() const { return &_class_data_; } void TestEmbedOptimizedForSize::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<TestEmbedOptimizedForSize *>(to)->MergeFrom( static_cast<const TestEmbedOptimizedForSize &>(from)); } void TestEmbedOptimizedForSize::MergeFrom(const TestEmbedOptimizedForSize& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestEmbedOptimizedForSize) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; repeated_message_.MergeFrom(from.repeated_message_); if (from._internal_has_optional_message()) { _internal_mutable_optional_message()->::protobuf_unittest::TestOptimizedForSize::MergeFrom(from._internal_optional_message()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void TestEmbedOptimizedForSize::CopyFrom(const TestEmbedOptimizedForSize& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestEmbedOptimizedForSize) if (&from == this) return; Clear(); MergeFrom(from); } bool TestEmbedOptimizedForSize::IsInitialized() const { if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(repeated_message_)) return false; if (_internal_has_optional_message()) { if (!optional_message_->IsInitialized()) return false; } return true; } void TestEmbedOptimizedForSize::InternalSwap(TestEmbedOptimizedForSize* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); repeated_message_.InternalSwap(&other->repeated_message_); swap(optional_message_, other->optional_message_); } ::PROTOBUF_NAMESPACE_ID::Metadata TestEmbedOptimizedForSize::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fembed_5foptimize_5ffor_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace protobuf_unittest PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestEmbedOptimizedForSize* Arena::CreateMaybeMessage< ::protobuf_unittest::TestEmbedOptimizedForSize >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::TestEmbedOptimizedForSize >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
// Copyright (c) 2012-2014 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 "clientversion.h" #include "tinyformat.h" #include <string> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-core, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Zerozed"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include "build.h" #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "$Format:%h$" #define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
//===--- CodeCompletion.cpp - Code completion implementation --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 "swift/IDE/CodeCompletion.h" #include "CodeCompletionResultBuilder.h" #include "ExprContextAnalysis.h" #include "swift/AST/ASTPrinter.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Comment.h" #include "swift/AST/ImportCache.h" #include "swift/AST/Initializer.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/LazyResolver.h" #include "swift/AST/NameLookup.h" #include "swift/AST/ParameterList.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/SourceFile.h" #include "swift/AST/SubstitutionMap.h" #include "swift/AST/USRGeneration.h" #include "swift/Basic/Defer.h" #include "swift/Basic/LLVM.h" #include "swift/ClangImporter/ClangImporter.h" #include "swift/ClangImporter/ClangModule.h" #include "swift/Frontend/FrontendOptions.h" #include "swift/IDE/CodeCompletionCache.h" #include "swift/IDE/CodeCompletionResultPrinter.h" #include "swift/IDE/Utils.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Sema/IDETypeChecking.h" #include "swift/Sema/CodeCompletionTypeChecking.h" #include "swift/Syntax/SyntaxKind.h" #include "swift/Strings.h" #include "swift/Subsystems.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/Comment.h" #include "clang/AST/CommentVisitor.h" #include "clang/AST/Decl.h" #include "clang/Basic/Module.h" #include "clang/Index/USRGeneration.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SaveAndRestore.h" #include <algorithm> #include <string> using namespace swift; using namespace ide; using CommandWordsPairs = std::vector<std::pair<StringRef, StringRef>>; using NotRecommendedReason = CodeCompletionResult::NotRecommendedReason; enum CodeCompletionCommandKind { none, keyword, recommended, recommendedover, mutatingvariant, nonmutatingvariant, }; CodeCompletionCommandKind getCommandKind(StringRef Command) { #define CHECK_CASE(KIND) \ if (Command == #KIND) \ return CodeCompletionCommandKind::KIND; CHECK_CASE(keyword); CHECK_CASE(recommended); CHECK_CASE(recommendedover); CHECK_CASE(mutatingvariant); CHECK_CASE(nonmutatingvariant); #undef CHECK_CASE return CodeCompletionCommandKind::none; } StringRef getCommandName(CodeCompletionCommandKind Kind) { #define CHECK_CASE(KIND) \ if (CodeCompletionCommandKind::KIND == Kind) { \ static std::string Name(#KIND); \ return Name; \ } CHECK_CASE(keyword) CHECK_CASE(recommended) CHECK_CASE(recommendedover) CHECK_CASE(mutatingvariant); CHECK_CASE(nonmutatingvariant); #undef CHECK_CASE llvm_unreachable("Cannot handle this Kind."); } bool containsInterestedWords(StringRef Content, StringRef Splitter, bool AllowWhitespace) { do { Content = Content.split(Splitter).second; Content = AllowWhitespace ? Content.trim() : Content; #define CHECK_CASE(KIND) \ if (Content.startswith(#KIND)) \ return true; CHECK_CASE(keyword) CHECK_CASE(recommended) CHECK_CASE(recommendedover) CHECK_CASE(mutatingvariant); CHECK_CASE(nonmutatingvariant); #undef CHECK_CASE } while (!Content.empty()); return false; } void splitTextByComma(StringRef Text, std::vector<StringRef>& Subs) { do { auto Pair = Text.split(','); auto Key = Pair.first.trim(); if (!Key.empty()) Subs.push_back(Key); Text = Pair.second; } while (!Text.empty()); } namespace clang { namespace comments { class WordPairsArrangedViewer { ArrayRef<std::pair<StringRef, StringRef>> Content; std::vector<StringRef> ViewedText; std::vector<StringRef> Words; StringRef Key; bool isKeyViewed(StringRef K) { return std::find(ViewedText.begin(), ViewedText.end(), K) != ViewedText.end(); } public: WordPairsArrangedViewer(ArrayRef<std::pair<StringRef, StringRef>> Content): Content(Content) {} bool hasNext() { Words.clear(); bool Found = false; for (auto P : Content) { if (!Found && !isKeyViewed(P.first)) { Key = P.first; Found = true; } if (Found && P.first == Key) Words.push_back(P.second); } return Found; } std::pair<StringRef, ArrayRef<StringRef>> next() { bool HasNext = hasNext(); (void) HasNext; assert(HasNext && "Have no more data."); ViewedText.push_back(Key); return std::make_pair(Key, llvm::makeArrayRef(Words)); } }; class ClangCommentExtractor : public ConstCommentVisitor<ClangCommentExtractor> { CommandWordsPairs &Words; const CommandTraits &Traits; std::vector<const Comment *> Parents; void visitChildren(const Comment* C) { Parents.push_back(C); for (auto It = C->child_begin(); It != C->child_end(); ++ It) visit(*It); Parents.pop_back(); } public: ClangCommentExtractor(CommandWordsPairs &Words, const CommandTraits &Traits) : Words(Words), Traits(Traits) {} #define CHILD_VISIT(NAME) \ void visit##NAME(const NAME *C) {\ visitChildren(C);\ } CHILD_VISIT(FullComment) CHILD_VISIT(ParagraphComment) #undef CHILD_VISIT void visitInlineCommandComment(const InlineCommandComment *C) { auto Command = C->getCommandName(Traits); auto CommandKind = getCommandKind(Command); if (CommandKind == CodeCompletionCommandKind::none) return; auto &Parent = Parents.back(); for (auto CIT = std::find(Parent->child_begin(), Parent->child_end(), C) + 1; CIT != Parent->child_end(); ++CIT) { if (auto TC = dyn_cast<TextComment>(*CIT)) { auto Text = TC->getText(); std::vector<StringRef> Subs; splitTextByComma(Text, Subs); auto Kind = getCommandName(CommandKind); for (auto S : Subs) Words.push_back(std::make_pair(Kind, S)); } else break; } } }; void getClangDocKeyword(ClangImporter &Importer, const Decl *D, CommandWordsPairs &Words) { ClangCommentExtractor Extractor(Words, Importer.getClangASTContext(). getCommentCommandTraits()); if (auto RC = Importer.getClangASTContext().getRawCommentForAnyRedecl(D)) { auto RT = RC->getRawText(Importer.getClangASTContext().getSourceManager()); if (containsInterestedWords(RT, "@", /*AllowWhitespace*/false)) { FullComment* Comment = Importer.getClangASTContext(). getLocalCommentForDeclUncached(D); Extractor.visit(Comment); } } } } // end namespace comments } // end namespace clang namespace swift { namespace markup { class SwiftDocWordExtractor : public MarkupASTWalker { CommandWordsPairs &Pairs; CodeCompletionCommandKind Kind; public: SwiftDocWordExtractor(CommandWordsPairs &Pairs) : Pairs(Pairs), Kind(CodeCompletionCommandKind::none) {} void visitKeywordField(const KeywordField *Field) override { Kind = CodeCompletionCommandKind::keyword; } void visitRecommendedField(const RecommendedField *Field) override { Kind = CodeCompletionCommandKind::recommended; } void visitRecommendedoverField(const RecommendedoverField *Field) override { Kind = CodeCompletionCommandKind::recommendedover; } void visitMutatingvariantField(const MutatingvariantField *Field) override { Kind = CodeCompletionCommandKind::mutatingvariant; } void visitNonmutatingvariantField(const NonmutatingvariantField *Field) override { Kind = CodeCompletionCommandKind::nonmutatingvariant; } void visitText(const Text *Text) override { if (Kind == CodeCompletionCommandKind::none) return; StringRef CommandName = getCommandName(Kind); std::vector<StringRef> Subs; splitTextByComma(Text->str(), Subs); for (auto S : Subs) Pairs.push_back(std::make_pair(CommandName, S)); } }; void getSwiftDocKeyword(const Decl* D, CommandWordsPairs &Words) { auto Interested = false; for (auto C : D->getRawComment(/*SerializedOK=*/false).Comments) { if (containsInterestedWords(C.RawText, "-", /*AllowWhitespace*/true)) { Interested = true; break; } } if (!Interested) return; static swift::markup::MarkupContext MC; auto DC = getSingleDocComment(MC, D); if (!DC) return; SwiftDocWordExtractor Extractor(Words); for (auto Part : DC->getBodyNodes()) { switch (Part->getKind()) { case ASTNodeKind::KeywordField: case ASTNodeKind::RecommendedField: case ASTNodeKind::RecommendedoverField: case ASTNodeKind::MutatingvariantField: case ASTNodeKind::NonmutatingvariantField: Extractor.walk(Part); break; default: break; } } } } // end namespace markup } // end namespace swift using DeclFilter = std::function<bool(ValueDecl *, DeclVisibilityKind)>; static bool DefaultFilter(ValueDecl* VD, DeclVisibilityKind Kind) { return true; } static bool KeyPathFilter(ValueDecl* decl, DeclVisibilityKind) { return isa<TypeDecl>(decl) || (isa<VarDecl>(decl) && decl->getDeclContext()->isTypeContext()); } static bool SwiftKeyPathFilter(ValueDecl* decl, DeclVisibilityKind) { switch(decl->getKind()){ case DeclKind::Var: case DeclKind::Subscript: return true; default: return false; } } std::string swift::ide::removeCodeCompletionTokens( StringRef Input, StringRef TokenName, unsigned *CompletionOffset) { assert(TokenName.size() >= 1); *CompletionOffset = ~0U; std::string CleanFile; CleanFile.reserve(Input.size()); const std::string Token = std::string("#^") + TokenName.str() + "^#"; for (const char *Ptr = Input.begin(), *End = Input.end(); Ptr != End; ++Ptr) { const char C = *Ptr; if (C == '#' && Ptr <= End - Token.size() && StringRef(Ptr, Token.size()) == Token) { Ptr += Token.size() - 1; *CompletionOffset = CleanFile.size(); CleanFile += '\0'; continue; } if (C == '#' && Ptr <= End - 2 && Ptr[1] == '^') { do { ++Ptr; } while (Ptr < End && *Ptr != '#'); if (Ptr == End) break; continue; } CleanFile += C; } return CleanFile; } llvm::StringRef swift::ide::copyString(llvm::BumpPtrAllocator &Allocator, llvm::StringRef Str) { char *Buffer = Allocator.Allocate<char>(Str.size()); std::copy(Str.begin(), Str.end(), Buffer); return llvm::StringRef(Buffer, Str.size()); } const char *swift::ide::copyCString(llvm::BumpPtrAllocator &Allocator, llvm::StringRef Str) { char *Buffer = Allocator.Allocate<char>(Str.size() + 1); std::copy(Str.begin(), Str.end(), Buffer); Buffer[Str.size()] = '\0'; return Buffer; } CodeCompletionString::CodeCompletionString(ArrayRef<Chunk> Chunks) { std::uninitialized_copy(Chunks.begin(), Chunks.end(), getTrailingObjects<Chunk>()); NumChunks = Chunks.size(); } CodeCompletionString *CodeCompletionString::create(llvm::BumpPtrAllocator &Allocator, ArrayRef<Chunk> Chunks) { void *CCSMem = Allocator.Allocate(totalSizeToAlloc<Chunk>(Chunks.size()), alignof(CodeCompletionString)); return new (CCSMem) CodeCompletionString(Chunks); } void CodeCompletionString::print(raw_ostream &OS) const { unsigned PrevNestingLevel = 0; auto chunks = getChunks(); for (auto I = chunks.begin(), E = chunks.end(); I != E; ++I) { bool AnnotatedTextChunk = false; if (I->getNestingLevel() < PrevNestingLevel) { OS << "#}"; } switch (I->getKind()) { using ChunkKind = Chunk::ChunkKind; case ChunkKind::AccessControlKeyword: case ChunkKind::DeclAttrKeyword: case ChunkKind::DeclAttrParamKeyword: case ChunkKind::OverrideKeyword: case ChunkKind::EffectsSpecifierKeyword: case ChunkKind::DeclIntroducer: case ChunkKind::Text: case ChunkKind::LeftParen: case ChunkKind::RightParen: case ChunkKind::LeftBracket: case ChunkKind::RightBracket: case ChunkKind::LeftAngle: case ChunkKind::RightAngle: case ChunkKind::Dot: case ChunkKind::Ellipsis: case ChunkKind::Comma: case ChunkKind::ExclamationMark: case ChunkKind::QuestionMark: case ChunkKind::Ampersand: case ChunkKind::Equal: case ChunkKind::Whitespace: case ChunkKind::Keyword: case ChunkKind::Attribute: case ChunkKind::BaseName: case ChunkKind::TypeIdSystem: case ChunkKind::TypeIdUser: AnnotatedTextChunk = I->isAnnotation(); LLVM_FALLTHROUGH; case ChunkKind::CallParameterName: case ChunkKind::CallParameterInternalName: case ChunkKind::CallParameterColon: case ChunkKind::DeclAttrParamColon: case ChunkKind::CallParameterType: case ChunkKind::CallParameterClosureType: case ChunkKind::GenericParameterName: if (AnnotatedTextChunk) OS << "['"; else if (I->getKind() == ChunkKind::CallParameterInternalName) OS << "("; else if (I->getKind() == ChunkKind::CallParameterClosureType) OS << "##"; for (char Ch : I->getText()) { if (Ch == '\n') OS << "\\n"; else OS << Ch; } if (AnnotatedTextChunk) OS << "']"; else if (I->getKind() == ChunkKind::CallParameterInternalName) OS << ")"; break; case ChunkKind::OptionalBegin: case ChunkKind::CallParameterBegin: case ChunkKind::CallParameterTypeBegin: case ChunkKind::GenericParameterBegin: OS << "{#"; break; case ChunkKind::DynamicLookupMethodCallTail: case ChunkKind::OptionalMethodCallTail: OS << I->getText(); break; case ChunkKind::TypeAnnotationBegin: { OS << "[#"; ++I; auto level = I->getNestingLevel(); for (; I != E && !I->endsPreviousNestedGroup(level); ++I) if (I->hasText()) OS << I->getText(); --I; OS << "#]"; continue; } case ChunkKind::TypeAnnotation: OS << "[#"; OS << I->getText(); OS << "#]"; break; case ChunkKind::CallParameterClosureExpr: OS << " {" << I->getText() << "|}"; break; case ChunkKind::BraceStmtWithCursor: OS << " {|}"; break; } PrevNestingLevel = I->getNestingLevel(); } while (PrevNestingLevel > 0) { OS << "#}"; --PrevNestingLevel; } } void CodeCompletionString::dump() const { print(llvm::errs()); } CodeCompletionDeclKind CodeCompletionResult::getCodeCompletionDeclKind(const Decl *D) { switch (D->getKind()) { case DeclKind::Import: case DeclKind::Extension: case DeclKind::PatternBinding: case DeclKind::EnumCase: case DeclKind::TopLevelCode: case DeclKind::IfConfig: case DeclKind::PoundDiagnostic: case DeclKind::MissingMember: case DeclKind::OpaqueType: llvm_unreachable("not expecting such a declaration result"); case DeclKind::Module: return CodeCompletionDeclKind::Module; case DeclKind::TypeAlias: return CodeCompletionDeclKind::TypeAlias; case DeclKind::AssociatedType: return CodeCompletionDeclKind::AssociatedType; case DeclKind::GenericTypeParam: return CodeCompletionDeclKind::GenericTypeParam; case DeclKind::Enum: return CodeCompletionDeclKind::Enum; case DeclKind::Struct: return CodeCompletionDeclKind::Struct; case DeclKind::Class: return CodeCompletionDeclKind::Class; case DeclKind::Protocol: return CodeCompletionDeclKind::Protocol; case DeclKind::Var: case DeclKind::Param: { auto DC = D->getDeclContext(); if (DC->isTypeContext()) { if (cast<VarDecl>(D)->isStatic()) return CodeCompletionDeclKind::StaticVar; else return CodeCompletionDeclKind::InstanceVar; } if (DC->isLocalContext()) return CodeCompletionDeclKind::LocalVar; return CodeCompletionDeclKind::GlobalVar; } case DeclKind::Constructor: return CodeCompletionDeclKind::Constructor; case DeclKind::Destructor: return CodeCompletionDeclKind::Destructor; case DeclKind::Accessor: case DeclKind::Func: { auto DC = D->getDeclContext(); auto FD = cast<FuncDecl>(D); if (DC->isTypeContext()) { if (FD->isStatic()) return CodeCompletionDeclKind::StaticMethod; return CodeCompletionDeclKind::InstanceMethod; } if (FD->isOperator()) { if (auto op = FD->getOperatorDecl()) { switch (op->getKind()) { case DeclKind::PrefixOperator: return CodeCompletionDeclKind::PrefixOperatorFunction; case DeclKind::PostfixOperator: return CodeCompletionDeclKind::PostfixOperatorFunction; case DeclKind::InfixOperator: return CodeCompletionDeclKind::InfixOperatorFunction; default: llvm_unreachable("unexpected operator kind"); } } else { return CodeCompletionDeclKind::InfixOperatorFunction; } } return CodeCompletionDeclKind::FreeFunction; } case DeclKind::InfixOperator: return CodeCompletionDeclKind::InfixOperatorFunction; case DeclKind::PrefixOperator: return CodeCompletionDeclKind::PrefixOperatorFunction; case DeclKind::PostfixOperator: return CodeCompletionDeclKind::PostfixOperatorFunction; case DeclKind::PrecedenceGroup: return CodeCompletionDeclKind::PrecedenceGroup; case DeclKind::EnumElement: return CodeCompletionDeclKind::EnumElement; case DeclKind::Subscript: return CodeCompletionDeclKind::Subscript; } llvm_unreachable("invalid DeclKind"); } bool CodeCompletionResult::getDeclIsSystem(const Decl *D) { return D->getModuleContext()->isSystemModule(); } void CodeCompletionResult::printPrefix(raw_ostream &OS) const { llvm::SmallString<64> Prefix; switch (getKind()) { case ResultKind::Declaration: Prefix.append("Decl"); switch (getAssociatedDeclKind()) { case CodeCompletionDeclKind::Class: Prefix.append("[Class]"); break; case CodeCompletionDeclKind::Struct: Prefix.append("[Struct]"); break; case CodeCompletionDeclKind::Enum: Prefix.append("[Enum]"); break; case CodeCompletionDeclKind::EnumElement: Prefix.append("[EnumElement]"); break; case CodeCompletionDeclKind::Protocol: Prefix.append("[Protocol]"); break; case CodeCompletionDeclKind::TypeAlias: Prefix.append("[TypeAlias]"); break; case CodeCompletionDeclKind::AssociatedType: Prefix.append("[AssociatedType]"); break; case CodeCompletionDeclKind::GenericTypeParam: Prefix.append("[GenericTypeParam]"); break; case CodeCompletionDeclKind::Constructor: Prefix.append("[Constructor]"); break; case CodeCompletionDeclKind::Destructor: Prefix.append("[Destructor]"); break; case CodeCompletionDeclKind::Subscript: Prefix.append("[Subscript]"); break; case CodeCompletionDeclKind::StaticMethod: Prefix.append("[StaticMethod]"); break; case CodeCompletionDeclKind::InstanceMethod: Prefix.append("[InstanceMethod]"); break; case CodeCompletionDeclKind::PrefixOperatorFunction: Prefix.append("[PrefixOperatorFunction]"); break; case CodeCompletionDeclKind::PostfixOperatorFunction: Prefix.append("[PostfixOperatorFunction]"); break; case CodeCompletionDeclKind::InfixOperatorFunction: Prefix.append("[InfixOperatorFunction]"); break; case CodeCompletionDeclKind::FreeFunction: Prefix.append("[FreeFunction]"); break; case CodeCompletionDeclKind::StaticVar: Prefix.append("[StaticVar]"); break; case CodeCompletionDeclKind::InstanceVar: Prefix.append("[InstanceVar]"); break; case CodeCompletionDeclKind::LocalVar: Prefix.append("[LocalVar]"); break; case CodeCompletionDeclKind::GlobalVar: Prefix.append("[GlobalVar]"); break; case CodeCompletionDeclKind::Module: Prefix.append("[Module]"); break; case CodeCompletionDeclKind::PrecedenceGroup: Prefix.append("[PrecedenceGroup]"); break; } break; case ResultKind::Keyword: Prefix.append("Keyword"); switch (getKeywordKind()) { case CodeCompletionKeywordKind::None: break; #define KEYWORD(X) case CodeCompletionKeywordKind::kw_##X: \ Prefix.append("[" #X "]"); \ break; #define POUND_KEYWORD(X) case CodeCompletionKeywordKind::pound_##X: \ Prefix.append("[#" #X "]"); \ break; #include "swift/Syntax/TokenKinds.def" } break; case ResultKind::Pattern: Prefix.append("Pattern"); break; case ResultKind::Literal: Prefix.append("Literal"); switch (getLiteralKind()) { case CodeCompletionLiteralKind::ArrayLiteral: Prefix.append("[Array]"); break; case CodeCompletionLiteralKind::BooleanLiteral: Prefix.append("[Boolean]"); break; case CodeCompletionLiteralKind::ColorLiteral: Prefix.append("[_Color]"); break; case CodeCompletionLiteralKind::ImageLiteral: Prefix.append("[_Image]"); break; case CodeCompletionLiteralKind::DictionaryLiteral: Prefix.append("[Dictionary]"); break; case CodeCompletionLiteralKind::IntegerLiteral: Prefix.append("[Integer]"); break; case CodeCompletionLiteralKind::NilLiteral: Prefix.append("[Nil]"); break; case CodeCompletionLiteralKind::StringLiteral: Prefix.append("[String]"); break; case CodeCompletionLiteralKind::Tuple: Prefix.append("[Tuple]"); break; } break; case ResultKind::BuiltinOperator: Prefix.append("BuiltinOperator"); break; } Prefix.append("/"); switch (getSemanticContext()) { case SemanticContextKind::None: Prefix.append("None"); break; case SemanticContextKind::ExpressionSpecific: Prefix.append("ExprSpecific"); break; case SemanticContextKind::Local: Prefix.append("Local"); break; case SemanticContextKind::CurrentNominal: Prefix.append("CurrNominal"); break; case SemanticContextKind::Super: Prefix.append("Super"); break; case SemanticContextKind::OutsideNominal: Prefix.append("OutNominal"); break; case SemanticContextKind::CurrentModule: Prefix.append("CurrModule"); break; case SemanticContextKind::OtherModule: Prefix.append("OtherModule"); if (!ModuleName.empty()) Prefix.append((Twine("[") + ModuleName + "]").str()); break; } if (NotRecommended) Prefix.append("/NotRecommended"); if (IsSystem) Prefix.append("/IsSystem"); if (NumBytesToErase != 0) { Prefix.append("/Erase["); Prefix.append(Twine(NumBytesToErase).str()); Prefix.append("]"); } switch (getExpectedTypeRelation()) { case ExpectedTypeRelation::Invalid: Prefix.append("/TypeRelation[Invalid]"); break; case ExpectedTypeRelation::Identical: Prefix.append("/TypeRelation[Identical]"); break; case ExpectedTypeRelation::Convertible: Prefix.append("/TypeRelation[Convertible]"); break; case ExpectedTypeRelation::NotApplicable: case ExpectedTypeRelation::Unknown: case ExpectedTypeRelation::Unrelated: break; } for (clang::comments::WordPairsArrangedViewer Viewer(DocWords); Viewer.hasNext();) { auto Pair = Viewer.next(); Prefix.append("/"); Prefix.append(Pair.first); Prefix.append("["); StringRef Sep = ", "; for (auto KW : Pair.second) { Prefix.append(KW); Prefix.append(Sep); } for (unsigned I = 0, N = Sep.size(); I < N; ++I) Prefix.pop_back(); Prefix.append("]"); } Prefix.append(": "); while (Prefix.size() < 36) { Prefix.append(" "); } OS << Prefix; } void CodeCompletionResult::dump() const { printPrefix(llvm::errs()); CompletionString->print(llvm::errs()); llvm::errs() << "\n"; } void CodeCompletionResultBuilder::withNestedGroup( CodeCompletionString::Chunk::ChunkKind Kind, llvm::function_ref<void()> body) { ++CurrentNestingLevel; addSimpleChunk(Kind); body(); --CurrentNestingLevel; } void CodeCompletionResultBuilder::addChunkWithText( CodeCompletionString::Chunk::ChunkKind Kind, StringRef Text) { addChunkWithTextNoCopy(Kind, copyString(*Sink.Allocator, Text)); } void CodeCompletionResultBuilder::setAssociatedDecl(const Decl *D) { assert(Kind == CodeCompletionResult::ResultKind::Declaration); AssociatedDecl = D; if (auto *ClangD = D->getClangDecl()) CurrentModule = ClangD->getImportedOwningModule(); // FIXME: macros // FIXME: imported header module if (!CurrentModule) { ModuleDecl *MD = D->getModuleContext(); // If this is an underscored cross-import overlay, map it to the underlying // module that declares it instead. if (ModuleDecl *Declaring = MD->getDeclaringModuleIfCrossImportOverlay()) MD = Declaring; CurrentModule = MD; } if (D->getAttrs().getDeprecated(D->getASTContext())) setNotRecommended(NotRecommendedReason::Deprecated); } namespace { class AnnotatedTypePrinter : public ASTPrinter { using ChunkKind = CodeCompletionString::Chunk::ChunkKind; CodeCompletionResultBuilder &Builder; SmallString<16> Buffer; ChunkKind CurrChunkKind = ChunkKind::Text; ChunkKind NextChunkKind = ChunkKind::Text; Optional<ChunkKind> getChunkKindForPrintNameContext(PrintNameContext context) { switch (context) { case PrintNameContext::Keyword: return ChunkKind::Keyword; case PrintNameContext::Attribute: return ChunkKind::Attribute; default: return None; } } void flush() { if (Buffer.empty()) return; Builder.addChunkWithText(CurrChunkKind, Buffer); Buffer.clear(); } public: AnnotatedTypePrinter(CodeCompletionResultBuilder &Builder) : Builder(Builder) {} ~AnnotatedTypePrinter() { // Flush the remainings. flush(); } void printText(StringRef Text) override { if (CurrChunkKind != NextChunkKind) { // If the next desired kind is different from the current buffer, flush // the current buffer. flush(); CurrChunkKind = NextChunkKind; } Buffer.append(Text); } void printTypeRef( Type T, const TypeDecl *TD, Identifier Name, PrintNameContext NameContext = PrintNameContext::Normal) override { NextChunkKind = TD->getModuleContext()->isSystemModule() ? ChunkKind::TypeIdSystem : ChunkKind::TypeIdUser; ASTPrinter::printTypeRef(T, TD, Name, NameContext); NextChunkKind = ChunkKind::Text; } void printNamePre(PrintNameContext context) override { if (auto Kind = getChunkKindForPrintNameContext(context)) NextChunkKind = *Kind; } void printNamePost(PrintNameContext context) override { if (auto Kind = getChunkKindForPrintNameContext(context)) NextChunkKind = ChunkKind::Text; } }; } // namespcae void CodeCompletionResultBuilder::addCallParameter(Identifier Name, Identifier LocalName, Type Ty, Type ContextTy, bool IsVarArg, bool IsInOut, bool IsIUO, bool isAutoClosure, bool useUnderscoreLabel, bool isLabeledTrailingClosure) { ++CurrentNestingLevel; using ChunkKind = CodeCompletionString::Chunk::ChunkKind; addSimpleChunk(ChunkKind::CallParameterBegin); if (shouldAnnotateResults()) { if (!Name.empty() || !LocalName.empty()) { llvm::SmallString<16> EscapedKeyword; if (!Name.empty()) { addChunkWithText( CodeCompletionString::Chunk::ChunkKind::CallParameterName, escapeKeyword(Name.str(), false, EscapedKeyword)); if (!LocalName.empty() && Name != LocalName) { addChunkWithTextNoCopy(ChunkKind::Text, " "); getLastChunk().setIsAnnotation(); addChunkWithText(ChunkKind::CallParameterInternalName, escapeKeyword(LocalName.str(), false, EscapedKeyword)); getLastChunk().setIsAnnotation(); } } else { assert(!LocalName.empty()); addChunkWithTextNoCopy(ChunkKind::CallParameterName, "_"); getLastChunk().setIsAnnotation(); addChunkWithTextNoCopy(ChunkKind::Text, " "); getLastChunk().setIsAnnotation(); addChunkWithText(ChunkKind::CallParameterInternalName, escapeKeyword(LocalName.str(), false, EscapedKeyword)); } addChunkWithTextNoCopy(ChunkKind::CallParameterColon, ": "); } } else { if (!Name.empty()) { llvm::SmallString<16> EscapedKeyword; addChunkWithText( CodeCompletionString::Chunk::ChunkKind::CallParameterName, escapeKeyword(Name.str(), false, EscapedKeyword)); addChunkWithTextNoCopy( CodeCompletionString::Chunk::ChunkKind::CallParameterColon, ": "); } else if (useUnderscoreLabel) { addChunkWithTextNoCopy( CodeCompletionString::Chunk::ChunkKind::CallParameterName, "_"); addChunkWithTextNoCopy( CodeCompletionString::Chunk::ChunkKind::CallParameterColon, ": "); } else if (!LocalName.empty()) { // Use local (non-API) parameter name if we have nothing else. llvm::SmallString<16> EscapedKeyword; addChunkWithText( CodeCompletionString::Chunk::ChunkKind::CallParameterInternalName, escapeKeyword(LocalName.str(), false, EscapedKeyword)); addChunkWithTextNoCopy( CodeCompletionString::Chunk::ChunkKind::CallParameterColon, ": "); } } // 'inout' arguments are printed specially. if (IsInOut) { addChunkWithTextNoCopy( CodeCompletionString::Chunk::ChunkKind::Ampersand, "&"); Ty = Ty->getInOutObjectType(); } // If the parameter is of the type @autoclosure ()->output, then the // code completion should show the parameter of the output type // instead of the function type ()->output. if (isAutoClosure) { // 'Ty' may be ErrorType. if (auto funcTy = Ty->getAs<FunctionType>()) Ty = funcTy->getResult(); } PrintOptions PO; PO.SkipAttributes = true; PO.PrintOptionalAsImplicitlyUnwrapped = IsIUO; PO.OpaqueReturnTypePrinting = PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword; if (ContextTy) PO.setBaseType(ContextTy); if (shouldAnnotateResults()) { withNestedGroup(ChunkKind::CallParameterTypeBegin, [&]() { AnnotatedTypePrinter printer(*this); Ty->print(printer, PO); }); } else { std::string TypeName = Ty->getString(PO); addChunkWithText(ChunkKind::CallParameterType, TypeName); } // Look through optional types and type aliases to find out if we have // function type. Ty = Ty->lookThroughAllOptionalTypes(); if (auto AFT = Ty->getAs<AnyFunctionType>()) { // If this is a closure type, add ChunkKind::CallParameterClosureType or // ChunkKind::CallParameterClosureExpr for labeled trailing closures. PrintOptions PO; PO.PrintFunctionRepresentationAttrs = PrintOptions::FunctionRepresentationMode::None; PO.SkipAttributes = true; PO.OpaqueReturnTypePrinting = PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword; PO.AlwaysTryPrintParameterLabels = true; if (ContextTy) PO.setBaseType(ContextTy); if (isLabeledTrailingClosure) { // Expand the closure body. SmallString<32> buffer; llvm::raw_svector_ostream OS(buffer); bool firstParam = true; for (const auto &param : AFT->getParams()) { if (!firstParam) OS << ", "; firstParam = false; if (param.hasLabel()) { OS << param.getLabel(); } else if (param.hasInternalLabel()) { OS << param.getInternalLabel(); } else { OS << "<#"; if (param.isInOut()) OS << "inout "; OS << param.getPlainType()->getString(PO); if (param.isVariadic()) OS << "..."; OS << "#>"; } } if (!firstParam) OS << " in"; addChunkWithText( CodeCompletionString::Chunk::ChunkKind::CallParameterClosureExpr, OS.str()); } else { // Add the closure type. addChunkWithText( CodeCompletionString::Chunk::ChunkKind::CallParameterClosureType, AFT->getString(PO)); } } if (IsVarArg) addEllipsis(); --CurrentNestingLevel; } void CodeCompletionResultBuilder::addTypeAnnotation(Type T, PrintOptions PO, StringRef suffix) { T = T->getReferenceStorageReferent(); // Replace '()' with 'Void'. if (T->isVoid()) T = T->getASTContext().getVoidDecl()->getDeclaredInterfaceType(); if (shouldAnnotateResults()) { withNestedGroup(CodeCompletionString::Chunk::ChunkKind::TypeAnnotationBegin, [&]() { AnnotatedTypePrinter printer(*this); T->print(printer, PO); if (!suffix.empty()) printer.printText(suffix); }); } else { auto str = T.getString(PO); if (!suffix.empty()) str += suffix.str(); addTypeAnnotation(str); } } StringRef CodeCompletionContext::copyString(StringRef Str) { return ::copyString(*CurrentResults.Allocator, Str); } bool shouldCopyAssociatedUSRForDecl(const ValueDecl *VD) { // Avoid trying to generate a USR for some declaration types. if (isa<AbstractTypeParamDecl>(VD) && !isa<AssociatedTypeDecl>(VD)) return false; if (isa<ParamDecl>(VD)) return false; if (isa<ModuleDecl>(VD)) return false; if (VD->hasClangNode() && !VD->getClangDecl()) return false; return true; } template <typename FnTy> static void walkValueDeclAndOverriddenDecls(const Decl *D, const FnTy &Fn) { if (auto *VD = dyn_cast<ValueDecl>(D)) { Fn(VD); walkOverriddenDecls(VD, Fn); } } ArrayRef<StringRef> copyAssociatedUSRs(llvm::BumpPtrAllocator &Allocator, const Decl *D) { llvm::SmallVector<StringRef, 4> USRs; walkValueDeclAndOverriddenDecls(D, [&](llvm::PointerUnion<const ValueDecl*, const clang::NamedDecl*> OD) { llvm::SmallString<128> SS; bool Ignored = true; if (auto *OVD = OD.dyn_cast<const ValueDecl*>()) { if (shouldCopyAssociatedUSRForDecl(OVD)) { llvm::raw_svector_ostream OS(SS); Ignored = printValueDeclUSR(OVD, OS); } } else if (auto *OND = OD.dyn_cast<const clang::NamedDecl*>()) { Ignored = clang::index::generateUSRForDecl(OND, SS); } if (!Ignored) USRs.push_back(copyString(Allocator, SS)); }); if (!USRs.empty()) return copyArray(Allocator, ArrayRef<StringRef>(USRs)); return ArrayRef<StringRef>(); } static CodeCompletionResult::ExpectedTypeRelation calculateTypeRelation(Type Ty, Type ExpectedTy, const DeclContext *DC) { if (Ty.isNull() || ExpectedTy.isNull() || Ty->is<ErrorType>() || ExpectedTy->is<ErrorType>()) return CodeCompletionResult::ExpectedTypeRelation::Unrelated; // Equality/Conversion of GenericTypeParameterType won't account for // requirements – ignore them if (!Ty->hasTypeParameter() && !ExpectedTy->hasTypeParameter()) { if (Ty->isEqual(ExpectedTy)) return CodeCompletionResult::ExpectedTypeRelation::Identical; bool isAny = false; isAny |= ExpectedTy->isAny(); isAny |= ExpectedTy->is<ArchetypeType>() && !ExpectedTy->castTo<ArchetypeType>()->hasRequirements(); if (!isAny && isConvertibleTo(Ty, ExpectedTy, /*openArchetypes=*/true, *const_cast<DeclContext *>(DC))) return CodeCompletionResult::ExpectedTypeRelation::Convertible; } if (auto FT = Ty->getAs<AnyFunctionType>()) { if (FT->getResult()->isVoid()) return CodeCompletionResult::ExpectedTypeRelation::Invalid; } return CodeCompletionResult::ExpectedTypeRelation::Unrelated; } static CodeCompletionResult::ExpectedTypeRelation calculateMaxTypeRelation(Type Ty, const ExpectedTypeContext &typeContext, const DeclContext *DC) { if (typeContext.empty()) return CodeCompletionResult::ExpectedTypeRelation::Unknown; if (auto funcTy = Ty->getAs<AnyFunctionType>()) Ty = funcTy->removeArgumentLabels(1); auto Result = CodeCompletionResult::ExpectedTypeRelation::Unrelated; for (auto expectedTy : typeContext.possibleTypes) { // Do not use Void type context for a single-expression body, since the // implicit return does not constrain the expression. // // { ... -> () in x } // x can be anything // // This behaves differently from explicit return, and from non-Void: // // { ... -> Int in x } // x must be Int // { ... -> () in return x } // x must be Void if (typeContext.isImplicitSingleExpressionReturn && expectedTy->isVoid()) continue; Result = std::max(Result, calculateTypeRelation(Ty, expectedTy, DC)); // Map invalid -> unrelated when in a single-expression body, since the // input may be incomplete. if (typeContext.isImplicitSingleExpressionReturn && Result == CodeCompletionResult::ExpectedTypeRelation::Invalid) Result = CodeCompletionResult::ExpectedTypeRelation::Unrelated; } return Result; } CodeCompletionOperatorKind CodeCompletionResult::getCodeCompletionOperatorKind(StringRef name) { using CCOK = CodeCompletionOperatorKind; using OpPair = std::pair<StringRef, CCOK>; // This list must be kept in alphabetical order. static OpPair ops[] = { std::make_pair("!", CCOK::Bang), std::make_pair("!=", CCOK::NotEq), std::make_pair("!==", CCOK::NotEqEq), std::make_pair("%", CCOK::Modulo), std::make_pair("%=", CCOK::ModuloEq), std::make_pair("&", CCOK::Amp), std::make_pair("&&", CCOK::AmpAmp), std::make_pair("&*", CCOK::AmpStar), std::make_pair("&+", CCOK::AmpPlus), std::make_pair("&-", CCOK::AmpMinus), std::make_pair("&=", CCOK::AmpEq), std::make_pair("(", CCOK::LParen), std::make_pair("*", CCOK::Star), std::make_pair("*=", CCOK::StarEq), std::make_pair("+", CCOK::Plus), std::make_pair("+=", CCOK::PlusEq), std::make_pair("-", CCOK::Minus), std::make_pair("-=", CCOK::MinusEq), std::make_pair(".", CCOK::Dot), std::make_pair("...", CCOK::DotDotDot), std::make_pair("..<", CCOK::DotDotLess), std::make_pair("/", CCOK::Slash), std::make_pair("/=", CCOK::SlashEq), std::make_pair("<", CCOK::Less), std::make_pair("<<", CCOK::LessLess), std::make_pair("<<=", CCOK::LessLessEq), std::make_pair("<=", CCOK::LessEq), std::make_pair("=", CCOK::Eq), std::make_pair("==", CCOK::EqEq), std::make_pair("===", CCOK::EqEqEq), std::make_pair(">", CCOK::Greater), std::make_pair(">=", CCOK::GreaterEq), std::make_pair(">>", CCOK::GreaterGreater), std::make_pair(">>=", CCOK::GreaterGreaterEq), std::make_pair("?.", CCOK::QuestionDot), std::make_pair("^", CCOK::Caret), std::make_pair("^=", CCOK::CaretEq), std::make_pair("|", CCOK::Pipe), std::make_pair("|=", CCOK::PipeEq), std::make_pair("||", CCOK::PipePipe), std::make_pair("~=", CCOK::TildeEq), }; static auto opsSize = sizeof(ops) / sizeof(ops[0]); auto I = std::lower_bound( ops, &ops[opsSize], std::make_pair(name, CCOK::None), [](const OpPair &a, const OpPair &b) { return a.first < b.first; }); if (I == &ops[opsSize] || I->first != name) return CCOK::Unknown; return I->second; } static StringRef getOperatorName(CodeCompletionString *str) { return str->getFirstTextChunk(/*includeLeadingPunctuation=*/true); } CodeCompletionOperatorKind CodeCompletionResult::getCodeCompletionOperatorKind(CodeCompletionString *str) { return getCodeCompletionOperatorKind(getOperatorName(str)); } CodeCompletionResult *CodeCompletionResultBuilder::takeResult() { auto *CCS = CodeCompletionString::create(*Sink.Allocator, Chunks); switch (Kind) { case CodeCompletionResult::ResultKind::Declaration: { StringRef BriefComment; auto MaybeClangNode = AssociatedDecl->getClangNode(); if (MaybeClangNode) { if (auto *D = MaybeClangNode.getAsDecl()) { const auto &ClangContext = D->getASTContext(); if (const clang::RawComment *RC = ClangContext.getRawCommentForAnyRedecl(D)) BriefComment = RC->getBriefText(ClangContext); } } else { BriefComment = AssociatedDecl->getBriefComment(); } StringRef ModuleName; if (CurrentModule) { if (Sink.LastModule.first == CurrentModule.getOpaqueValue()) { ModuleName = Sink.LastModule.second; } else { if (auto *C = CurrentModule.dyn_cast<const clang::Module *>()) { ModuleName = copyString(*Sink.Allocator, C->getFullModuleName()); } else { ModuleName = copyString( *Sink.Allocator, CurrentModule.get<const swift::ModuleDecl *>()->getName().str()); } Sink.LastModule.first = CurrentModule.getOpaqueValue(); Sink.LastModule.second = ModuleName; } } return new (*Sink.Allocator) CodeCompletionResult( SemanticContext, NumBytesToErase, CCS, AssociatedDecl, ModuleName, NotRecReason, copyString(*Sink.Allocator, BriefComment), copyAssociatedUSRs(*Sink.Allocator, AssociatedDecl), copyArray(*Sink.Allocator, CommentWords), ExpectedTypeRelation); } case CodeCompletionResult::ResultKind::Keyword: return new (*Sink.Allocator) CodeCompletionResult( KeywordKind, SemanticContext, NumBytesToErase, CCS, ExpectedTypeRelation, copyString(*Sink.Allocator, BriefDocComment)); case CodeCompletionResult::ResultKind::BuiltinOperator: case CodeCompletionResult::ResultKind::Pattern: return new (*Sink.Allocator) CodeCompletionResult( Kind, SemanticContext, NumBytesToErase, CCS, ExpectedTypeRelation, CodeCompletionOperatorKind::None, copyString(*Sink.Allocator, BriefDocComment)); case CodeCompletionResult::ResultKind::Literal: assert(LiteralKind.hasValue()); return new (*Sink.Allocator) CodeCompletionResult(*LiteralKind, SemanticContext, NumBytesToErase, CCS, ExpectedTypeRelation); } llvm_unreachable("Unhandled CodeCompletionResult in switch."); } void CodeCompletionResultBuilder::finishResult() { if (!Cancelled) Sink.Results.push_back(takeResult()); } MutableArrayRef<CodeCompletionResult *> CodeCompletionContext::takeResults() { // Copy pointers to the results. const size_t Count = CurrentResults.Results.size(); CodeCompletionResult **Results = CurrentResults.Allocator->Allocate<CodeCompletionResult *>(Count); std::copy(CurrentResults.Results.begin(), CurrentResults.Results.end(), Results); CurrentResults.Results.clear(); return MutableArrayRef<CodeCompletionResult *>(Results, Count); } Optional<unsigned> CodeCompletionString::getFirstTextChunkIndex( bool includeLeadingPunctuation) const { for (auto i : indices(getChunks())) { auto &C = getChunks()[i]; switch (C.getKind()) { using ChunkKind = Chunk::ChunkKind; case ChunkKind::Text: case ChunkKind::CallParameterName: case ChunkKind::CallParameterInternalName: case ChunkKind::GenericParameterName: case ChunkKind::LeftParen: case ChunkKind::LeftBracket: case ChunkKind::Equal: case ChunkKind::DeclAttrParamKeyword: case ChunkKind::DeclAttrKeyword: case ChunkKind::Keyword: case ChunkKind::Attribute: case ChunkKind::BaseName: case ChunkKind::TypeIdSystem: case ChunkKind::TypeIdUser: case ChunkKind::CallParameterBegin: return i; case ChunkKind::Dot: case ChunkKind::ExclamationMark: case ChunkKind::QuestionMark: if (includeLeadingPunctuation) return i; continue; case ChunkKind::RightParen: case ChunkKind::RightBracket: case ChunkKind::LeftAngle: case ChunkKind::RightAngle: case ChunkKind::Ellipsis: case ChunkKind::Comma: case ChunkKind::Ampersand: case ChunkKind::Whitespace: case ChunkKind::AccessControlKeyword: case ChunkKind::OverrideKeyword: case ChunkKind::EffectsSpecifierKeyword: case ChunkKind::DeclIntroducer: case ChunkKind::CallParameterColon: case ChunkKind::CallParameterTypeBegin: case ChunkKind::DeclAttrParamColon: case ChunkKind::CallParameterType: case ChunkKind::CallParameterClosureType: case ChunkKind::CallParameterClosureExpr: case ChunkKind::OptionalBegin: case ChunkKind::GenericParameterBegin: case ChunkKind::DynamicLookupMethodCallTail: case ChunkKind::OptionalMethodCallTail: case ChunkKind::TypeAnnotation: case ChunkKind::TypeAnnotationBegin: continue; case ChunkKind::BraceStmtWithCursor: llvm_unreachable("should have already extracted the text"); } } return None; } StringRef CodeCompletionString::getFirstTextChunk(bool includeLeadingPunctuation) const { Optional<unsigned> Idx = getFirstTextChunkIndex(includeLeadingPunctuation); if (Idx.hasValue()) return getChunks()[*Idx].getText(); return StringRef(); } void CodeCompletionString::getName(raw_ostream &OS) const { auto FirstTextChunk = getFirstTextChunkIndex(); int TextSize = 0; if (FirstTextChunk.hasValue()) { auto chunks = getChunks().slice(*FirstTextChunk); for (auto i = chunks.begin(), e = chunks.end(); i != e; ++i) { using ChunkKind = Chunk::ChunkKind; bool shouldPrint = !i->isAnnotation(); switch (i->getKind()) { case ChunkKind::TypeAnnotation: case ChunkKind::CallParameterClosureType: case ChunkKind::CallParameterClosureExpr: case ChunkKind::DeclAttrParamColon: case ChunkKind::OptionalMethodCallTail: continue; case ChunkKind::TypeAnnotationBegin: { auto level = i->getNestingLevel(); do { ++i; } while (i != e && !i->endsPreviousNestedGroup(level)); --i; continue; } case ChunkKind::EffectsSpecifierKeyword: shouldPrint = true; // Even when they're annotations. break; default: break; } if (i->hasText() && shouldPrint) { TextSize += i->getText().size(); OS << i->getText(); } } } } void CodeCompletionContext::sortCompletionResults( MutableArrayRef<CodeCompletionResult *> Results) { struct ResultAndName { CodeCompletionResult *result; std::string name; }; // Caching the name of each field is important to avoid unnecessary calls to // CodeCompletionString::getName(). std::vector<ResultAndName> nameCache(Results.size()); for (unsigned i = 0, n = Results.size(); i < n; ++i) { auto *result = Results[i]; nameCache[i].result = result; llvm::raw_string_ostream OS(nameCache[i].name); result->getCompletionString()->getName(OS); OS.flush(); } // Sort nameCache, and then transform Results to return the pointers in order. std::sort(nameCache.begin(), nameCache.end(), [](const ResultAndName &LHS, const ResultAndName &RHS) { int Result = StringRef(LHS.name).compare_lower(RHS.name); // If the case insensitive comparison is equal, then secondary sort order // should be case sensitive. if (Result == 0) Result = LHS.name.compare(RHS.name); return Result < 0; }); llvm::transform(nameCache, Results.begin(), [](const ResultAndName &entry) { return entry.result; }); } namespace { class CodeCompletionCallbacksImpl : public CodeCompletionCallbacks { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; CodeCompletionExpr *CodeCompleteTokenExpr = nullptr; CompletionKind Kind = CompletionKind::None; Expr *ParsedExpr = nullptr; SourceLoc DotLoc; TypeLoc ParsedTypeLoc; DeclContext *CurDeclContext = nullptr; DeclAttrKind AttrKind; /// In situations when \c SyntaxKind hints or determines /// completions, i.e. a precedence group attribute, this /// can be set and used to control the code completion scenario. SyntaxKind SyntxKind; int AttrParamIndex; bool IsInSil = false; bool HasSpace = false; bool ShouldCompleteCallPatternAfterParen = true; bool PreferFunctionReferencesToCalls = false; bool AttTargetIsIndependent = false; bool IsAtStartOfLine = false; Optional<DeclKind> AttTargetDK; Optional<StmtKind> ParentStmtKind; SmallVector<StringRef, 3> ParsedKeywords; SourceLoc introducerLoc; std::vector<std::pair<std::string, bool>> SubModuleNameVisibilityPairs; void addSuperKeyword(CodeCompletionResultSink &Sink) { auto *DC = CurDeclContext->getInnermostTypeContext(); if (!DC) return; auto *CD = DC->getSelfClassDecl(); if (!CD) return; Type ST = CD->getSuperclass(); if (ST.isNull() || ST->is<ErrorType>()) return; CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::CurrentNominal, {}); Builder.setKeywordKind(CodeCompletionKeywordKind::kw_super); Builder.addKeyword("super"); Builder.addTypeAnnotation(ST, PrintOptions()); } Optional<std::pair<Type, ConcreteDeclRef>> typeCheckParsedExpr() { assert(ParsedExpr && "should have an expression"); // Figure out the kind of type-check we'll be performing. auto CheckKind = CompletionTypeCheckKind::Normal; if (Kind == CompletionKind::KeyPathExprObjC) CheckKind = CompletionTypeCheckKind::KeyPath; // If we've already successfully type-checked the expression for some // reason, just return the type. // FIXME: if it's ErrorType but we've already typechecked we shouldn't // typecheck again. rdar://21466394 if (CheckKind == CompletionTypeCheckKind::Normal && ParsedExpr->getType() && !ParsedExpr->getType()->is<ErrorType>()) { return getReferencedDecl(ParsedExpr); } ConcreteDeclRef ReferencedDecl = nullptr; Expr *ModifiedExpr = ParsedExpr; if (auto T = getTypeOfCompletionContextExpr(P.Context, CurDeclContext, CheckKind, ModifiedExpr, ReferencedDecl)) { // FIXME: even though we don't apply the solution, the type checker may // modify the original expression. We should understand what effect that // may have on code completion. ParsedExpr = ModifiedExpr; return std::make_pair(*T, ReferencedDecl); } return None; } /// \returns true on success, false on failure. bool typecheckParsedType() { assert(ParsedTypeLoc.getTypeRepr() && "should have a TypeRepr"); if (ParsedTypeLoc.wasValidated() && !ParsedTypeLoc.isError()) { return true; } const auto ty = swift::performTypeResolution( ParsedTypeLoc.getTypeRepr(), P.Context, /*isSILMode=*/false, /*isSILType=*/false, CurDeclContext->getGenericEnvironmentOfContext(), /*GenericParams=*/nullptr, CurDeclContext, /*ProduceDiagnostics=*/false); ParsedTypeLoc.setType(ty); if (!ParsedTypeLoc.isError()) { return true; } // It doesn't type check as a type, so see if it's a qualifying module name. if (auto *ITR = dyn_cast<IdentTypeRepr>(ParsedTypeLoc.getTypeRepr())) { const auto &componentRange = ITR->getComponentRange(); // If it has more than one component, it can't be a module name. if (std::distance(componentRange.begin(), componentRange.end()) != 1) return false; const auto &component = componentRange.front(); ImportPath::Module::Builder builder( component->getNameRef().getBaseIdentifier(), component->getLoc()); if (auto Module = Context.getLoadedModule(builder.get())) ParsedTypeLoc.setType(ModuleType::get(Module)); return true; } return false; } public: CodeCompletionCallbacksImpl(Parser &P, CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CodeCompletionCallbacks(P), CompletionContext(CompletionContext), Consumer(Consumer) { } void setAttrTargetDeclKind(Optional<DeclKind> DK) override { if (DK == DeclKind::PatternBinding) DK = DeclKind::Var; else if (DK == DeclKind::Param) // For params, consider the attribute is always for the decl. AttTargetIsIndependent = false; if (!AttTargetIsIndependent) AttTargetDK = DK; } void completeDotExpr(CodeCompletionExpr *E, SourceLoc DotLoc) override; void completeStmtOrExpr(CodeCompletionExpr *E) override; void completePostfixExprBeginning(CodeCompletionExpr *E) override; void completeForEachSequenceBeginning(CodeCompletionExpr *E) override; void completePostfixExpr(Expr *E, bool hasSpace) override; void completePostfixExprParen(Expr *E, Expr *CodeCompletionE) override; void completeExprKeyPath(KeyPathExpr *KPE, SourceLoc DotLoc) override; void completeTypeDeclResultBeginning() override; void completeTypeSimpleBeginning() override; void completeTypeIdentifierWithDot(IdentTypeRepr *ITR) override; void completeTypeIdentifierWithoutDot(IdentTypeRepr *ITR) override; void completeCaseStmtKeyword() override; void completeCaseStmtBeginning(CodeCompletionExpr *E) override; void completeDeclAttrBeginning(bool Sil, bool isIndependent) override; void completeDeclAttrParam(DeclAttrKind DK, int Index) override; void completeEffectsSpecifier(bool hasAsync, bool hasThrows) override; void completeInPrecedenceGroup(SyntaxKind SK) override; void completeNominalMemberBeginning( SmallVectorImpl<StringRef> &Keywords, SourceLoc introducerLoc) override; void completeAccessorBeginning(CodeCompletionExpr *E) override; void completePoundAvailablePlatform() override; void completeImportDecl(ImportPath::Builder &Path) override; void completeUnresolvedMember(CodeCompletionExpr *E, SourceLoc DotLoc) override; void completeCallArg(CodeCompletionExpr *E, bool isFirst) override; void completeLabeledTrailingClosure(CodeCompletionExpr *E, bool isAtStartOfLine) override; bool canPerformCompleteLabeledTrailingClosure() const override { return true; } void completeReturnStmt(CodeCompletionExpr *E) override; void completeYieldStmt(CodeCompletionExpr *E, Optional<unsigned> yieldIndex) override; void completeAfterPoundExpr(CodeCompletionExpr *E, Optional<StmtKind> ParentKind) override; void completeAfterPoundDirective() override; void completePlatformCondition() override; void completeGenericRequirement() override; void completeAfterIfStmt(bool hasElse) override; void completeStmtLabel(StmtKind ParentKind) override; void doneParsing() override; private: void addKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody); bool trySolverCompletion(bool MaybeFuncBody); }; } // end anonymous namespace namespace { static bool isTopLevelSubcontext(const DeclContext *DC) { for (; DC && DC->isLocalContext(); DC = DC->getParent()) { switch (DC->getContextKind()) { case DeclContextKind::TopLevelCodeDecl: return true; case DeclContextKind::AbstractFunctionDecl: case DeclContextKind::SubscriptDecl: case DeclContextKind::EnumElementDecl: return false; default: continue; } } return false; } static KnownProtocolKind protocolForLiteralKind(CodeCompletionLiteralKind kind) { switch (kind) { case CodeCompletionLiteralKind::ArrayLiteral: return KnownProtocolKind::ExpressibleByArrayLiteral; case CodeCompletionLiteralKind::BooleanLiteral: return KnownProtocolKind::ExpressibleByBooleanLiteral; case CodeCompletionLiteralKind::ColorLiteral: return KnownProtocolKind::ExpressibleByColorLiteral; case CodeCompletionLiteralKind::ImageLiteral: return KnownProtocolKind::ExpressibleByImageLiteral; case CodeCompletionLiteralKind::DictionaryLiteral: return KnownProtocolKind::ExpressibleByDictionaryLiteral; case CodeCompletionLiteralKind::IntegerLiteral: return KnownProtocolKind::ExpressibleByIntegerLiteral; case CodeCompletionLiteralKind::NilLiteral: return KnownProtocolKind::ExpressibleByNilLiteral; case CodeCompletionLiteralKind::StringLiteral: return KnownProtocolKind::ExpressibleByUnicodeScalarLiteral; case CodeCompletionLiteralKind::Tuple: llvm_unreachable("no such protocol kind"); } llvm_unreachable("Unhandled CodeCompletionLiteralKind in switch."); } static Type defaultTypeLiteralKind(CodeCompletionLiteralKind kind, ASTContext &Ctx) { switch (kind) { case CodeCompletionLiteralKind::BooleanLiteral: return Ctx.getBoolDecl()->getDeclaredInterfaceType(); case CodeCompletionLiteralKind::IntegerLiteral: return Ctx.getIntDecl()->getDeclaredInterfaceType(); case CodeCompletionLiteralKind::StringLiteral: return Ctx.getStringDecl()->getDeclaredInterfaceType(); case CodeCompletionLiteralKind::ArrayLiteral: return Ctx.getArrayDecl()->getDeclaredType(); case CodeCompletionLiteralKind::DictionaryLiteral: return Ctx.getDictionaryDecl()->getDeclaredType(); case CodeCompletionLiteralKind::NilLiteral: case CodeCompletionLiteralKind::ColorLiteral: case CodeCompletionLiteralKind::ImageLiteral: case CodeCompletionLiteralKind::Tuple: return Type(); } llvm_unreachable("Unhandled CodeCompletionLiteralKind in switch."); } /// Whether funcType has a single argument (not including defaulted arguments) /// that is of type () -> (). static bool hasTrivialTrailingClosure(const FuncDecl *FD, AnyFunctionType *funcType) { ParameterListInfo paramInfo(funcType->getParams(), FD, /*skipCurriedSelf*/ FD->hasCurriedSelf()); if (paramInfo.size() - paramInfo.numNonDefaultedParameters() == 1) { auto param = funcType->getParams().back(); if (!param.isAutoClosure()) { if (auto Fn = param.getOldType()->getAs<AnyFunctionType>()) { return Fn->getParams().empty() && Fn->getResult()->isVoid(); } } } return false; } /// Returns \c true if \p DC can handles async call. static bool canDeclContextHandleAsync(const DeclContext *DC) { if (auto *func = dyn_cast<AbstractFunctionDecl>(DC)) return func->isAsyncContext(); if (auto *closure = dyn_cast<ClosureExpr>(DC)) { // See if the closure has 'async' function type. if (auto closureType = closure->getType()) if (auto fnType = closureType->getAs<AnyFunctionType>()) if (fnType->isAsync()) return true; // If the closure doesn't contain any async call in the body, closure itself // doesn't have 'async' type even if 'async' closure is expected. // func foo(fn: () async -> Void) // foo { <HERE> } // In this case, the closure is wrapped with a 'FunctionConversionExpr' // which has 'async' function type. struct AsyncClosureChecker: public ASTWalker { const ClosureExpr *Target; bool Result = false; AsyncClosureChecker(const ClosureExpr *Target) : Target(Target) {} std::pair<bool, Expr *> walkToExprPre(Expr *E) override { if (E == Target) return {false, E}; if (auto conversionExpr = dyn_cast<FunctionConversionExpr>(E)) { if (conversionExpr->getSubExpr() == Target) { if (conversionExpr->getType()->is<AnyFunctionType>() && conversionExpr->getType()->castTo<AnyFunctionType>()->isAsync()) Result = true; return {false, E}; } } return {true, E}; } } checker(closure); closure->getParent()->walkContext(checker); return checker.Result; } return false; } /// Build completions by doing visible decl lookup from a context. class CompletionLookup final : public swift::VisibleDeclConsumer { CodeCompletionResultSink &Sink; ASTContext &Ctx; const DeclContext *CurrDeclContext; ModuleDecl *CurrModule; ClangImporter *Importer; CodeCompletionContext *CompletionContext; enum class LookupKind { ValueExpr, ValueInDeclContext, EnumElement, Type, TypeInDeclContext, ImportFromModule, GenericRequirement, }; LookupKind Kind; /// Type of the user-provided expression for LookupKind::ValueExpr /// completions. Type ExprType; /// Whether the expr is of statically inferred metatype. bool IsStaticMetatype = false; /// User-provided base type for LookupKind::Type completions. Type BaseType; /// Expected types of the code completion expression. ExpectedTypeContext expectedTypeContext; bool CanCurrDeclContextHandleAsync = false; bool HaveDot = false; bool IsUnwrappedOptional = false; SourceLoc DotLoc; bool NeedLeadingDot = false; bool NeedOptionalUnwrap = false; unsigned NumBytesToEraseForOptionalUnwrap = 0; bool HaveLParen = false; bool IsSuperRefExpr = false; bool IsSelfRefExpr = false; bool IsKeyPathExpr = false; bool IsSwiftKeyPathExpr = false; bool IsAfterSwiftKeyPathRoot = false; bool IsDynamicLookup = false; bool IsCrossActorReference = false; bool PreferFunctionReferencesToCalls = false; bool HaveLeadingSpace = false; bool CheckForDuplicates = false; llvm::DenseSet<std::pair<const Decl *, Type>> PreviouslySeen; bool IncludeInstanceMembers = false; /// True if we are code completing inside a static method. bool InsideStaticMethod = false; /// Innermost method that the code completion point is in. const AbstractFunctionDecl *CurrentMethod = nullptr; Optional<SemanticContextKind> ForcedSemanticContext = None; bool IsUnresolvedMember = false; public: bool FoundFunctionCalls = false; bool FoundFunctionsWithoutFirstKeyword = false; private: void foundFunction(const AbstractFunctionDecl *AFD) { FoundFunctionCalls = true; const DeclName Name = AFD->getName(); auto ArgNames = Name.getArgumentNames(); if (ArgNames.empty()) return; if (ArgNames[0].empty()) FoundFunctionsWithoutFirstKeyword = true; } void foundFunction(const AnyFunctionType *AFT) { FoundFunctionCalls = true; auto Params = AFT->getParams(); if (Params.empty()) return; if (Params.size() == 1 && !Params[0].hasLabel()) { FoundFunctionsWithoutFirstKeyword = true; return; } if (!Params[0].hasLabel()) FoundFunctionsWithoutFirstKeyword = true; } void setClangDeclKeywords(const ValueDecl *VD, CommandWordsPairs &Pairs, CodeCompletionResultBuilder &Builder) { if (auto *CD = VD->getClangDecl()) { clang::comments::getClangDocKeyword(*Importer, CD, Pairs); } else { swift::markup::getSwiftDocKeyword(VD, Pairs); } Builder.addDeclDocCommentWords(llvm::makeArrayRef(Pairs)); } /// Returns \c true if \p TAD is usable as a first type of a requirement in /// \c where clause for a context. /// \p selfTy must be a \c Self type of the context. static bool canBeUsedAsRequirementFirstType(Type selfTy, TypeAliasDecl *TAD) { auto T = TAD->getDeclaredInterfaceType(); auto subMap = selfTy->getMemberSubstitutionMap(TAD->getParentModule(), TAD); T = T.subst(subMap)->getCanonicalType(); ArchetypeType *archeTy = T->getAs<ArchetypeType>(); if (!archeTy) return false; archeTy = archeTy->getRoot(); // For protocol, the 'archeTy' should match with the 'baseTy' which is the // dynamic 'Self' type of the protocol. For nominal decls, 'archTy' should // be one of the generic params in 'selfTy'. Search 'archeTy' in 'baseTy'. return selfTy.findIf([&](Type T) { return archeTy->isEqual(T); }); } public: struct RequestedResultsTy { const ModuleDecl *TheModule; bool OnlyTypes; bool OnlyPrecedenceGroups; bool NeedLeadingDot; bool IncludeModuleQualifier; static RequestedResultsTy fromModule(const ModuleDecl *TheModule) { return { TheModule, false, false, false, true }; } RequestedResultsTy onlyTypes() const { return { TheModule, true, false, NeedLeadingDot, IncludeModuleQualifier }; } RequestedResultsTy onlyPrecedenceGroups() const { assert(!OnlyTypes && "onlyTypes() already includes precedence groups"); return { TheModule, false, true, false, true }; } RequestedResultsTy needLeadingDot(bool NeedDot) const { return { TheModule, OnlyTypes, OnlyPrecedenceGroups, NeedDot, IncludeModuleQualifier }; } RequestedResultsTy withModuleQualifier(bool IncludeModule) const { return { TheModule, OnlyTypes, OnlyPrecedenceGroups, NeedLeadingDot, IncludeModule }; } static RequestedResultsTy toplevelResults() { return { nullptr, false, false, false, true }; } }; std::vector<RequestedResultsTy> RequestedCachedResults; public: CompletionLookup(CodeCompletionResultSink &Sink, ASTContext &Ctx, const DeclContext *CurrDeclContext, CodeCompletionContext *CompletionContext = nullptr) : Sink(Sink), Ctx(Ctx), CurrDeclContext(CurrDeclContext), CurrModule(CurrDeclContext ? CurrDeclContext->getParentModule() : nullptr), Importer(static_cast<ClangImporter *>(CurrDeclContext->getASTContext(). getClangModuleLoader())), CompletionContext(CompletionContext) { // Determine if we are doing code completion inside a static method. if (CurrDeclContext) { CurrentMethod = CurrDeclContext->getInnermostMethodContext(); if (auto *FD = dyn_cast_or_null<FuncDecl>(CurrentMethod)) InsideStaticMethod = FD->isStatic(); CanCurrDeclContextHandleAsync = canDeclContextHandleAsync(CurrDeclContext); } } void setHaveDot(SourceLoc DotLoc) { HaveDot = true; this->DotLoc = DotLoc; } void setIsUnwrappedOptional(bool value) { IsUnwrappedOptional = value; } void setIsStaticMetatype(bool value) { IsStaticMetatype = value; } void setExpectedTypes(ArrayRef<Type> Types, bool isImplicitSingleExpressionReturn, bool preferNonVoid = false) { expectedTypeContext.isImplicitSingleExpressionReturn = isImplicitSingleExpressionReturn; expectedTypeContext.preferNonVoid = preferNonVoid; expectedTypeContext.possibleTypes.clear(); expectedTypeContext.possibleTypes.reserve(Types.size()); for (auto T : Types) if (T) expectedTypeContext.possibleTypes.push_back(T); } void setIdealExpectedType(Type Ty) { expectedTypeContext.idealType = Ty; } CodeCompletionContext::TypeContextKind typeContextKind() const { if (expectedTypeContext.empty() && !expectedTypeContext.preferNonVoid) { return CodeCompletionContext::TypeContextKind::None; } else if (expectedTypeContext.isImplicitSingleExpressionReturn) { return CodeCompletionContext::TypeContextKind::SingleExpressionBody; } else { return CodeCompletionContext::TypeContextKind::Required; } } bool needDot() const { return NeedLeadingDot; } void setHaveLParen(bool Value) { HaveLParen = Value; } void setIsSuperRefExpr(bool Value = true) { IsSuperRefExpr = Value; } void setIsSelfRefExpr(bool value) { IsSelfRefExpr = value; } void setIsKeyPathExpr() { IsKeyPathExpr = true; } void shouldCheckForDuplicates(bool value = true) { CheckForDuplicates = value; } void setIsSwiftKeyPathExpr(bool onRoot) { IsSwiftKeyPathExpr = true; IsAfterSwiftKeyPathRoot = onRoot; } void setIsDynamicLookup() { IsDynamicLookup = true; } void setPreferFunctionReferencesToCalls() { PreferFunctionReferencesToCalls = true; } void setHaveLeadingSpace(bool value) { HaveLeadingSpace = value; } void includeInstanceMembers() { IncludeInstanceMembers = true; } void addSubModuleNames(std::vector<std::pair<std::string, bool>> &SubModuleNameVisibilityPairs) { for (auto &Pair : SubModuleNameVisibilityPairs) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind:: Declaration, SemanticContextKind::None, expectedTypeContext); auto MD = ModuleDecl::create(Ctx.getIdentifier(Pair.first), Ctx); Builder.setAssociatedDecl(MD); Builder.addBaseName(MD->getNameStr()); Builder.addTypeAnnotation("Module"); if (Pair.second) Builder.setNotRecommended(NotRecommendedReason::RedundantImport); } } void collectImportedModules(llvm::StringSet<> &ImportedModules) { SmallVector<ImportedModule, 16> Imported; SmallVector<ImportedModule, 16> FurtherImported; CurrDeclContext->getParentSourceFile()->getImportedModules( Imported, {ModuleDecl::ImportFilterKind::Exported, ModuleDecl::ImportFilterKind::Default, ModuleDecl::ImportFilterKind::ImplementationOnly}); while (!Imported.empty()) { ModuleDecl *MD = Imported.back().importedModule; Imported.pop_back(); if (!ImportedModules.insert(MD->getNameStr()).second) continue; FurtherImported.clear(); MD->getImportedModules(FurtherImported, ModuleDecl::ImportFilterKind::Exported); Imported.append(FurtherImported.begin(), FurtherImported.end()); } } void addModuleName(ModuleDecl *MD, Optional<NotRecommendedReason> R = None) { // Don't add underscored cross-import overlay modules. if (MD->getDeclaringModuleIfCrossImportOverlay()) return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::None, expectedTypeContext); Builder.setAssociatedDecl(MD); Builder.addBaseName(MD->getNameStr()); Builder.addTypeAnnotation("Module"); if (R) Builder.setNotRecommended(*R); } void addImportModuleNames() { SmallVector<Identifier, 0> ModuleNames; Ctx.getVisibleTopLevelModuleNames(ModuleNames); llvm::StringSet<> ImportedModules; collectImportedModules(ImportedModules); auto mainModuleName = CurrModule->getName(); for (auto ModuleName : ModuleNames) { if (ModuleName.str().startswith("_") || ModuleName == mainModuleName || ModuleName == Ctx.SwiftShimsModuleName || ModuleName.str() == SWIFT_ONONE_SUPPORT) continue; auto MD = ModuleDecl::create(ModuleName, Ctx); Optional<NotRecommendedReason> Reason = None; // Imported modules are not recommended. if (ImportedModules.count(MD->getNameStr()) != 0) Reason = NotRecommendedReason::RedundantImport; addModuleName(MD, Reason); } } SemanticContextKind getSemanticContext(const Decl *D, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { if (ForcedSemanticContext) return *ForcedSemanticContext; switch (Reason) { case DeclVisibilityKind::LocalVariable: case DeclVisibilityKind::FunctionParameter: case DeclVisibilityKind::GenericParameter: return SemanticContextKind::Local; case DeclVisibilityKind::MemberOfCurrentNominal: if (IsSuperRefExpr && CurrentMethod && CurrentMethod->getOverriddenDecl() == D) return SemanticContextKind::ExpressionSpecific; return SemanticContextKind::CurrentNominal; case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal: case DeclVisibilityKind::MemberOfSuper: return SemanticContextKind::Super; case DeclVisibilityKind::MemberOfOutsideNominal: return SemanticContextKind::OutsideNominal; case DeclVisibilityKind::VisibleAtTopLevel: if (CurrDeclContext && D->getModuleContext() == CurrModule) { // Treat global variables from the same source file as local when // completing at top-level. if (isa<VarDecl>(D) && isTopLevelSubcontext(CurrDeclContext) && D->getDeclContext()->getParentSourceFile() == CurrDeclContext->getParentSourceFile()) { return SemanticContextKind::Local; } else { return SemanticContextKind::CurrentModule; } } else { return SemanticContextKind::OtherModule; } case DeclVisibilityKind::DynamicLookup: switch (dynamicLookupInfo.getKind()) { case DynamicLookupInfo::None: llvm_unreachable("invalid DynamicLookupInfo::Kind for dynamic lookup"); case DynamicLookupInfo::AnyObject: // AnyObject results can come from different modules, including the // current module, but we always assign them the OtherModule semantic // context. These declarations are uniqued by signature, so it is // totally random (determined by the hash function) which of the // equivalent declarations (across multiple modules) we will get. return SemanticContextKind::OtherModule; case DynamicLookupInfo::KeyPathDynamicMember: // Use the visibility of the underlying declaration. // FIXME: KeyPath<AnyObject, U> !?!? assert(dynamicLookupInfo.getKeyPathDynamicMember().originalVisibility != DeclVisibilityKind::DynamicLookup); return getSemanticContext( D, dynamicLookupInfo.getKeyPathDynamicMember().originalVisibility, {}); } case DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal: llvm_unreachable("should not see this kind"); } llvm_unreachable("unhandled kind"); } bool isUnresolvedMemberIdealType(Type Ty) { assert(Ty); if (!IsUnresolvedMember) return false; Type idealTy = expectedTypeContext.idealType; if (!idealTy) return false; /// Consider optional object type is the ideal. /// For exmaple: /// enum MyEnum { case foo, bar } /// func foo(_: MyEnum?) /// fooo(.<HERE>) /// Prefer '.foo' and '.bar' over '.some' and '.none'. idealTy = idealTy->lookThroughAllOptionalTypes(); return idealTy->isEqual(Ty); } void addValueBaseName(CodeCompletionResultBuilder &Builder, DeclBaseName Name) { auto NameStr = Name.userFacingName(); bool shouldEscapeKeywords; if (Name.isSpecial()) { // Special names (i.e. 'init') are always displayed as its user facing // name. shouldEscapeKeywords = false; } else if (ExprType) { // After dot. User can write any keyword after '.' except for `init` and // `self`. E.g. 'func `init`()' must be called by 'expr.`init`()'. shouldEscapeKeywords = NameStr == "self" || NameStr == "init"; } else { // As primary expresson. We have to escape almost every keywords except // for 'self' and 'Self'. shouldEscapeKeywords = NameStr != "self" && NameStr != "Self"; } if (!shouldEscapeKeywords) { Builder.addBaseName(NameStr); } else { SmallString<16> buffer; Builder.addBaseName(Builder.escapeKeyword(NameStr, true, buffer)); } } void addLeadingDot(CodeCompletionResultBuilder &Builder) { if (NeedOptionalUnwrap) { Builder.setNumBytesToErase(NumBytesToEraseForOptionalUnwrap); Builder.addQuestionMark(); Builder.addLeadingDot(); return; } if (needDot()) Builder.addLeadingDot(); } void addTypeAnnotation(CodeCompletionResultBuilder &Builder, Type T, GenericSignature genericSig = GenericSignature()) { PrintOptions PO; PO.OpaqueReturnTypePrinting = PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword; if (auto typeContext = CurrDeclContext->getInnermostTypeContext()) PO.setBaseType(typeContext->getDeclaredTypeInContext()); Builder.addTypeAnnotation(eraseArchetypes(T, genericSig), PO); Builder.setExpectedTypeRelation( calculateMaxTypeRelation(T, expectedTypeContext, CurrDeclContext)); } void addTypeAnnotationForImplicitlyUnwrappedOptional( CodeCompletionResultBuilder &Builder, Type T, GenericSignature genericSig = GenericSignature(), bool dynamicOrOptional = false) { std::string suffix; // FIXME: This retains previous behavior, but in reality the type of dynamic // lookups is IUO, not Optional as it is for the @optional attribute. if (dynamicOrOptional) { T = T->getOptionalObjectType(); suffix = "?"; } PrintOptions PO; PO.PrintOptionalAsImplicitlyUnwrapped = true; PO.OpaqueReturnTypePrinting = PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword; if (auto typeContext = CurrDeclContext->getInnermostTypeContext()) PO.setBaseType(typeContext->getDeclaredTypeInContext()); Builder.addTypeAnnotation(eraseArchetypes(T, genericSig), PO, suffix); Builder.setExpectedTypeRelation( calculateMaxTypeRelation(T, expectedTypeContext, CurrDeclContext)); } /// For printing in code completion results, replace archetypes with /// protocol compositions. /// /// FIXME: Perhaps this should be an option in PrintOptions instead. Type eraseArchetypes(Type type, GenericSignature genericSig) { if (!genericSig) return type; auto buildProtocolComposition = [&](ArrayRef<ProtocolDecl *> protos) -> Type { SmallVector<Type, 2> types; for (auto proto : protos) types.push_back(proto->getDeclaredInterfaceType()); return ProtocolCompositionType::get(Ctx, types, /*HasExplicitAnyObject=*/false); }; if (auto *genericFuncType = type->getAs<GenericFunctionType>()) { SmallVector<AnyFunctionType::Param, 8> erasedParams; for (const auto &param : genericFuncType->getParams()) { auto erasedTy = eraseArchetypes(param.getPlainType(), genericSig); erasedParams.emplace_back(param.withType(erasedTy)); } return GenericFunctionType::get(genericSig, erasedParams, eraseArchetypes(genericFuncType->getResult(), genericSig), genericFuncType->getExtInfo()); } return type.transform([&](Type t) -> Type { // FIXME: Code completion should only deal with one or the other, // and not both. if (auto *archetypeType = t->getAs<ArchetypeType>()) { // Don't erase opaque archetype. if (isa<OpaqueTypeArchetypeType>(archetypeType)) return t; auto protos = archetypeType->getConformsTo(); if (!protos.empty()) return buildProtocolComposition(protos); } if (t->isTypeParameter()) { const auto protos = genericSig->getRequiredProtocols(t); if (!protos.empty()) return buildProtocolComposition(protos); } return t; }); } Type getTypeOfMember(const ValueDecl *VD, DynamicLookupInfo dynamicLookupInfo) { switch (dynamicLookupInfo.getKind()) { case DynamicLookupInfo::None: return getTypeOfMember(VD, this->ExprType); case DynamicLookupInfo::AnyObject: return getTypeOfMember(VD, Type()); case DynamicLookupInfo::KeyPathDynamicMember: { auto &keyPathInfo = dynamicLookupInfo.getKeyPathDynamicMember(); // Map the result of VD to keypath member lookup results. // Given: // struct Wrapper<T> { // subscript<U>(dynamicMember: KeyPath<T, U>) -> Wrapped<U> { get } // } // struct Circle { // var center: Point { get } // var radius: Length { get } // } // // Consider 'Wrapper<Circle>.center'. // 'VD' is 'Circle.center' decl. // 'keyPathInfo.subscript' is 'Wrapper<T>.subscript' decl. // 'keyPathInfo.baseType' is 'Wrapper<Circle>' type. // FIXME: Handle nested keypath member lookup. // i.e. cases where 'ExprType' != 'keyPathInfo.baseType'. auto *SD = keyPathInfo.subscript; const auto elementTy = SD->getElementInterfaceType(); if (!elementTy->hasTypeParameter()) return elementTy; // Map is: // { τ_0_0(T) => Circle // τ_1_0(U) => U } auto subs = keyPathInfo.baseType->getMemberSubstitutions(SD); // If the keyPath result type has type parameters, that might affect the // subscript result type. auto keyPathResultTy = getResultTypeOfKeypathDynamicMember(SD)-> mapTypeOutOfContext(); if (keyPathResultTy->hasTypeParameter()) { auto keyPathRootTy = getRootTypeOfKeypathDynamicMember(SD). subst(QueryTypeSubstitutionMap{subs}, LookUpConformanceInModule(CurrModule)); // The result type of the VD. // i.e. 'Circle.center' => 'Point'. auto innerResultTy = getTypeOfMember(VD, keyPathRootTy); if (auto paramTy = keyPathResultTy->getAs<GenericTypeParamType>()) { // Replace keyPath result type in the map with the inner result type. // i.e. Make the map as: // { τ_0_0(T) => Circle // τ_1_0(U) => Point } auto key = paramTy->getCanonicalType()->castTo<GenericTypeParamType>(); subs[key] = innerResultTy; } else { // FIXME: Handle the case where the KeyPath result is generic. // e.g. 'subscript<U>(dynamicMember: KeyPath<T, Box<U>>) -> Bag<U>' // For now, just return the inner type. return innerResultTy; } } // Substitute the element type of the subscript using modified map. // i.e. 'Wrapped<U>' => 'Wrapped<Point>'. return elementTy.subst(QueryTypeSubstitutionMap{subs}, LookUpConformanceInModule(CurrModule)); } } llvm_unreachable("Unhandled DynamicLookupInfo Kind in switch"); } Type getTypeOfMember(const ValueDecl *VD, Type ExprType) { Type T = VD->getInterfaceType(); assert(!T.isNull()); if (ExprType) { Type ContextTy = VD->getDeclContext()->getDeclaredInterfaceType(); if (ContextTy) { // Look through lvalue types and metatypes Type MaybeNominalType = ExprType->getRValueType(); if (auto Metatype = MaybeNominalType->getAs<MetatypeType>()) MaybeNominalType = Metatype->getInstanceType(); if (auto SelfType = MaybeNominalType->getAs<DynamicSelfType>()) MaybeNominalType = SelfType->getSelfType(); // For optional protocol requirements and dynamic dispatch, // strip off optionality from the base type, but only if // we're not actually completing a member of Optional. if (!ContextTy->getOptionalObjectType() && MaybeNominalType->getOptionalObjectType()) MaybeNominalType = MaybeNominalType->getOptionalObjectType(); // For dynamic lookup don't substitute in the base type. if (MaybeNominalType->isAnyObject()) return T; // FIXME: Sometimes ExprType is the type of the member here, // and not the type of the base. That is inconsistent and // should be cleaned up. if (!MaybeNominalType->mayHaveMembers()) return T; // We can't do anything if the base type has unbound generic parameters. if (MaybeNominalType->hasUnboundGenericType()) return T; // For everything else, substitute in the base type. auto Subs = MaybeNominalType->getMemberSubstitutionMap(CurrModule, VD); // Pass in DesugarMemberTypes so that we see the actual // concrete type witnesses instead of type alias types. T = T.subst(Subs, SubstFlags::DesugarMemberTypes); } } return T; } Type getAssociatedTypeType(const AssociatedTypeDecl *ATD) { Type BaseTy = BaseType; if (!BaseTy) BaseTy = ExprType; if (!BaseTy && CurrDeclContext) BaseTy = CurrDeclContext->getInnermostTypeContext() ->getDeclaredTypeInContext(); if (BaseTy) { BaseTy = BaseTy->getInOutObjectType()->getMetatypeInstanceType(); if (auto NTD = BaseTy->getAnyNominal()) { auto *Module = NTD->getParentModule(); auto Conformance = Module->lookupConformance( BaseTy, ATD->getProtocol()); if (Conformance.isConcrete()) { return Conformance.getConcrete()->getTypeWitness( const_cast<AssociatedTypeDecl *>(ATD)); } } } return Type(); } void analyzeActorIsolation(const ValueDecl *VD, Type T, bool &implicitlyAsync, Optional<NotRecommendedReason> &NotRecommended) { auto isolation = getActorIsolation(const_cast<ValueDecl *>(VD)); switch (isolation.getKind()) { case ActorIsolation::ActorInstance: { if (IsCrossActorReference) { implicitlyAsync = true; // TODO: 'NotRecommended' if this is a r-value reference. } break; } case ActorIsolation::GlobalActor: case ActorIsolation::GlobalActorUnsafe: // TODO: Implement. break; case ActorIsolation::Unspecified: case ActorIsolation::Independent: return; } // If the reference is 'async', all types must be 'Sendable'. if (implicitlyAsync && T) { if (isa<VarDecl>(VD)) { if (!isSendableType(CurrDeclContext, T)) { NotRecommended = NotRecommendedReason::CrossActorReference; } } else { assert(isa<FuncDecl>(VD) || isa<SubscriptDecl>(VD)); // Check if the result and the param types are all 'Sendable'. auto *AFT = T->castTo<AnyFunctionType>(); if (!isSendableType(CurrDeclContext, AFT->getResult())) { NotRecommended = NotRecommendedReason::CrossActorReference; } else { for (auto &param : AFT->getParams()) { Type paramType = param.getPlainType(); if (!isSendableType(CurrDeclContext, paramType)) { NotRecommended = NotRecommendedReason::CrossActorReference; break; } } } } } } void addVarDeclRef(const VarDecl *VD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { if (!VD->hasName()) return; const Identifier Name = VD->getName(); assert(!Name.empty() && "name should not be empty"); Type VarType; if (VD->hasInterfaceType()) VarType = getTypeOfMember(VD, dynamicLookupInfo); Optional<NotRecommendedReason> NotRecommended; // "not recommended" in its own getter. if (Kind == LookupKind::ValueInDeclContext) { if (auto accessor = dyn_cast<AccessorDecl>(CurrDeclContext)) { if (accessor->getStorage() == VD && accessor->isGetter()) NotRecommended = NotRecommendedReason::VariableUsedInOwnDefinition; } } bool implicitlyAsync = false; analyzeActorIsolation(VD, VarType, implicitlyAsync, NotRecommended); if (!NotRecommended && implicitlyAsync && !CanCurrDeclContextHandleAsync) { NotRecommended = NotRecommendedReason::InvalidAsyncContext; } CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(VD, Reason, dynamicLookupInfo), expectedTypeContext); Builder.setAssociatedDecl(VD); addLeadingDot(Builder); addValueBaseName(Builder, Name); setClangDeclKeywords(VD, Pairs, Builder); if (NotRecommended) Builder.setNotRecommended(*NotRecommended); if (!VarType) return; if (auto *PD = dyn_cast<ParamDecl>(VD)) { if (Name != Ctx.Id_self && PD->isInOut()) { // It is useful to show inout for function parameters. // But for 'self' it is just noise. VarType = InOutType::get(VarType); } } auto DynamicOrOptional = IsDynamicLookup || VD->getAttrs().hasAttribute<OptionalAttr>(); if (DynamicOrOptional) { // Values of properties that were found on a AnyObject have // Optional<T> type. Same applies to optional members. VarType = OptionalType::get(VarType); } auto genericSig = VD->getInnermostDeclContext()->getGenericSignatureOfContext(); if (VD->isImplicitlyUnwrappedOptional()) addTypeAnnotationForImplicitlyUnwrappedOptional( Builder, VarType, genericSig, DynamicOrOptional); else addTypeAnnotation(Builder, VarType, genericSig); if (implicitlyAsync) Builder.addAnnotatedAsync(); if (isUnresolvedMemberIdealType(VarType)) Builder.setSemanticContext(SemanticContextKind::ExpressionSpecific); } static bool hasInterestingDefaultValues(const AbstractFunctionDecl *func) { if (!func) return false; for (auto param : *func->getParameters()) { switch (param->getDefaultArgumentKind()) { case DefaultArgumentKind::Normal: case DefaultArgumentKind::StoredProperty: case DefaultArgumentKind::Inherited: // FIXME: include this? return true; default: break; } } return false; } /// Build argument patterns for calling. Returns \c true if any content was /// added to \p Builder. If \p declParams is non-empty, the size must match /// with \p typeParams. bool addCallArgumentPatterns(CodeCompletionResultBuilder &Builder, ArrayRef<AnyFunctionType::Param> typeParams, ArrayRef<const ParamDecl *> declParams, GenericSignature genericSig, bool includeDefaultArgs = true) { assert(declParams.empty() || typeParams.size() == declParams.size()); bool modifiedBuilder = false; // Determine whether we should skip this argument because it is defaulted. auto shouldSkipArg = [&](const ParamDecl *PD) -> bool { switch (PD->getDefaultArgumentKind()) { case DefaultArgumentKind::None: return false; case DefaultArgumentKind::Normal: case DefaultArgumentKind::StoredProperty: case DefaultArgumentKind::Inherited: case DefaultArgumentKind::NilLiteral: case DefaultArgumentKind::EmptyArray: case DefaultArgumentKind::EmptyDictionary: return !includeDefaultArgs; #define MAGIC_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \ case DefaultArgumentKind::NAME: #include "swift/AST/MagicIdentifierKinds.def" // Skip parameters that are defaulted to source location or other // caller context information. Users typically don't want to specify // these parameters. return true; } llvm_unreachable("Unhandled DefaultArgumentKind in switch."); }; bool NeedComma = false; // Iterate over each parameter. for (unsigned i = 0; i != typeParams.size(); ++i) { auto &typeParam = typeParams[i]; Identifier argName; Identifier bodyName; bool isIUO = false; if (!declParams.empty()) { auto *PD = declParams[i]; if (shouldSkipArg(PD)) continue; argName = PD->getArgumentName(); bodyName = PD->getParameterName(); isIUO = PD->isImplicitlyUnwrappedOptional(); } else { isIUO = false; argName = typeParam.getLabel(); } bool isVariadic = typeParam.isVariadic(); bool isInOut = typeParam.isInOut(); bool isAutoclosure = typeParam.isAutoClosure(); Type paramTy = typeParam.getPlainType(); if (isVariadic) paramTy = ParamDecl::getVarargBaseTy(paramTy); if (NeedComma) Builder.addComma(); Type contextTy; if (auto typeContext = CurrDeclContext->getInnermostTypeContext()) contextTy = typeContext->getDeclaredTypeInContext(); Builder.addCallParameter(argName, bodyName, eraseArchetypes(paramTy, genericSig), contextTy, isVariadic, isInOut, isIUO, isAutoclosure, /*useUnderscoreLabel=*/false, /*isLabeledTrailingClosure=*/false); modifiedBuilder = true; NeedComma = true; } return modifiedBuilder; } /// Build argument patterns for calling. Returns \c true if any content was /// added to \p Builder. If \p Params is non-nullptr, \F bool addCallArgumentPatterns(CodeCompletionResultBuilder &Builder, const AnyFunctionType *AFT, const ParameterList *Params, GenericSignature genericSig, bool includeDefaultArgs = true) { ArrayRef<const ParamDecl *> declParams; if (Params) declParams = Params->getArray(); return addCallArgumentPatterns(Builder, AFT->getParams(), declParams, genericSig, includeDefaultArgs); } static void addEffectsSpecifiers(CodeCompletionResultBuilder &Builder, const AnyFunctionType *AFT, const AbstractFunctionDecl *AFD, bool forceAsync = false) { assert(AFT != nullptr); // 'async'. if (forceAsync || (AFD && AFD->hasAsync()) || AFT->isAsync()) Builder.addAnnotatedAsync(); // 'throws' or 'rethrows'. if (AFD && AFD->getAttrs().hasAttribute<RethrowsAttr>()) Builder.addAnnotatedRethrows(); else if (AFT->isThrowing()) Builder.addAnnotatedThrows(); } void addPoundAvailable(Optional<StmtKind> ParentKind) { if (ParentKind != StmtKind::If && ParentKind != StmtKind::Guard) return; CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::ExpressionSpecific, expectedTypeContext); Builder.addBaseName("available"); Builder.addLeftParen(); Builder.addSimpleTypedParameter("Platform", /*IsVarArg=*/true); Builder.addComma(); Builder.addTextChunk("*"); Builder.addRightParen(); } void addPoundSelector(bool needPound) { // #selector is only available when the Objective-C runtime is. if (!Ctx.LangOpts.EnableObjCInterop) return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); if (needPound) Builder.addTextChunk("#selector"); else Builder.addTextChunk("selector"); Builder.addLeftParen(); Builder.addSimpleTypedParameter("@objc method", /*IsVarArg=*/false); Builder.addRightParen(); Builder.addTypeAnnotation("Selector"); // This function is called only if the context type is 'Selector'. Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::Identical); } void addPoundKeyPath(bool needPound) { // #keyPath is only available when the Objective-C runtime is. if (!Ctx.LangOpts.EnableObjCInterop) return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); if (needPound) Builder.addTextChunk("#keyPath"); else Builder.addTextChunk("keyPath"); Builder.addLeftParen(); Builder.addSimpleTypedParameter("@objc property sequence", /*IsVarArg=*/false); Builder.addRightParen(); Builder.addTypeAnnotation("String"); // This function is called only if the context type is 'String'. Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::Identical); } SemanticContextKind getSemanticContextKind(const ValueDecl *VD) { // FIXME: to get the corect semantic context we need to know how lookup // would have found the VD. For now, just infer a reasonable semantics. if (!VD) return SemanticContextKind::CurrentModule; DeclContext *calleeDC = VD->getDeclContext(); if (calleeDC->isTypeContext()) // FIXME: We should distinguish CurrentNominal and Super. We need to // propagate the base type to do that. return SemanticContextKind::CurrentNominal; if (calleeDC->isLocalContext()) return SemanticContextKind::Local; if (calleeDC->getParentModule() == CurrModule) return SemanticContextKind::CurrentModule; return SemanticContextKind::OtherModule; } void addSubscriptCallPattern( const AnyFunctionType *AFT, const SubscriptDecl *SD, const Optional<SemanticContextKind> SemanticContext = None) { foundFunction(AFT); GenericSignature genericSig; if (SD) genericSig = SD->getGenericSignatureOfContext(); CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, SD ? CodeCompletionResult::ResultKind::Declaration : CodeCompletionResult::ResultKind::Pattern, SemanticContext ? *SemanticContext : getSemanticContextKind(SD), expectedTypeContext); if (SD) { Builder.setAssociatedDecl(SD); setClangDeclKeywords(SD, Pairs, Builder); } if (!HaveLParen) Builder.addLeftBracket(); else Builder.addAnnotatedLeftBracket(); ArrayRef<const ParamDecl *> declParams; if (SD) declParams = SD->getIndices()->getArray(); addCallArgumentPatterns(Builder, AFT->getParams(), declParams, genericSig); if (!HaveLParen) Builder.addRightBracket(); else Builder.addAnnotatedRightBracket(); if (SD && SD->isImplicitlyUnwrappedOptional()) addTypeAnnotationForImplicitlyUnwrappedOptional(Builder, AFT->getResult(), genericSig); else addTypeAnnotation(Builder, AFT->getResult(), genericSig); } void addFunctionCallPattern( const AnyFunctionType *AFT, const AbstractFunctionDecl *AFD = nullptr, const Optional<SemanticContextKind> SemanticContext = None) { GenericSignature genericSig; if (AFD) genericSig = AFD->getGenericSignatureOfContext(); // Add the pattern, possibly including any default arguments. auto addPattern = [&](ArrayRef<const ParamDecl *> declParams = {}, bool includeDefaultArgs = true) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, AFD ? CodeCompletionResult::ResultKind::Declaration : CodeCompletionResult::ResultKind::Pattern, SemanticContext ? *SemanticContext : getSemanticContextKind(AFD), expectedTypeContext); if (AFD) { Builder.setAssociatedDecl(AFD); setClangDeclKeywords(AFD, Pairs, Builder); } if (!HaveLParen) Builder.addLeftParen(); else Builder.addAnnotatedLeftParen(); addCallArgumentPatterns(Builder, AFT->getParams(), declParams, genericSig, includeDefaultArgs); // The rparen matches the lparen here so that we insert both or neither. if (!HaveLParen) Builder.addRightParen(); else Builder.addAnnotatedRightParen(); addEffectsSpecifiers(Builder, AFT, AFD); if (AFD && AFD->isImplicitlyUnwrappedOptional()) addTypeAnnotationForImplicitlyUnwrappedOptional(Builder, AFT->getResult(), genericSig); else addTypeAnnotation(Builder, AFT->getResult(), genericSig); if (AFT->isAsync() && !CanCurrDeclContextHandleAsync) { Builder.setNotRecommended(NotRecommendedReason::InvalidAsyncContext); } }; if (!AFD || !AFD->getInterfaceType()->is<AnyFunctionType>()) { // Probably, calling closure type expression. foundFunction(AFT); addPattern(); return; } else { // Calling function or method. foundFunction(AFD); // FIXME: Hack because we don't know we are calling instance // method or not. There's invariant that funcTy is derived from AFD. // Only if we are calling instance method on meta type, AFT is still // curried. So we should be able to detect that by comparing curried level // of AFT and the interface type of AFD. auto getCurriedLevel = [](const AnyFunctionType *funcTy) -> unsigned { unsigned level = 0; while ((funcTy = funcTy->getResult()->getAs<AnyFunctionType>())) ++level; return level; }; bool isImplicitlyCurriedInstanceMethod = (AFD->hasImplicitSelfDecl() && getCurriedLevel(AFT) == getCurriedLevel( AFD->getInterfaceType()->castTo<AnyFunctionType>()) && // NOTE: shouldn't be necessary, but just in case curried level check // is insufficient. AFT->getParams().size() == 1 && AFT->getParams()[0].getLabel().empty()); if (isImplicitlyCurriedInstanceMethod) { addPattern({AFD->getImplicitSelfDecl()}, /*includeDefaultArgs=*/true); } else { if (hasInterestingDefaultValues(AFD)) addPattern(AFD->getParameters()->getArray(), /*includeDefaultArgs=*/false); addPattern(AFD->getParameters()->getArray(), /*includeDefaultArgs=*/true); } } } bool isImplicitlyCurriedInstanceMethod(const AbstractFunctionDecl *FD) { if (FD->isStatic()) return false; switch (Kind) { case LookupKind::ValueExpr: return ExprType->is<AnyMetatypeType>(); case LookupKind::ValueInDeclContext: if (InsideStaticMethod) return FD->getDeclContext() == CurrentMethod->getDeclContext(); if (auto Init = dyn_cast<Initializer>(CurrDeclContext)) { if (auto PatInit = dyn_cast<PatternBindingInitializer>(Init)) { if (PatInit->getInitializedLazyVar()) return false; } return FD->getDeclContext() == Init->getInnermostTypeContext(); } return false; case LookupKind::EnumElement: case LookupKind::Type: case LookupKind::TypeInDeclContext: case LookupKind::GenericRequirement: llvm_unreachable("cannot have a method call while doing a " "type completion"); case LookupKind::ImportFromModule: return false; } llvm_unreachable("Unhandled LookupKind in switch."); } void addMethodCall(const FuncDecl *FD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { if (FD->getBaseIdentifier().empty()) return; foundFunction(FD); const Identifier Name = FD->getBaseIdentifier(); assert(!Name.empty() && "name should not be empty"); Type FunctionType = getTypeOfMember(FD, dynamicLookupInfo); assert(FunctionType); auto AFT = FunctionType->getAs<AnyFunctionType>(); bool IsImplicitlyCurriedInstanceMethod = false; if (FD->hasImplicitSelfDecl()) { IsImplicitlyCurriedInstanceMethod = isImplicitlyCurriedInstanceMethod(FD); // Strip off '(_ self: Self)' if needed. if (AFT && !IsImplicitlyCurriedInstanceMethod) { AFT = AFT->getResult()->getAs<AnyFunctionType>(); // Check for duplicates with the adjusted type too. if (isDuplicate(FD, AFT)) return; } } bool trivialTrailingClosure = false; if (AFT && !IsImplicitlyCurriedInstanceMethod) trivialTrailingClosure = hasTrivialTrailingClosure(FD, AFT); Optional<NotRecommendedReason> NotRecommended; bool implictlyAsync = false; analyzeActorIsolation(FD, AFT, implictlyAsync, NotRecommended); if (!NotRecommended && !IsImplicitlyCurriedInstanceMethod && ((AFT && AFT->isAsync()) || implictlyAsync) && !CanCurrDeclContextHandleAsync) { NotRecommended = NotRecommendedReason::InvalidAsyncContext; } // Add the method, possibly including any default arguments. auto addMethodImpl = [&](bool includeDefaultArgs = true, bool trivialTrailingClosure = false) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(FD, Reason, dynamicLookupInfo), expectedTypeContext); setClangDeclKeywords(FD, Pairs, Builder); Builder.setAssociatedDecl(FD); if (NotRecommended) Builder.setNotRecommended(*NotRecommended); addLeadingDot(Builder); addValueBaseName(Builder, Name); if (IsDynamicLookup) Builder.addDynamicLookupMethodCallTail(); else if (FD->getAttrs().hasAttribute<OptionalAttr>()) Builder.addOptionalMethodCallTail(); if (!AFT) { addTypeAnnotation(Builder, FunctionType, FD->getGenericSignatureOfContext()); return; } if (IsImplicitlyCurriedInstanceMethod) { Builder.addLeftParen(); addCallArgumentPatterns(Builder, AFT->getParams(), {FD->getImplicitSelfDecl()}, FD->getGenericSignatureOfContext(), includeDefaultArgs); Builder.addRightParen(); } else if (trivialTrailingClosure) { Builder.addBraceStmtWithCursor(" { code }"); addEffectsSpecifiers(Builder, AFT, FD, implictlyAsync); } else { Builder.addLeftParen(); addCallArgumentPatterns(Builder, AFT, FD->getParameters(), FD->getGenericSignatureOfContext(), includeDefaultArgs); Builder.addRightParen(); addEffectsSpecifiers(Builder, AFT, FD, implictlyAsync); } // Build type annotation. Type ResultType = AFT->getResult(); // As we did with parameters in addParamPatternFromFunction, // for regular methods we'll print '!' after implicitly // unwrapped optional results. bool IsIUO = !IsImplicitlyCurriedInstanceMethod && FD->isImplicitlyUnwrappedOptional(); PrintOptions PO; PO.OpaqueReturnTypePrinting = PrintOptions::OpaqueReturnTypePrintingMode::WithoutOpaqueKeyword; PO.PrintOptionalAsImplicitlyUnwrapped = IsIUO; if (auto typeContext = CurrDeclContext->getInnermostTypeContext()) PO.setBaseType(typeContext->getDeclaredTypeInContext()); Type AnnotationTy = eraseArchetypes(ResultType, FD->getGenericSignatureOfContext()); if (Builder.shouldAnnotateResults()) { Builder.withNestedGroup( CodeCompletionString::Chunk::ChunkKind::TypeAnnotationBegin, [&] { AnnotatedTypePrinter printer(Builder); if (IsImplicitlyCurriedInstanceMethod) { auto *FnType = AnnotationTy->castTo<AnyFunctionType>(); AnyFunctionType::printParams(FnType->getParams(), printer, PrintOptions()); AnnotationTy = FnType->getResult(); printer.printText(" -> "); } // What's left is the result type. if (AnnotationTy->isVoid()) AnnotationTy = Ctx.getVoidDecl()->getDeclaredInterfaceType(); AnnotationTy.print(printer, PO); }); } else { llvm::SmallString<32> TypeStr; llvm::raw_svector_ostream OS(TypeStr); if (IsImplicitlyCurriedInstanceMethod) { auto *FnType = AnnotationTy->castTo<AnyFunctionType>(); AnyFunctionType::printParams(FnType->getParams(), OS); AnnotationTy = FnType->getResult(); OS << " -> "; } // What's left is the result type. if (AnnotationTy->isVoid()) AnnotationTy = Ctx.getVoidDecl()->getDeclaredInterfaceType(); AnnotationTy.print(OS, PO); Builder.addTypeAnnotation(TypeStr); } Builder.setExpectedTypeRelation(calculateMaxTypeRelation( ResultType, expectedTypeContext, CurrDeclContext)); if (isUnresolvedMemberIdealType(ResultType)) Builder.setSemanticContext(SemanticContextKind::ExpressionSpecific); if (!IsImplicitlyCurriedInstanceMethod && expectedTypeContext.requiresNonVoid() && ResultType->isVoid()) { Builder.setExpectedTypeRelation(CodeCompletionResult::Invalid); } }; if (!AFT || IsImplicitlyCurriedInstanceMethod) { addMethodImpl(); } else { if (trivialTrailingClosure) addMethodImpl(/*includeDefaultArgs=*/false, /*trivialTrailingClosure=*/true); if (hasInterestingDefaultValues(FD)) addMethodImpl(/*includeDefaultArgs=*/false); addMethodImpl(/*includeDefaultArgs=*/true); } } void addConstructorCall(const ConstructorDecl *CD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo, Optional<Type> BaseType, Optional<Type> Result, bool IsOnType = true, Identifier addName = Identifier()) { foundFunction(CD); Type MemberType = getTypeOfMember(CD, BaseType.getValueOr(ExprType)); AnyFunctionType *ConstructorType = nullptr; if (auto MemberFuncType = MemberType->getAs<AnyFunctionType>()) ConstructorType = MemberFuncType->getResult() ->castTo<AnyFunctionType>(); bool needInit = false; if (!IsOnType) { assert(addName.empty()); needInit = true; } else if (addName.empty() && HaveDot) { needInit = true; } // If we won't be able to provide a result, bail out. if (!ConstructorType && addName.empty() && !needInit) return; // Add the constructor, possibly including any default arguments. auto addConstructorImpl = [&](bool includeDefaultArgs = true) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(CD, Reason, dynamicLookupInfo), expectedTypeContext); setClangDeclKeywords(CD, Pairs, Builder); Builder.setAssociatedDecl(CD); if (needInit) { assert(addName.empty()); addLeadingDot(Builder); Builder.addBaseName("init"); } else if (!addName.empty()) { Builder.addBaseName(addName.str()); } if (!ConstructorType) { addTypeAnnotation(Builder, MemberType, CD->getGenericSignatureOfContext()); return; } if (!HaveLParen) Builder.addLeftParen(); else Builder.addAnnotatedLeftParen(); addCallArgumentPatterns(Builder, ConstructorType, CD->getParameters(), CD->getGenericSignatureOfContext(), includeDefaultArgs); // The rparen matches the lparen here so that we insert both or neither. if (!HaveLParen) Builder.addRightParen(); else Builder.addAnnotatedRightParen(); addEffectsSpecifiers(Builder, ConstructorType, CD); if (!Result.hasValue()) Result = ConstructorType->getResult(); if (CD->isImplicitlyUnwrappedOptional()) { addTypeAnnotationForImplicitlyUnwrappedOptional( Builder, *Result, CD->getGenericSignatureOfContext()); } else { addTypeAnnotation(Builder, *Result, CD->getGenericSignatureOfContext()); } if (ConstructorType->isAsync() && !CanCurrDeclContextHandleAsync) { Builder.setNotRecommended(NotRecommendedReason::InvalidAsyncContext); } }; if (ConstructorType && hasInterestingDefaultValues(CD)) addConstructorImpl(/*includeDefaultArgs*/ false); addConstructorImpl(); } void addConstructorCallsForType(Type type, Identifier name, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { if (!Ctx.LangOpts.CodeCompleteInitsInPostfixExpr) return; assert(CurrDeclContext); auto results = swift::lookupSemanticMember(const_cast<DeclContext *>(CurrDeclContext), type, DeclBaseName::createConstructor()); for (const auto &entry : results.allResults()) { auto *init = cast<ConstructorDecl>(entry.getValueDecl()); if (init->shouldHideFromEditor()) continue; addConstructorCall(cast<ConstructorDecl>(init), Reason, dynamicLookupInfo, type, None, /*IsOnType=*/true, name); } } void addSubscriptCall(const SubscriptDecl *SD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { // Don't add subscript call to unqualified completion. if (!ExprType) return; // Subscript after '.' is valid only after type part of Swift keypath // expression. (e.g. '\TyName.SubTy.[0]) if (HaveDot && !IsAfterSwiftKeyPathRoot) return; auto subscriptType = getTypeOfMember(SD, dynamicLookupInfo)->getAs<AnyFunctionType>(); if (!subscriptType) return; Optional<NotRecommendedReason> NotRecommended; bool implictlyAsync = false; analyzeActorIsolation(SD, subscriptType, implictlyAsync, NotRecommended); if (!NotRecommended && implictlyAsync && !CanCurrDeclContextHandleAsync) { NotRecommended = NotRecommendedReason::InvalidAsyncContext; } CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(SD, Reason, dynamicLookupInfo), expectedTypeContext); Builder.setAssociatedDecl(SD); setClangDeclKeywords(SD, Pairs, Builder); if (NotRecommended) Builder.setNotRecommended(*NotRecommended); // '\TyName#^TOKEN^#' requires leading dot. if (!HaveDot && IsAfterSwiftKeyPathRoot) Builder.addLeadingDot(); if (NeedOptionalUnwrap) { Builder.setNumBytesToErase(NumBytesToEraseForOptionalUnwrap); Builder.addQuestionMark(); } Builder.addLeftBracket(); addCallArgumentPatterns(Builder, subscriptType, SD->getIndices(), SD->getGenericSignatureOfContext(), true); Builder.addRightBracket(); // Add a type annotation. Type resultTy = subscriptType->getResult(); if (IsDynamicLookup) { // Values of properties that were found on a AnyObject have // Optional<T> type. resultTy = OptionalType::get(resultTy); } if (implictlyAsync) Builder.addAnnotatedAsync(); addTypeAnnotation(Builder, resultTy, SD->getGenericSignatureOfContext()); } void addNominalTypeRef(const NominalTypeDecl *NTD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(NTD, Reason, dynamicLookupInfo), expectedTypeContext); Builder.setAssociatedDecl(NTD); setClangDeclKeywords(NTD, Pairs, Builder); addLeadingDot(Builder); Builder.addBaseName(NTD->getName().str()); addTypeAnnotation(Builder, NTD->getDeclaredType()); // Override the type relation for NominalTypes. Use the better relation // for the metatypes and the instance type. For example, // // func receiveInstance(_: Int) {} // func receiveMetatype(_: Int.Type) {} // // We want to suggest 'Int' as 'Identical' for both arguments. Builder.setExpectedTypeRelation(std::max( calculateMaxTypeRelation(NTD->getDeclaredInterfaceType(), expectedTypeContext, CurrDeclContext), calculateMaxTypeRelation(NTD->getInterfaceType(), expectedTypeContext, CurrDeclContext))); } void addTypeAliasRef(const TypeAliasDecl *TAD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(TAD, Reason, dynamicLookupInfo), expectedTypeContext); Builder.setAssociatedDecl(TAD); setClangDeclKeywords(TAD, Pairs, Builder); addLeadingDot(Builder); Builder.addBaseName(TAD->getName().str()); if (auto underlyingType = TAD->getUnderlyingType()) { if (underlyingType->hasError()) { Type parentType; if (auto nominal = TAD->getDeclContext()->getSelfNominalTypeDecl()) { parentType = nominal->getDeclaredInterfaceType(); } addTypeAnnotation( Builder, TypeAliasType::get(const_cast<TypeAliasDecl *>(TAD), parentType, SubstitutionMap(), underlyingType)); } else { addTypeAnnotation(Builder, underlyingType); } } } void addGenericTypeParamRef(const GenericTypeParamDecl *GP, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(GP, Reason, dynamicLookupInfo), expectedTypeContext); setClangDeclKeywords(GP, Pairs, Builder); Builder.setAssociatedDecl(GP); addLeadingDot(Builder); Builder.addBaseName(GP->getName().str()); addTypeAnnotation(Builder, GP->getDeclaredInterfaceType()); } void addAssociatedTypeRef(const AssociatedTypeDecl *AT, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(AT, Reason, dynamicLookupInfo), expectedTypeContext); setClangDeclKeywords(AT, Pairs, Builder); Builder.setAssociatedDecl(AT); addLeadingDot(Builder); Builder.addBaseName(AT->getName().str()); if (Type T = getAssociatedTypeType(AT)) addTypeAnnotation(Builder, T); } void addPrecedenceGroupRef(PrecedenceGroupDecl *PGD) { auto semanticContext = getSemanticContext(PGD, DeclVisibilityKind::VisibleAtTopLevel, {}); CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::Declaration, semanticContext, {}); builder.addBaseName(PGD->getName().str()); builder.setAssociatedDecl(PGD); }; void addEnumElementRef(const EnumElementDecl *EED, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo, bool HasTypeContext) { if (!EED->hasName() || !EED->isAccessibleFrom(CurrDeclContext) || EED->shouldHideFromEditor()) return; CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, HasTypeContext ? SemanticContextKind::ExpressionSpecific : getSemanticContext(EED, Reason, dynamicLookupInfo), expectedTypeContext); Builder.setAssociatedDecl(EED); setClangDeclKeywords(EED, Pairs, Builder); addLeadingDot(Builder); addValueBaseName(Builder, EED->getBaseIdentifier()); // Enum element is of function type; (Self.type) -> Self or // (Self.Type) -> (Args...) -> Self. Type EnumType = getTypeOfMember(EED, dynamicLookupInfo); if (EnumType->is<AnyFunctionType>()) EnumType = EnumType->castTo<AnyFunctionType>()->getResult(); if (EnumType->is<FunctionType>()) { Builder.addLeftParen(); addCallArgumentPatterns(Builder, EnumType->castTo<FunctionType>(), EED->getParameterList(), EED->getGenericSignatureOfContext()); Builder.addRightParen(); // Extract result as the enum type. EnumType = EnumType->castTo<FunctionType>()->getResult(); } addTypeAnnotation(Builder, EnumType, EED->getGenericSignatureOfContext()); if (isUnresolvedMemberIdealType(EnumType)) Builder.setSemanticContext(SemanticContextKind::ExpressionSpecific); } void addKeyword(StringRef Name, Type TypeAnnotation = Type(), SemanticContextKind SK = SemanticContextKind::None, CodeCompletionKeywordKind KeyKind = CodeCompletionKeywordKind::None, unsigned NumBytesToErase = 0) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SK, expectedTypeContext); addLeadingDot(Builder); Builder.addKeyword(Name); Builder.setKeywordKind(KeyKind); if (TypeAnnotation) addTypeAnnotation(Builder, TypeAnnotation); if (NumBytesToErase > 0) Builder.setNumBytesToErase(NumBytesToErase); } void addKeyword(StringRef Name, StringRef TypeAnnotation, CodeCompletionKeywordKind KeyKind = CodeCompletionKeywordKind::None) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, expectedTypeContext); addLeadingDot(Builder); Builder.addKeyword(Name); Builder.setKeywordKind(KeyKind); if (!TypeAnnotation.empty()) Builder.addTypeAnnotation(TypeAnnotation); } void addDeclAttrParamKeyword(StringRef Name, StringRef Annotation, bool NeedSpecify) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, expectedTypeContext); Builder.addDeclAttrParamKeyword(Name, Annotation, NeedSpecify); } void addDeclAttrKeyword(StringRef Name, StringRef Annotation) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, expectedTypeContext); Builder.addDeclAttrKeyword(Name, Annotation); } /// Add the compound function name for the given function. /// Returns \c true if the compound function name is actually used. bool addCompoundFunctionNameIfDesiable(AbstractFunctionDecl *AFD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { auto funcTy = getTypeOfMember(AFD, dynamicLookupInfo)->getAs<AnyFunctionType>(); bool dropCurryLevel = funcTy && AFD->getDeclContext()->isTypeContext() && !isImplicitlyCurriedInstanceMethod(AFD); if (dropCurryLevel) funcTy = funcTy->getResult()->getAs<AnyFunctionType>(); bool useFunctionReference = PreferFunctionReferencesToCalls; if (!useFunctionReference && funcTy) { auto maxRel = calculateMaxTypeRelation(funcTy, expectedTypeContext, CurrDeclContext); useFunctionReference = maxRel >= CodeCompletionResult::ExpectedTypeRelation::Convertible; } if (!useFunctionReference) return false; // Check for duplicates with the adjusted type too. if (dropCurryLevel && isDuplicate(AFD, funcTy)) return true; CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(AFD, Reason, dynamicLookupInfo), expectedTypeContext); setClangDeclKeywords(AFD, Pairs, Builder); Builder.setAssociatedDecl(AFD); // Base name addLeadingDot(Builder); addValueBaseName(Builder, AFD->getBaseName()); // Add the argument labels. const auto ArgLabels = AFD->getName().getArgumentNames(); if (!ArgLabels.empty()) { if (!HaveLParen) Builder.addLeftParen(); else Builder.addAnnotatedLeftParen(); for (auto ArgLabel : ArgLabels) { if (ArgLabel.empty()) Builder.addTextChunk("_"); else Builder.addTextChunk(ArgLabel.str()); Builder.addTextChunk(":"); } Builder.addRightParen(); } if (funcTy) addTypeAnnotation(Builder, funcTy, AFD->getGenericSignatureOfContext()); return true; } private: /// Returns true if duplicate checking is enabled (via /// \c shouldCheckForDuplicates) and this decl + type combination has been /// checked previously. Returns false otherwise. bool isDuplicate(const ValueDecl *D, Type Ty) { if (!CheckForDuplicates) return false; return !PreviouslySeen.insert({D, Ty}).second; } /// Returns true if duplicate checking is enabled (via /// \c shouldCheckForDuplicates) and this decl has been checked previously /// with the type according to \c getTypeOfMember. Returns false otherwise. bool isDuplicate(const ValueDecl *D, DynamicLookupInfo dynamicLookupInfo) { if (!CheckForDuplicates) return false; Type Ty = getTypeOfMember(D, dynamicLookupInfo); return !PreviouslySeen.insert({D, Ty}).second; } public: // Implement swift::VisibleDeclConsumer. void foundDecl(ValueDecl *D, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) override { assert(Reason != DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal && "Including derived requirement in non-override lookup"); if (D->shouldHideFromEditor()) return; if (IsKeyPathExpr && !KeyPathFilter(D, Reason)) return; if (IsSwiftKeyPathExpr && !SwiftKeyPathFilter(D, Reason)) return; // If we've seen this decl+type before (possible when multiple lookups are // performed e.g. because of ambiguous base types), bail. if (isDuplicate(D, dynamicLookupInfo)) return; // FIXME(InterfaceTypeRequest): Remove this. (void)D->getInterfaceType(); switch (Kind) { case LookupKind::ValueExpr: if (auto *CD = dyn_cast<ConstructorDecl>(D)) { // Do we want compound function names here? if (addCompoundFunctionNameIfDesiable(CD, Reason, dynamicLookupInfo)) return; if (auto MT = ExprType->getAs<AnyMetatypeType>()) { Type Ty = MT->getInstanceType(); assert(Ty && "Cannot find instance type."); // If instance type is type alias, show users that the constructed // type is the typealias instead of the underlying type of the alias. Optional<Type> Result = None; if (!CD->getInterfaceType()->is<ErrorType>() && isa<TypeAliasType>(Ty.getPointer()) && Ty->getDesugaredType() == CD->getResultInterfaceType().getPointer()) { Result = Ty; } // If the expression type is not a static metatype or an archetype, the base // is not a type. Direct call syntax is illegal on values, so we only add // initializer completions if we do not have a left parenthesis and either // the initializer is required, the base type's instance type is not a class, // or this is a 'self' or 'super' reference. if (IsStaticMetatype || IsUnresolvedMember || Ty->is<ArchetypeType>()) addConstructorCall(CD, Reason, dynamicLookupInfo, None, Result, /*isOnType*/ true); else if ((IsSelfRefExpr || IsSuperRefExpr || !Ty->is<ClassType>() || CD->isRequired()) && !HaveLParen) addConstructorCall(CD, Reason, dynamicLookupInfo, None, Result, /*isOnType*/ false); return; } if (!HaveLParen) { auto CDC = dyn_cast<ConstructorDecl>(CurrDeclContext); if (!CDC) return; // For classes, we do not want 'init' completions for 'self' in // non-convenience initializers and for 'super' in convenience initializers. if (ExprType->is<ClassType>()) { if ((IsSelfRefExpr && !CDC->isConvenienceInit()) || (IsSuperRefExpr && CDC->isConvenienceInit())) return; } if (IsSelfRefExpr || IsSuperRefExpr) addConstructorCall(CD, Reason, dynamicLookupInfo, None, None, /*IsOnType=*/false); } return; } if (HaveLParen) return; LLVM_FALLTHROUGH; case LookupKind::ValueInDeclContext: case LookupKind::ImportFromModule: if (auto *VD = dyn_cast<VarDecl>(D)) { addVarDeclRef(VD, Reason, dynamicLookupInfo); return; } if (auto *FD = dyn_cast<FuncDecl>(D)) { // We cannot call operators with a postfix parenthesis syntax. if (FD->isBinaryOperator() || FD->isUnaryOperator()) return; // We cannot call accessors. We use VarDecls and SubscriptDecls to // produce completions that refer to getters and setters. if (isa<AccessorDecl>(FD)) return; // Do we want compound function names here? if (addCompoundFunctionNameIfDesiable(FD, Reason, dynamicLookupInfo)) return; addMethodCall(FD, Reason, dynamicLookupInfo); // SE-0253: Callable values of user-defined nominal types. if (FD->isCallAsFunctionMethod() && !HaveDot && (!ExprType || !ExprType->is<AnyMetatypeType>())) { Type funcType = getTypeOfMember(FD, dynamicLookupInfo) ->castTo<AnyFunctionType>() ->getResult(); // Check for duplicates with the adjusted type too. if (isDuplicate(FD, funcType)) return; addFunctionCallPattern( funcType->castTo<AnyFunctionType>(), FD, getSemanticContext(FD, Reason, dynamicLookupInfo)); } return; } if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) { addNominalTypeRef(NTD, Reason, dynamicLookupInfo); addConstructorCallsForType(NTD->getDeclaredInterfaceType(), NTD->getName(), Reason, dynamicLookupInfo); return; } if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) { addTypeAliasRef(TAD, Reason, dynamicLookupInfo); auto type = TAD->mapTypeIntoContext(TAD->getDeclaredInterfaceType()); if (type->mayHaveMembers()) addConstructorCallsForType(type, TAD->getName(), Reason, dynamicLookupInfo); return; } if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) { addGenericTypeParamRef(GP, Reason, dynamicLookupInfo); for (auto *protocol : GP->getConformingProtocols()) addConstructorCallsForType(protocol->getDeclaredInterfaceType(), GP->getName(), Reason, dynamicLookupInfo); return; } if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) { addAssociatedTypeRef(AT, Reason, dynamicLookupInfo); return; } if (auto *EED = dyn_cast<EnumElementDecl>(D)) { addEnumElementRef(EED, Reason, dynamicLookupInfo, /*HasTypeContext=*/false); return; } // Swift key path allows .[0] if (auto *SD = dyn_cast<SubscriptDecl>(D)) { addSubscriptCall(SD, Reason, dynamicLookupInfo); return; } return; case LookupKind::EnumElement: handleEnumElement(D, Reason, dynamicLookupInfo); return; case LookupKind::Type: case LookupKind::TypeInDeclContext: if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) { addNominalTypeRef(NTD, Reason, dynamicLookupInfo); return; } if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) { addGenericTypeParamRef(GP, Reason, dynamicLookupInfo); return; } LLVM_FALLTHROUGH; case LookupKind::GenericRequirement: if (TypeAliasDecl *TAD = dyn_cast<TypeAliasDecl>(D)) { if (Kind == LookupKind::GenericRequirement && !canBeUsedAsRequirementFirstType(BaseType, TAD)) return; addTypeAliasRef(TAD, Reason, dynamicLookupInfo); return; } if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) { addAssociatedTypeRef(AT, Reason, dynamicLookupInfo); return; } return; } } bool handleEnumElement(ValueDecl *D, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { if (auto *EED = dyn_cast<EnumElementDecl>(D)) { addEnumElementRef(EED, Reason, dynamicLookupInfo, /*HasTypeContext=*/true); return true; } else if (auto *ED = dyn_cast<EnumDecl>(D)) { llvm::DenseSet<EnumElementDecl *> Elements; ED->getAllElements(Elements); for (auto *Ele : Elements) { addEnumElementRef(Ele, Reason, dynamicLookupInfo, /*HasTypeContext=*/true); } return true; } return false; } bool tryTupleExprCompletions(Type ExprType) { auto *TT = ExprType->getAs<TupleType>(); if (!TT) return false; unsigned Index = 0; for (auto TupleElt : TT->getElements()) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Pattern, SemanticContextKind::CurrentNominal, expectedTypeContext); addLeadingDot(Builder); if (TupleElt.hasName()) { Builder.addBaseName(TupleElt.getName().str()); } else { llvm::SmallString<4> IndexStr; { llvm::raw_svector_ostream OS(IndexStr); OS << Index; } Builder.addBaseName(IndexStr.str()); } addTypeAnnotation(Builder, TupleElt.getType()); ++Index; } return true; } bool tryFunctionCallCompletions(Type ExprType, const ValueDecl *VD, Optional<SemanticContextKind> SemanticContext = None) { ExprType = ExprType->getRValueType(); if (auto AFT = ExprType->getAs<AnyFunctionType>()) { if (auto *AFD = dyn_cast_or_null<AbstractFunctionDecl>(VD)) { addFunctionCallPattern(AFT, AFD, SemanticContext); } else { addFunctionCallPattern(AFT); } return true; } return false; } bool tryModuleCompletions(Type ExprType, bool TypesOnly = false) { if (auto MT = ExprType->getAs<ModuleType>()) { ModuleDecl *M = MT->getModule(); // Only lookup this module's symbols from the cache if it is not the // current module. if (M == CurrModule) return false; // If the module is shadowed by a separately imported overlay(s), look up // the symbols from the overlay(s) instead. SmallVector<ModuleDecl *, 1> ShadowingOrOriginal; if (auto *SF = CurrDeclContext->getParentSourceFile()) { SF->getSeparatelyImportedOverlays(M, ShadowingOrOriginal); if (ShadowingOrOriginal.empty()) ShadowingOrOriginal.push_back(M); } for (ModuleDecl *M: ShadowingOrOriginal) { RequestedResultsTy Request = RequestedResultsTy::fromModule(M) .needLeadingDot(needDot()) .withModuleQualifier(false); if (TypesOnly) Request = Request.onlyTypes(); RequestedCachedResults.push_back(Request); } return true; } return false; } /// If the given ExprType is optional, this adds completions for the unwrapped /// type. /// /// \return true if the given type was Optional . bool tryUnwrappedCompletions(Type ExprType, bool isIUO) { // FIXME: consider types convertible to T?. ExprType = ExprType->getRValueType(); // FIXME: We don't always pass down whether a type is from an // unforced IUO. if (isIUO) { if (Type Unwrapped = ExprType->getOptionalObjectType()) { lookupVisibleMemberDecls(*this, Unwrapped, CurrDeclContext, IncludeInstanceMembers, /*includeDerivedRequirements*/false, /*includeProtocolExtensionMembers*/true); return true; } assert(IsUnwrappedOptional && "IUOs should be optional if not bound/forced"); return false; } if (Type Unwrapped = ExprType->getOptionalObjectType()) { llvm::SaveAndRestore<bool> ChangeNeedOptionalUnwrap(NeedOptionalUnwrap, true); if (DotLoc.isValid()) { // Let's not erase the dot if the completion is after a swift key path // root because \A?.?.member is the correct way to access wrapped type // member from an optional key path root. auto loc = IsAfterSwiftKeyPathRoot ? DotLoc.getAdvancedLoc(1) : DotLoc; NumBytesToEraseForOptionalUnwrap = Ctx.SourceMgr.getByteDistance( loc, Ctx.SourceMgr.getCodeCompletionLoc()); } else { NumBytesToEraseForOptionalUnwrap = 0; } if (NumBytesToEraseForOptionalUnwrap <= CodeCompletionResult::MaxNumBytesToErase) { if (!tryTupleExprCompletions(Unwrapped)) { lookupVisibleMemberDecls(*this, Unwrapped, CurrDeclContext, IncludeInstanceMembers, /*includeDerivedRequirements*/false, /*includeProtocolExtensionMembers*/true); } } return true; } return false; } void getPostfixKeywordCompletions(Type ExprType, Expr *ParsedExpr) { if (IsSuperRefExpr) return; if (!ExprType->getAs<ModuleType>()) { addKeyword(getTokenText(tok::kw_self), ExprType->getRValueType(), SemanticContextKind::CurrentNominal, CodeCompletionKeywordKind::kw_self); } if (isa<TypeExpr>(ParsedExpr)) { if (auto *T = ExprType->getAs<AnyMetatypeType>()) { auto instanceTy = T->getInstanceType(); if (instanceTy->isAnyExistentialType()) { addKeyword("Protocol", MetatypeType::get(instanceTy), SemanticContextKind::CurrentNominal); addKeyword("Type", ExistentialMetatypeType::get(instanceTy), SemanticContextKind::CurrentNominal); } else { addKeyword("Type", MetatypeType::get(instanceTy), SemanticContextKind::CurrentNominal); } } } } void getValueExprCompletions(Type ExprType, ValueDecl *VD = nullptr) { Kind = LookupKind::ValueExpr; NeedLeadingDot = !HaveDot; ExprType = ExprType->getRValueType(); assert(!ExprType->hasTypeParameter()); this->ExprType = ExprType; // Open existential types, so that lookupVisibleMemberDecls() can properly // substitute them. bool WasOptional = false; if (auto OptionalType = ExprType->getOptionalObjectType()) { ExprType = OptionalType; WasOptional = true; } if (!ExprType->getMetatypeInstanceType()->isAnyObject()) if (ExprType->isAnyExistentialType()) ExprType = OpenedArchetypeType::getAny(ExprType); if (!IsSelfRefExpr && !IsSuperRefExpr && ExprType->getAnyNominal() && ExprType->getAnyNominal()->isActor()) { IsCrossActorReference = true; } if (WasOptional) ExprType = OptionalType::get(ExprType); // Handle special cases bool isIUO = VD && VD->isImplicitlyUnwrappedOptional(); if (tryFunctionCallCompletions(ExprType, VD)) return; if (tryModuleCompletions(ExprType)) return; if (tryTupleExprCompletions(ExprType)) return; // Don't check/return so we still add the members of Optional itself below tryUnwrappedCompletions(ExprType, isIUO); lookupVisibleMemberDecls(*this, ExprType, CurrDeclContext, IncludeInstanceMembers, /*includeDerivedRequirements*/false, /*includeProtocolExtensionMembers*/true); } void collectOperators(SmallVectorImpl<OperatorDecl *> &results) { assert(CurrDeclContext); for (auto import : namelookup::getAllImports(CurrDeclContext)) import.importedModule->getOperatorDecls(results); } void addPostfixBang(Type resultType) { CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::BuiltinOperator, SemanticContextKind::None, {}); // FIXME: we can't use the exclamation mark chunk kind, or it isn't // included in the completion name. builder.addTextChunk("!"); assert(resultType); addTypeAnnotation(builder, resultType); } void addPostfixOperatorCompletion(OperatorDecl *op, Type resultType) { // FIXME: we should get the semantic context of the function, not the // operator decl. auto semanticContext = getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel, {}); CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::Declaration, semanticContext, {}); // FIXME: handle variable amounts of space. if (HaveLeadingSpace) builder.setNumBytesToErase(1); builder.setAssociatedDecl(op); builder.addBaseName(op->getName().str()); assert(resultType); addTypeAnnotation(builder, resultType); } void tryPostfixOperator(Expr *expr, PostfixOperatorDecl *op) { ConcreteDeclRef referencedDecl; FunctionType *funcTy = getTypeOfCompletionOperator( const_cast<DeclContext *>(CurrDeclContext), expr, op->getName(), DeclRefKind::PostfixOperator, referencedDecl); if (!funcTy) return; // TODO: Use referencedDecl (FuncDecl) instead of 'op' (OperatorDecl). addPostfixOperatorCompletion(op, funcTy->getResult()); } void addAssignmentOperator(Type RHSType, Type resultType) { CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::BuiltinOperator, SemanticContextKind::None, {}); if (HaveLeadingSpace) builder.addAnnotatedWhitespace(" "); else builder.addWhitespace(" "); builder.addEqual(); builder.addWhitespace(" "); assert(RHSType && resultType); Type contextTy; if (auto typeContext = CurrDeclContext->getInnermostTypeContext()) contextTy = typeContext->getDeclaredTypeInContext(); builder.addCallParameter(Identifier(), RHSType, contextTy); addTypeAnnotation(builder, resultType); } void addInfixOperatorCompletion(OperatorDecl *op, Type resultType, Type RHSType) { // FIXME: we should get the semantic context of the function, not the // operator decl. auto semanticContext = getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel, {}); CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::Declaration, semanticContext, {}); builder.setAssociatedDecl(op); if (HaveLeadingSpace) builder.addAnnotatedWhitespace(" "); else builder.addWhitespace(" "); builder.addBaseName(op->getName().str()); builder.addWhitespace(" "); if (RHSType) { Type contextTy; if (auto typeContext = CurrDeclContext->getInnermostTypeContext()) contextTy = typeContext->getDeclaredTypeInContext(); builder.addCallParameter(Identifier(), RHSType, contextTy); } if (resultType) addTypeAnnotation(builder, resultType); } void tryInfixOperatorCompletion(Expr *foldedExpr, InfixOperatorDecl *op) { ConcreteDeclRef referencedDecl; FunctionType *funcTy = getTypeOfCompletionOperator( const_cast<DeclContext *>(CurrDeclContext), foldedExpr, op->getName(), DeclRefKind::BinaryOperator, referencedDecl); if (!funcTy) return; Type lhsTy = funcTy->getParams()[0].getPlainType(); Type rhsTy = funcTy->getParams()[1].getPlainType(); Type resultTy = funcTy->getResult(); // Don't complete optional operators on non-optional types. if (!lhsTy->getRValueType()->getOptionalObjectType()) { // 'T ?? T' if (op->getName().str() == "??") return; // 'T == nil' if (auto NT = rhsTy->getNominalOrBoundGenericNominal()) if (NT->getName() == CurrDeclContext->getASTContext().Id_OptionalNilComparisonType) return; } // If the right-hand side and result type are both type parameters, we're // not providing a useful completion. if (resultTy->isTypeParameter() && rhsTy->isTypeParameter()) return; // TODO: Use referencedDecl (FuncDecl) instead of 'op' (OperatorDecl). addInfixOperatorCompletion(op, funcTy->getResult(), funcTy->getParams()[1].getPlainType()); } Expr *typeCheckLeadingSequence(Expr *LHS, ArrayRef<Expr *> leadingSequence) { if (leadingSequence.empty()) return LHS; SourceRange sequenceRange(leadingSequence.front()->getStartLoc(), LHS->getEndLoc()); auto *expr = findParsedExpr(CurrDeclContext, sequenceRange); if (!expr) return LHS; if (expr->getType() && !expr->getType()->hasError()) return expr; if (!typeCheckExpression(const_cast<DeclContext *>(CurrDeclContext), expr)) return expr; return LHS; } void getOperatorCompletions(Expr *LHS, ArrayRef<Expr *> leadingSequence) { if (IsSuperRefExpr) return; Expr *foldedExpr = typeCheckLeadingSequence(LHS, leadingSequence); SmallVector<OperatorDecl *, 16> operators; collectOperators(operators); // FIXME: this always chooses the first operator with the given name. llvm::DenseSet<Identifier> seenPostfixOperators; llvm::DenseSet<Identifier> seenInfixOperators; for (auto op : operators) { switch (op->getKind()) { case DeclKind::PrefixOperator: // Don't insert prefix operators in postfix position. // FIXME: where should these get completed? break; case DeclKind::PostfixOperator: if (seenPostfixOperators.insert(op->getName()).second) tryPostfixOperator(LHS, cast<PostfixOperatorDecl>(op)); break; case DeclKind::InfixOperator: if (seenInfixOperators.insert(op->getName()).second) tryInfixOperatorCompletion(foldedExpr, cast<InfixOperatorDecl>(op)); break; default: llvm_unreachable("unexpected operator kind"); } } if (leadingSequence.empty() && LHS->getType() && LHS->getType()->hasLValueType()) { addAssignmentOperator(LHS->getType()->getRValueType(), CurrDeclContext->getASTContext().TheEmptyTupleType); } // FIXME: unify this with the ?.member completions. if (auto T = LHS->getType()) if (auto ValueT = T->getRValueType()->getOptionalObjectType()) addPostfixBang(ValueT); } void addTypeRelationFromProtocol(CodeCompletionResultBuilder &builder, CodeCompletionLiteralKind kind) { // Check for matching ExpectedTypes. auto *P = Ctx.getProtocol(protocolForLiteralKind(kind)); for (auto T : expectedTypeContext.possibleTypes) { if (!T) continue; auto typeRelation = CodeCompletionResult::Identical; // Convert through optional types unless we're looking for a protocol // that Optional itself conforms to. if (kind != CodeCompletionLiteralKind::NilLiteral) { if (auto optionalObjT = T->getOptionalObjectType()) { T = optionalObjT; typeRelation = CodeCompletionResult::Convertible; } } // Check for conformance to the literal protocol. if (auto *NTD = T->getAnyNominal()) { SmallVector<ProtocolConformance *, 2> conformances; if (NTD->lookupConformance(CurrModule, P, conformances)) { addTypeAnnotation(builder, T); builder.setExpectedTypeRelation(typeRelation); return; } } } // Fallback to showing the default type. if (auto defaultTy = defaultTypeLiteralKind(kind, Ctx)) { builder.addTypeAnnotation(defaultTy, PrintOptions()); builder.setExpectedTypeRelation( expectedTypeContext.possibleTypes.empty() ? CodeCompletionResult::ExpectedTypeRelation::Unknown : CodeCompletionResult::ExpectedTypeRelation::Unrelated); } } /// Add '#file', '#line', et at. void addPoundLiteralCompletions(bool needPound) { auto addFromProto = [&](MagicIdentifierLiteralExpr::Kind magicKind, Optional<CodeCompletionLiteralKind> literalKind) { CodeCompletionKeywordKind kwKind; switch (magicKind) { case MagicIdentifierLiteralExpr::FileIDSpelledAsFile: kwKind = CodeCompletionKeywordKind::pound_file; break; case MagicIdentifierLiteralExpr::FilePathSpelledAsFile: // Already handled by above case. return; #define MAGIC_IDENTIFIER_TOKEN(NAME, TOKEN) \ case MagicIdentifierLiteralExpr::NAME: \ kwKind = CodeCompletionKeywordKind::TOKEN; \ break; #define MAGIC_IDENTIFIER_DEPRECATED_TOKEN(NAME, TOKEN) #include "swift/AST/MagicIdentifierKinds.def" } StringRef name = MagicIdentifierLiteralExpr::getKindString(magicKind); if (!needPound) name = name.substr(1); if (!literalKind) { // Pointer type addKeyword(name, "UnsafeRawPointer", kwKind); return; } CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); builder.setLiteralKind(literalKind.getValue()); builder.setKeywordKind(kwKind); builder.addBaseName(name); addTypeRelationFromProtocol(builder, literalKind.getValue()); }; #define MAGIC_STRING_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \ addFromProto(MagicIdentifierLiteralExpr::NAME, \ CodeCompletionLiteralKind::StringLiteral); #define MAGIC_INT_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \ addFromProto(MagicIdentifierLiteralExpr::NAME, \ CodeCompletionLiteralKind::IntegerLiteral); #define MAGIC_POINTER_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \ addFromProto(MagicIdentifierLiteralExpr::NAME, \ None); #include "swift/AST/MagicIdentifierKinds.def" } void addValueLiteralCompletions() { auto &context = CurrDeclContext->getASTContext(); auto addFromProto = [&]( CodeCompletionLiteralKind kind, llvm::function_ref<void(CodeCompletionResultBuilder &)> consumer, bool isKeyword = false) { CodeCompletionResultBuilder builder(Sink, CodeCompletionResult::Literal, SemanticContextKind::None, {}); builder.setLiteralKind(kind); consumer(builder); addTypeRelationFromProtocol(builder, kind); }; // FIXME: the pedantically correct way is to resolve Swift.*LiteralType. using LK = CodeCompletionLiteralKind; using Builder = CodeCompletionResultBuilder; // Add literal completions that conform to specific protocols. addFromProto(LK::IntegerLiteral, [](Builder &builder) { builder.addTextChunk("0"); }); addFromProto(LK::BooleanLiteral, [](Builder &builder) { builder.addBaseName("true"); }, /*isKeyword=*/true); addFromProto(LK::BooleanLiteral, [](Builder &builder) { builder.addBaseName("false"); }, /*isKeyword=*/true); addFromProto(LK::NilLiteral, [](Builder &builder) { builder.addBaseName("nil"); }, /*isKeyword=*/true); addFromProto(LK::StringLiteral, [&](Builder &builder) { builder.addTextChunk("\""); builder.addSimpleNamedParameter("abc"); builder.addTextChunk("\""); }); addFromProto(LK::ArrayLiteral, [&](Builder &builder) { builder.addLeftBracket(); builder.addSimpleNamedParameter("values"); builder.addRightBracket(); }); addFromProto(LK::DictionaryLiteral, [&](Builder &builder) { builder.addLeftBracket(); builder.addSimpleNamedParameter("key"); builder.addTextChunk(": "); builder.addSimpleNamedParameter("value"); builder.addRightBracket(); }); auto floatType = context.getFloatDecl()->getDeclaredInterfaceType(); addFromProto(LK::ColorLiteral, [&](Builder &builder) { builder.addBaseName("#colorLiteral"); builder.addLeftParen(); builder.addCallParameter(context.getIdentifier("red"), floatType); builder.addComma(); builder.addCallParameter(context.getIdentifier("green"), floatType); builder.addComma(); builder.addCallParameter(context.getIdentifier("blue"), floatType); builder.addComma(); builder.addCallParameter(context.getIdentifier("alpha"), floatType); builder.addRightParen(); }); auto stringType = context.getStringDecl()->getDeclaredInterfaceType(); addFromProto(LK::ImageLiteral, [&](Builder &builder) { builder.addBaseName("#imageLiteral"); builder.addLeftParen(); builder.addCallParameter(context.getIdentifier("resourceName"), stringType); builder.addRightParen(); }); // Add tuple completion (item, item). { CodeCompletionResultBuilder builder(Sink, CodeCompletionResult::Literal, SemanticContextKind::None, {}); builder.setLiteralKind(LK::Tuple); builder.addLeftParen(); builder.addSimpleNamedParameter("values"); builder.addRightParen(); for (auto T : expectedTypeContext.possibleTypes) { if (T && T->is<TupleType>() && !T->isVoid()) { addTypeAnnotation(builder, T); builder.setExpectedTypeRelation(CodeCompletionResult::Identical); break; } } } } void addObjCPoundKeywordCompletions(bool needPound) { if (!Ctx.LangOpts.EnableObjCInterop) return; // If the expected type is ObjectiveC.Selector, add #selector. If // it's String, add #keyPath. bool addedSelector = false; bool addedKeyPath = false; for (auto T : expectedTypeContext.possibleTypes) { T = T->lookThroughAllOptionalTypes(); if (auto structDecl = T->getStructOrBoundGenericStruct()) { if (!addedSelector && structDecl->getName() == Ctx.Id_Selector && structDecl->getParentModule()->getName() == Ctx.Id_ObjectiveC) { addPoundSelector(needPound); if (addedKeyPath) break; addedSelector = true; continue; } } if (!addedKeyPath && T->getAnyNominal() == Ctx.getStringDecl()) { addPoundKeyPath(needPound); if (addedSelector) break; addedKeyPath = true; continue; } } } struct FilteredDeclConsumer : public swift::VisibleDeclConsumer { swift::VisibleDeclConsumer &Consumer; DeclFilter Filter; FilteredDeclConsumer(swift::VisibleDeclConsumer &Consumer, DeclFilter Filter) : Consumer(Consumer), Filter(Filter) {} void foundDecl(ValueDecl *VD, DeclVisibilityKind Kind, DynamicLookupInfo dynamicLookupInfo) override { if (Filter(VD, Kind)) Consumer.foundDecl(VD, Kind, dynamicLookupInfo); } }; void getValueCompletionsInDeclContext(SourceLoc Loc, DeclFilter Filter = DefaultFilter, bool LiteralCompletions = true, bool ModuleQualifier = true) { ExprType = Type(); Kind = LookupKind::ValueInDeclContext; NeedLeadingDot = false; AccessFilteringDeclConsumer AccessFilteringConsumer( CurrDeclContext, *this); FilteredDeclConsumer FilteringConsumer(AccessFilteringConsumer, Filter); lookupVisibleDecls(FilteringConsumer, CurrDeclContext, /*IncludeTopLevel=*/false, Loc); RequestedCachedResults.push_back(RequestedResultsTy::toplevelResults() .withModuleQualifier(ModuleQualifier)); // Manually add any expected nominal types from imported modules so that // they get their expected type relation. Don't include protocols, since // they can't be initialized from the type name. // FIXME: this does not include types that conform to an expected protocol. // FIXME: this creates duplicate results. for (auto T : expectedTypeContext.possibleTypes) { if (auto NT = T->getAs<NominalType>()) { if (auto NTD = NT->getDecl()) { if (!isa<ProtocolDecl>(NTD) && NTD->getModuleContext() != CurrModule) { addNominalTypeRef(NT->getDecl(), DeclVisibilityKind::VisibleAtTopLevel, {}); } } } } if (CompletionContext) { // FIXME: this is an awful simplification that says all and only enums can // use implicit member syntax (leading dot). Computing the accurate answer // using lookup (e.g. getUnresolvedMemberCompletions) is too expensive, // and for some clients this approximation is good enough. CompletionContext->MayUseImplicitMemberExpr = std::any_of(expectedTypeContext.possibleTypes.begin(), expectedTypeContext.possibleTypes.end(), [](Type T) { if (auto *NTD = T->getAnyNominal()) return isa<EnumDecl>(NTD); return false; }); } if (LiteralCompletions) { addValueLiteralCompletions(); addPoundLiteralCompletions(/*needPound=*/true); } addObjCPoundKeywordCompletions(/*needPound=*/true); } void getUnresolvedMemberCompletions(Type T) { if (!T->mayHaveMembers()) return; if (auto objT = T->getOptionalObjectType()) { // Add 'nil' keyword with erasing '.' instruction. unsigned bytesToErase = 0; auto &SM = CurrDeclContext->getASTContext().SourceMgr; if (DotLoc.isValid()) bytesToErase = SM.getByteDistance(DotLoc, SM.getCodeCompletionLoc()); addKeyword("nil", T, SemanticContextKind::None, CodeCompletionKeywordKind::kw_nil, bytesToErase); } // We can only say .foo where foo is a static member of the contextual // type and has the same type (or if the member is a function, then the // same result type) as the contextual type. FilteredDeclConsumer consumer(*this, [=](ValueDecl *VD, DeclVisibilityKind Reason) { if (T->getOptionalObjectType() && VD->getModuleContext()->isStdlibModule()) { // In optional context, ignore '.init(<some>)', 'init(nilLiteral:)', if (isa<ConstructorDecl>(VD)) return false; } return true; }); auto baseType = MetatypeType::get(T); llvm::SaveAndRestore<LookupKind> SaveLook(Kind, LookupKind::ValueExpr); llvm::SaveAndRestore<Type> SaveType(ExprType, baseType); llvm::SaveAndRestore<bool> SaveUnresolved(IsUnresolvedMember, true); lookupVisibleMemberDecls(consumer, baseType, CurrDeclContext, /*includeInstanceMembers=*/false, /*includeDerivedRequirements*/false, /*includeProtocolExtensionMembers*/true); } void getUnresolvedMemberCompletions(ArrayRef<Type> Types) { NeedLeadingDot = !HaveDot; SmallPtrSet<CanType, 4> seenTypes; for (auto T : Types) { if (!T || !seenTypes.insert(T->getCanonicalType()).second) continue; if (auto objT = T->getOptionalObjectType()) { // If this is optional type, perform completion for the object type. // i.e. 'let _: Enum??? = .enumMember' is legal. objT = objT->lookThroughAllOptionalTypes(); if (seenTypes.insert(objT->getCanonicalType()).second) getUnresolvedMemberCompletions(objT); } getUnresolvedMemberCompletions(T); } } void addCallArgumentCompletionResults( ArrayRef<PossibleParamInfo> ParamInfos, bool isLabeledTrailingClosure = false) { Type ContextType; if (auto typeContext = CurrDeclContext->getInnermostTypeContext()) ContextType = typeContext->getDeclaredTypeInContext(); for (auto Info : ParamInfos) { const auto *Arg = Info.Param; if (!Arg) continue; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Pattern, SemanticContextKind::ExpressionSpecific, {}); Builder.addCallParameter(Arg->getLabel(), Identifier(), Arg->getPlainType(), ContextType, Arg->isVariadic(), Arg->isInOut(), /*isIUO=*/false, Arg->isAutoClosure(), /*useUnderscoreLabel=*/true, isLabeledTrailingClosure); auto Ty = Arg->getPlainType(); if (Arg->isInOut()) { Ty = InOutType::get(Ty); } else if (Arg->isAutoClosure()) { // 'Ty' may be ErrorType. if (auto funcTy = Ty->getAs<FunctionType>()) Ty = funcTy->getResult(); } addTypeAnnotation(Builder, Ty); Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::NotApplicable); } } void getTypeCompletions(Type BaseType) { if (tryModuleCompletions(BaseType, /*OnlyTypes=*/true)) return; Kind = LookupKind::Type; this->BaseType = BaseType; NeedLeadingDot = !HaveDot; lookupVisibleMemberDecls(*this, MetatypeType::get(BaseType), CurrDeclContext, IncludeInstanceMembers, /*includeDerivedRequirements*/false, /*includeProtocolExtensionMembers*/false); if (BaseType->isAnyExistentialType()) { addKeyword("Protocol", MetatypeType::get(BaseType)); addKeyword("Type", ExistentialMetatypeType::get(BaseType)); } else if (!BaseType->is<ModuleType>()) { addKeyword("Type", MetatypeType::get(BaseType)); } } void getGenericRequirementCompletions(DeclContext *DC, SourceLoc CodeCompletionLoc) { auto genericSig = DC->getGenericSignatureOfContext(); if (!genericSig) return; for (auto GPT : genericSig->getGenericParams()) { addGenericTypeParamRef(GPT->getDecl(), DeclVisibilityKind::GenericParameter, {}); } // For non-protocol nominal type decls, only suggest generic parameters. if (auto D = DC->getAsDecl()) if (isa<NominalTypeDecl>(D) && !isa<ProtocolDecl>(D)) return; auto typeContext = DC->getInnermostTypeContext(); if (!typeContext) return; auto selfTy = typeContext->getSelfTypeInContext(); Kind = LookupKind::GenericRequirement; this->BaseType = selfTy; NeedLeadingDot = false; lookupVisibleMemberDecls(*this, MetatypeType::get(selfTy), CurrDeclContext, IncludeInstanceMembers, /*includeDerivedRequirements*/false, /*includeProtocolExtensionMembers*/true); // We not only allow referencing nested types/typealiases directly, but also // qualified by the current type. Thus also suggest current self type so the // user can do a memberwise lookup on it. if (auto SelfType = typeContext->getSelfNominalTypeDecl()) { addNominalTypeRef(SelfType, DeclVisibilityKind::LocalVariable, DynamicLookupInfo()); } // Self is also valid in all cases in which it can be used in function // bodies. Suggest it if applicable. getSelfTypeCompletionInDeclContext(CodeCompletionLoc, /*isForResultType=*/false); } static bool canUseAttributeOnDecl(DeclAttrKind DAK, bool IsInSil, bool IsConcurrencyEnabled, Optional<DeclKind> DK) { if (DeclAttribute::isUserInaccessible(DAK)) return false; if (DeclAttribute::isDeclModifier(DAK)) return false; if (DeclAttribute::shouldBeRejectedByParser(DAK)) return false; if (!IsInSil && DeclAttribute::isSilOnly(DAK)) return false; if (!IsConcurrencyEnabled && DeclAttribute::isConcurrencyOnly(DAK)) return false; if (!DK.hasValue()) return true; return DeclAttribute::canAttributeAppearOnDeclKind(DAK, DK.getValue()); } void getAttributeDeclCompletions(bool IsInSil, Optional<DeclKind> DK) { // FIXME: also include user-defined attribute keywords StringRef TargetName = "Declaration"; if (DK.hasValue()) { switch (DK.getValue()) { #define DECL(Id, ...) \ case DeclKind::Id: \ TargetName = #Id; \ break; #include "swift/AST/DeclNodes.def" } } bool IsConcurrencyEnabled = Ctx.LangOpts.EnableExperimentalConcurrency; std::string Description = TargetName.str() + " Attribute"; #define DECL_ATTR(KEYWORD, NAME, ...) \ if (canUseAttributeOnDecl(DAK_##NAME, IsInSil, IsConcurrencyEnabled, DK)) \ addDeclAttrKeyword(#KEYWORD, Description); #include "swift/AST/Attr.def" } void getAttributeDeclParamCompletions(DeclAttrKind AttrKind, int ParamIndex) { if (AttrKind == DAK_Available) { if (ParamIndex == 0) { addDeclAttrParamKeyword("*", "Platform", false); #define AVAILABILITY_PLATFORM(X, PrettyName) \ addDeclAttrParamKeyword(swift::platformString(PlatformKind::X), \ "Platform", false); #include "swift/AST/PlatformKinds.def" } else { addDeclAttrParamKeyword("unavailable", "", false); addDeclAttrParamKeyword("message", "Specify message", true); addDeclAttrParamKeyword("renamed", "Specify replacing name", true); addDeclAttrParamKeyword("introduced", "Specify version number", true); addDeclAttrParamKeyword("deprecated", "Specify version number", true); } } } void collectPrecedenceGroups() { assert(CurrDeclContext); if (CurrModule) { for (auto FU: CurrModule->getFiles()) { // We are looking through the current module, // inspect only source files. if (FU->getKind() != FileUnitKind::Source) continue; llvm::SmallVector<PrecedenceGroupDecl*, 4> results; cast<SourceFile>(FU)->getPrecedenceGroups(results); for (auto PG: results) addPrecedenceGroupRef(PG); } } for (auto Import : namelookup::getAllImports(CurrDeclContext)) { auto Module = Import.importedModule; if (Module == CurrModule) continue; RequestedCachedResults.push_back(RequestedResultsTy::fromModule(Module) .onlyPrecedenceGroups() .withModuleQualifier(false)); } } void getPrecedenceGroupCompletions(SyntaxKind SK) { switch (SK) { case SyntaxKind::PrecedenceGroupAssociativity: addKeyword(getAssociativitySpelling(Associativity::None)); addKeyword(getAssociativitySpelling(Associativity::Left)); addKeyword(getAssociativitySpelling(Associativity::Right)); break; case SyntaxKind::PrecedenceGroupAssignment: addKeyword(getTokenText(tok::kw_false), Type(), SemanticContextKind::None, CodeCompletionKeywordKind::kw_false); addKeyword(getTokenText(tok::kw_true), Type(), SemanticContextKind::None, CodeCompletionKeywordKind::kw_true); break; case SyntaxKind::PrecedenceGroupAttributeList: addKeyword("associativity"); addKeyword("higherThan"); addKeyword("lowerThan"); addKeyword("assignment"); break; case SyntaxKind::PrecedenceGroupRelation: collectPrecedenceGroups(); break; default: llvm_unreachable("not a precedencegroup SyntaxKind"); } } void getPoundAvailablePlatformCompletions() { // The platform names should be identical to those in @available. getAttributeDeclParamCompletions(DAK_Available, 0); } /// \p Loc is the location of the code completin token. /// \p isForDeclResult determines if were are spelling out the result type /// of a declaration. void getSelfTypeCompletionInDeclContext(SourceLoc Loc, bool isForDeclResult) { const DeclContext *typeDC = CurrDeclContext->getInnermostTypeContext(); if (!typeDC) return; // For protocols, there's a 'Self' generic parameter. if (typeDC->getSelfProtocolDecl()) return; Type selfType = CurrDeclContext->mapTypeIntoContext(typeDC->getSelfInterfaceType()); if (typeDC->getSelfClassDecl()) { // In classes, 'Self' can be used in result type of func, subscript and // computed property, or inside function bodies. bool canUseDynamicSelf = false; if (isForDeclResult) { canUseDynamicSelf = true; } else { const auto *checkDC = CurrDeclContext; if (isa<TypeAliasDecl>(checkDC)) checkDC = checkDC->getParent(); if (const auto *AFD = checkDC->getInnermostMethodContext()) { canUseDynamicSelf = Ctx.SourceMgr.rangeContainsTokenLoc( AFD->getBodySourceRange(), Loc); } } if (!canUseDynamicSelf) return; // 'Self' in class is a dynamic type. selfType = DynamicSelfType::get(selfType, Ctx); } else { // In enums and structs, 'Self' is just an alias for the nominal type, // and can be used anywhere. } CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::CurrentNominal, expectedTypeContext); Builder.addKeyword("Self"); Builder.setKeywordKind(CodeCompletionKeywordKind::kw_Self); addTypeAnnotation(Builder, selfType); } void getTypeCompletionsInDeclContext(SourceLoc Loc, bool ModuleQualifier = true) { Kind = LookupKind::TypeInDeclContext; AccessFilteringDeclConsumer AccessFilteringConsumer( CurrDeclContext, *this); lookupVisibleDecls(AccessFilteringConsumer, CurrDeclContext, /*IncludeTopLevel=*/false, Loc); RequestedCachedResults.push_back( RequestedResultsTy::toplevelResults() .onlyTypes() .withModuleQualifier(ModuleQualifier)); } void getToplevelCompletions(bool OnlyTypes) { Kind = OnlyTypes ? LookupKind::TypeInDeclContext : LookupKind::ValueInDeclContext; NeedLeadingDot = false; UsableFilteringDeclConsumer UsableFilteringConsumer( Ctx.SourceMgr, CurrDeclContext, Ctx.SourceMgr.getCodeCompletionLoc(), *this); AccessFilteringDeclConsumer AccessFilteringConsumer( CurrDeclContext, UsableFilteringConsumer); CurrModule->lookupVisibleDecls({}, AccessFilteringConsumer, NLKind::UnqualifiedLookup); } void lookupExternalModuleDecls(const ModuleDecl *TheModule, ArrayRef<std::string> AccessPath, bool ResultsHaveLeadingDot) { assert(CurrModule != TheModule && "requested module should be external"); Kind = LookupKind::ImportFromModule; NeedLeadingDot = ResultsHaveLeadingDot; ImportPath::Access::Builder builder; for (auto Piece : AccessPath) { builder.push_back(Ctx.getIdentifier(Piece)); } AccessFilteringDeclConsumer FilteringConsumer(CurrDeclContext, *this); TheModule->lookupVisibleDecls(builder.get(), FilteringConsumer, NLKind::UnqualifiedLookup); llvm::SmallVector<PrecedenceGroupDecl*, 16> precedenceGroups; TheModule->getPrecedenceGroups(precedenceGroups); for (auto PGD: precedenceGroups) addPrecedenceGroupRef(PGD); } void getStmtLabelCompletions(SourceLoc Loc, bool isContinue) { class LabelFinder : public ASTWalker { SourceManager &SM; SourceLoc TargetLoc; bool IsContinue; public: SmallVector<Identifier, 2> Result; LabelFinder(SourceManager &SM, SourceLoc TargetLoc, bool IsContinue) : SM(SM), TargetLoc(TargetLoc), IsContinue(IsContinue) {} std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override { if (SM.isBeforeInBuffer(S->getEndLoc(), TargetLoc)) return {false, S}; if (LabeledStmt *LS = dyn_cast<LabeledStmt>(S)) { if (LS->getLabelInfo()) { if (!IsContinue || LS->isPossibleContinueTarget()) { auto label = LS->getLabelInfo().Name; if (!llvm::is_contained(Result, label)) Result.push_back(label); } } } return {true, S}; } Stmt *walkToStmtPost(Stmt *S) override { return nullptr; } std::pair<bool, Expr *> walkToExprPre(Expr *E) override { if (SM.isBeforeInBuffer(E->getEndLoc(), TargetLoc)) return {false, E}; return {true, E}; } } Finder(CurrDeclContext->getASTContext().SourceMgr, Loc, isContinue); const_cast<DeclContext *>(CurrDeclContext)->walkContext(Finder); for (auto name : Finder.Result) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Pattern, SemanticContextKind::Local, {}); Builder.addTextChunk(name.str()); } } }; class CompletionOverrideLookup : public swift::VisibleDeclConsumer { CodeCompletionResultSink &Sink; ASTContext &Ctx; const DeclContext *CurrDeclContext; SmallVectorImpl<StringRef> &ParsedKeywords; SourceLoc introducerLoc; bool hasFuncIntroducer = false; bool hasVarIntroducer = false; bool hasTypealiasIntroducer = false; bool hasInitializerModifier = false; bool hasAccessModifier = false; bool hasOverride = false; bool hasOverridabilityModifier = false; bool hasStaticOrClass = false; public: CompletionOverrideLookup(CodeCompletionResultSink &Sink, ASTContext &Ctx, const DeclContext *CurrDeclContext, SmallVectorImpl<StringRef> &ParsedKeywords, SourceLoc introducerLoc) : Sink(Sink), Ctx(Ctx), CurrDeclContext(CurrDeclContext), ParsedKeywords(ParsedKeywords), introducerLoc(introducerLoc) { hasFuncIntroducer = isKeywordSpecified("func"); hasVarIntroducer = isKeywordSpecified("var") || isKeywordSpecified("let"); hasTypealiasIntroducer = isKeywordSpecified("typealias"); hasInitializerModifier = isKeywordSpecified("required") || isKeywordSpecified("convenience"); hasAccessModifier = isKeywordSpecified("private") || isKeywordSpecified("fileprivate") || isKeywordSpecified("internal") || isKeywordSpecified("public") || isKeywordSpecified("open"); hasOverride = isKeywordSpecified("override"); hasOverridabilityModifier = isKeywordSpecified("final") || isKeywordSpecified("open"); hasStaticOrClass = isKeywordSpecified(getTokenText(tok::kw_class)) || isKeywordSpecified(getTokenText(tok::kw_static)); } bool isKeywordSpecified(StringRef Word) { return std::find(ParsedKeywords.begin(), ParsedKeywords.end(), Word) != ParsedKeywords.end(); } bool missingOverride(DeclVisibilityKind Reason) { return !hasOverride && Reason == DeclVisibilityKind::MemberOfSuper && !CurrDeclContext->getSelfProtocolDecl(); } void addAccessControl(const ValueDecl *VD, CodeCompletionResultBuilder &Builder) { auto CurrentNominal = CurrDeclContext->getSelfNominalTypeDecl(); assert(CurrentNominal); auto AccessOfContext = CurrentNominal->getFormalAccess(); if (AccessOfContext < AccessLevel::Public) return; auto Access = VD->getFormalAccess(); // Use the greater access between the protocol requirement and the witness. // In case of: // // public protocol P { func foo() } // public class B { func foo() {} } // public class C: B, P { // <complete> // } // // 'VD' is 'B.foo()' which is implicitly 'internal'. But as the overriding // declaration, the user needs to write both 'public' and 'override': // // public class C: B { // public override func foo() {} // } if (Access < AccessLevel::Public && !isa<ProtocolDecl>(VD->getDeclContext())) { for (auto Conformance : CurrentNominal->getAllConformances()) { Conformance->getRootConformance()->forEachValueWitness( [&](ValueDecl *req, Witness witness) { if (witness.getDecl() == VD) Access = std::max( Access, Conformance->getProtocol()->getFormalAccess()); }); } } Access = std::min(Access, AccessOfContext); // Only emit 'public', not needed otherwise. if (Access >= AccessLevel::Public) Builder.addAccessControlKeyword(Access); } /// Return type if the result type if \p VD should be represented as opaque /// result type. Type getOpaqueResultType(const ValueDecl *VD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { if (Reason != DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal) return nullptr; auto currTy = CurrDeclContext->getDeclaredTypeInContext(); if (!currTy) return nullptr; Type ResultT; if (auto *FD = dyn_cast<FuncDecl>(VD)) { if (FD->getGenericParams()) { // Generic function cannot have opaque result type. return nullptr; } ResultT = FD->getResultInterfaceType(); } else if (auto *SD = dyn_cast<SubscriptDecl>(VD)) { if (SD->getGenericParams()) { // Generic subscript cannot have opaque result type. return nullptr; } ResultT = SD->getElementInterfaceType(); } else if (auto *VarD = dyn_cast<VarDecl>(VD)) { ResultT = VarD->getInterfaceType(); } else { return nullptr; } if (!ResultT->is<DependentMemberType>() || !ResultT->castTo<DependentMemberType>()->getAssocType()) // The result is not a valid associatedtype. return nullptr; // Try substitution to see if the associated type is resolved to concrete // type. auto substMap = currTy->getMemberSubstitutionMap( CurrDeclContext->getParentModule(), VD); if (!ResultT.subst(substMap)->is<DependentMemberType>()) // If resolved print it. return nullptr; auto genericSig = VD->getDeclContext()->getGenericSignatureOfContext(); if (genericSig->isConcreteType(ResultT)) // If it has same type requrement, we will emit the concrete type. return nullptr; // Collect requirements on the associatedtype. SmallVector<Type, 2> opaqueTypes; bool hasExplicitAnyObject = false; if (auto superTy = genericSig->getSuperclassBound(ResultT)) opaqueTypes.push_back(superTy); for (const auto proto : genericSig->getRequiredProtocols(ResultT)) opaqueTypes.push_back(proto->getDeclaredInterfaceType()); if (auto layout = genericSig->getLayoutConstraint(ResultT)) hasExplicitAnyObject = layout->isClass(); if (!hasExplicitAnyObject) { if (opaqueTypes.empty()) return nullptr; if (opaqueTypes.size() == 1) return opaqueTypes.front(); } return ProtocolCompositionType::get( VD->getASTContext(), opaqueTypes, hasExplicitAnyObject); } void addValueOverride(const ValueDecl *VD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo, CodeCompletionResultBuilder &Builder, bool hasDeclIntroducer) { class DeclPrinter : public StreamPrinter { Type OpaqueBaseTy; public: using StreamPrinter::StreamPrinter; Optional<unsigned> NameOffset; DeclPrinter(raw_ostream &OS, Type OpaqueBaseTy) : StreamPrinter(OS), OpaqueBaseTy(OpaqueBaseTy) {} void printDeclLoc(const Decl *D) override { if (!NameOffset.hasValue()) NameOffset = OS.tell(); } // As for FuncDecl, SubscriptDecl, and VarDecl, void printDeclResultTypePre(ValueDecl *VD, TypeLoc &TL) override { if (!OpaqueBaseTy.isNull()) { OS << "some "; TL = TypeLoc::withoutLoc(OpaqueBaseTy); } } }; llvm::SmallString<256> DeclStr; unsigned NameOffset = 0; { llvm::raw_svector_ostream OS(DeclStr); DeclPrinter Printer( OS, getOpaqueResultType(VD, Reason, dynamicLookupInfo)); PrintOptions Options; if (auto transformType = CurrDeclContext->getDeclaredTypeInContext()) Options.setBaseType(transformType); Options.SkipUnderscoredKeywords = true; Options.PrintImplicitAttrs = false; Options.ExclusiveAttrList.push_back(TAK_escaping); Options.ExclusiveAttrList.push_back(TAK_autoclosure); Options.PrintOverrideKeyword = false; Options.PrintPropertyAccessors = false; Options.PrintSubscriptAccessors = false; Options.PrintStaticKeyword = !hasStaticOrClass; VD->print(Printer, Options); NameOffset = Printer.NameOffset.getValue(); } if (!hasDeclIntroducer && !hasAccessModifier) addAccessControl(VD, Builder); if (missingOverride(Reason)) { if (!hasDeclIntroducer) Builder.addOverrideKeyword(); else { auto dist = Ctx.SourceMgr.getByteDistance( introducerLoc, Ctx.SourceMgr.getCodeCompletionLoc()); if (dist <= CodeCompletionResult::MaxNumBytesToErase) { Builder.setNumBytesToErase(dist); Builder.addOverrideKeyword(); Builder.addDeclIntroducer(DeclStr.str().substr(0, NameOffset)); } } } if (!hasDeclIntroducer && NameOffset != 0) Builder.addDeclIntroducer(DeclStr.str().substr(0, NameOffset)); Builder.addTextChunk(DeclStr.str().substr(NameOffset)); } void addMethodOverride(const FuncDecl *FD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::NotApplicable); Builder.setAssociatedDecl(FD); addValueOverride(FD, Reason, dynamicLookupInfo, Builder, hasFuncIntroducer); Builder.addBraceStmtWithCursor(); } void addVarOverride(const VarDecl *VD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { // Overrides cannot use 'let', but if the 'override' keyword is specified // then the intention is clear, so provide the results anyway. The compiler // can then provide an error telling you to use 'var' instead. // If we don't need override then it's a protocol requirement, so show it. if (missingOverride(Reason) && hasVarIntroducer && isKeywordSpecified("let")) return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setAssociatedDecl(VD); addValueOverride(VD, Reason, dynamicLookupInfo, Builder, hasVarIntroducer); } void addSubscriptOverride(const SubscriptDecl *SD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::NotApplicable); Builder.setAssociatedDecl(SD); addValueOverride(SD, Reason, dynamicLookupInfo, Builder, false); Builder.addBraceStmtWithCursor(); } void addTypeAlias(const AssociatedTypeDecl *ATD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::NotApplicable); Builder.setAssociatedDecl(ATD); if (!hasTypealiasIntroducer && !hasAccessModifier) addAccessControl(ATD, Builder); if (!hasTypealiasIntroducer) Builder.addDeclIntroducer("typealias "); Builder.addTextChunk(ATD->getName().str()); Builder.addTextChunk(" = "); Builder.addSimpleNamedParameter("Type"); } void addConstructor(const ConstructorDecl *CD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::NotApplicable); Builder.setAssociatedDecl(CD); if (!hasAccessModifier) addAccessControl(CD, Builder); if (missingOverride(Reason) && CD->isDesignatedInit() && !CD->isRequired()) Builder.addOverrideKeyword(); // Emit 'required' if we're in class context, 'required' is not specified, // and 1) this is a protocol conformance and the class is not final, or 2) // this is subclass and the initializer is marked as required. bool needRequired = false; auto C = CurrDeclContext->getSelfClassDecl(); if (C && !isKeywordSpecified("required")) { switch (Reason) { case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal: case DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal: if (!C->isFinal()) needRequired = true; break; case DeclVisibilityKind::MemberOfSuper: if (CD->isRequired()) needRequired = true; break; default: break; } } llvm::SmallString<256> DeclStr; if (needRequired) DeclStr += "required "; { llvm::raw_svector_ostream OS(DeclStr); PrintOptions Options; if (auto transformType = CurrDeclContext->getDeclaredTypeInContext()) Options.setBaseType(transformType); Options.PrintImplicitAttrs = false; Options.SkipAttributes = true; CD->print(OS, Options); } Builder.addTextChunk(DeclStr); Builder.addBraceStmtWithCursor(); } // Implement swift::VisibleDeclConsumer. void foundDecl(ValueDecl *D, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo) override { if (Reason == DeclVisibilityKind::MemberOfCurrentNominal) return; if (D->shouldHideFromEditor()) return; if (D->isFinal()) return; bool hasIntroducer = hasFuncIntroducer || hasVarIntroducer || hasTypealiasIntroducer; if (hasStaticOrClass && !D->isStatic()) return; // As per the current convention, only instance members are // suggested if an introducer is not accompanied by a 'static' or // 'class' modifier. if (hasIntroducer && !hasStaticOrClass && D->isStatic()) return; if (auto *FD = dyn_cast<FuncDecl>(D)) { // We cannot override operators as members. if (FD->isBinaryOperator() || FD->isUnaryOperator()) return; // We cannot override individual accessors. if (isa<AccessorDecl>(FD)) return; if (hasFuncIntroducer || (!hasIntroducer && !hasInitializerModifier)) addMethodOverride(FD, Reason, dynamicLookupInfo); return; } if (auto *VD = dyn_cast<VarDecl>(D)) { if (hasVarIntroducer || (!hasIntroducer && !hasInitializerModifier)) addVarOverride(VD, Reason, dynamicLookupInfo); return; } if (auto *SD = dyn_cast<SubscriptDecl>(D)) { if (!hasIntroducer && !hasInitializerModifier) addSubscriptOverride(SD, Reason, dynamicLookupInfo); } if (auto *CD = dyn_cast<ConstructorDecl>(D)) { if (!isa<ProtocolDecl>(CD->getDeclContext())) return; if (hasIntroducer || hasOverride || hasOverridabilityModifier || hasStaticOrClass) return; if (CD->isRequired() || CD->isDesignatedInit()) addConstructor(CD, Reason, dynamicLookupInfo); return; } } void addDesignatedInitializers(NominalTypeDecl *NTD) { if (hasFuncIntroducer || hasVarIntroducer || hasTypealiasIntroducer || hasOverridabilityModifier || hasStaticOrClass) return; const auto *CD = dyn_cast<ClassDecl>(NTD); if (!CD) return; if (!CD->hasSuperclass()) return; CD = CD->getSuperclassDecl(); for (const auto *Member : CD->getMembers()) { const auto *Constructor = dyn_cast<ConstructorDecl>(Member); if (!Constructor) continue; if (Constructor->hasStubImplementation()) continue; if (Constructor->isDesignatedInit()) addConstructor(Constructor, DeclVisibilityKind::MemberOfSuper, {}); } } void addAssociatedTypes(NominalTypeDecl *NTD) { if (!hasTypealiasIntroducer && (hasFuncIntroducer || hasVarIntroducer || hasInitializerModifier || hasOverride || hasOverridabilityModifier || hasStaticOrClass)) return; for (auto Conformance : NTD->getAllConformances()) { auto Proto = Conformance->getProtocol(); if (!Proto->isAccessibleFrom(CurrDeclContext)) continue; for (auto *ATD : Proto->getAssociatedTypeMembers()) { // FIXME: Also exclude the type alias that has already been specified. if (!Conformance->hasTypeWitness(ATD) || ATD->hasDefaultDefinitionType()) continue; addTypeAlias( ATD, DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal, {}); } } } static StringRef getResultBuilderDocComment( ResultBuilderBuildFunction function) { switch (function) { case ResultBuilderBuildFunction::BuildArray: return "Enables support for..in loops in a result builder by " "combining the results of all iterations into a single result"; case ResultBuilderBuildFunction::BuildBlock: return "Required by every result builder to build combined results " "from statement blocks"; case ResultBuilderBuildFunction::BuildEitherFirst: return "With buildEither(second:), enables support for 'if-else' and " "'switch' statements by folding conditional results into a single " "result"; case ResultBuilderBuildFunction::BuildEitherSecond: return "With buildEither(first:), enables support for 'if-else' and " "'switch' statements by folding conditional results into a single " "result"; case ResultBuilderBuildFunction::BuildExpression: return "If declared, provides contextual type information for statement " "expressions to translate them into partial results"; case ResultBuilderBuildFunction::BuildFinalResult: return "If declared, this will be called on the partial result from the " "outermost block statement to produce the final returned result"; case ResultBuilderBuildFunction::BuildLimitedAvailability: return "If declared, this will be called on the partial result of " "an 'if #available' block to allow the result builder to erase " "type information"; case ResultBuilderBuildFunction::BuildOptional: return "Enables support for `if` statements that do not have an `else`"; } } void addResultBuilderBuildCompletion( NominalTypeDecl *builder, Type componentType, ResultBuilderBuildFunction function) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Pattern, SemanticContextKind::CurrentNominal, {}); Builder.setExpectedTypeRelation( CodeCompletionResult::ExpectedTypeRelation::NotApplicable); if (!hasFuncIntroducer) { if (!hasAccessModifier && builder->getFormalAccess() >= AccessLevel::Public) Builder.addAccessControlKeyword(AccessLevel::Public); if (!hasStaticOrClass) Builder.addTextChunk("static "); Builder.addTextChunk("func "); } std::string declStringWithoutFunc; { llvm::raw_string_ostream out(declStringWithoutFunc); printResultBuilderBuildFunction( builder, componentType, function, None, out); } Builder.addTextChunk(declStringWithoutFunc); Builder.addBraceStmtWithCursor(); Builder.setBriefDocComment(getResultBuilderDocComment(function)); } /// Add completions for the various "build" functions in a result builder. void addResultBuilderBuildCompletions(NominalTypeDecl *builder) { Type componentType = inferResultBuilderComponentType(builder); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildBlock); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildExpression); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildOptional); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildEitherFirst); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildEitherSecond); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildArray); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildLimitedAvailability); addResultBuilderBuildCompletion( builder, componentType, ResultBuilderBuildFunction::BuildFinalResult); } void getOverrideCompletions(SourceLoc Loc) { if (!CurrDeclContext->isTypeContext()) return; if (isa<ProtocolDecl>(CurrDeclContext)) return; Type CurrTy = CurrDeclContext->getSelfTypeInContext(); auto *NTD = CurrDeclContext->getSelfNominalTypeDecl(); if (CurrTy && !CurrTy->is<ErrorType>()) { // Look for overridable static members too. Type Meta = MetatypeType::get(CurrTy); lookupVisibleMemberDecls(*this, Meta, CurrDeclContext, /*includeInstanceMembers=*/true, /*includeDerivedRequirements*/true, /*includeProtocolExtensionMembers*/false); addDesignatedInitializers(NTD); addAssociatedTypes(NTD); } if (NTD && NTD->getAttrs().hasAttribute<ResultBuilderAttr>()) { addResultBuilderBuildCompletions(NTD); } } }; } // end anonymous namespace static void addSelectorModifierKeywords(CodeCompletionResultSink &sink) { auto addKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { CodeCompletionResultBuilder Builder( sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(Kind); Builder.addTextChunk(Name); Builder.addCallParameterColon(); Builder.addSimpleTypedParameter("@objc property", /*IsVarArg=*/false); }; addKeyword("getter", CodeCompletionKeywordKind::None); addKeyword("setter", CodeCompletionKeywordKind::None); } void CodeCompletionCallbacksImpl::completeDotExpr(CodeCompletionExpr *E, SourceLoc DotLoc) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::DotExpr; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = E->getBase(); this->DotLoc = DotLoc; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeStmtOrExpr(CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); Kind = CompletionKind::StmtOrExpr; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completePostfixExprBeginning(CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::PostfixExprBeginning; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; if (CompleteExprSelectorContext == ObjCSelectorContext::MethodSelector) { addSelectorModifierKeywords(CompletionContext.getResultSink()); } } CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeForEachSequenceBeginning( CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); Kind = CompletionKind::ForEachSequence; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completePostfixExpr(Expr *E, bool hasSpace) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; HasSpace = hasSpace; Kind = CompletionKind::PostfixExpr; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = E; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completePostfixExprParen(Expr *E, Expr *CodeCompletionE) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::PostfixExprParen; ParsedExpr = E; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = static_cast<CodeCompletionExpr*>(CodeCompletionE); ShouldCompleteCallPatternAfterParen = true; if (Context.LangOpts.CodeCompleteCallPatternHeuristics) { // Lookahead one token to decide what kind of call completions to provide. // When it appears that there is already code for the call present, just // complete values and/or argument labels. Otherwise give the entire call // pattern. Token next = P.peekToken(); if (!next.isAtStartOfLine() && !next.is(tok::eof) && !next.is(tok::r_paren)) { ShouldCompleteCallPatternAfterParen = false; } } } void CodeCompletionCallbacksImpl::completeExprKeyPath(KeyPathExpr *KPE, SourceLoc DotLoc) { Kind = (!KPE || KPE->isObjC()) ? CompletionKind::KeyPathExprObjC : CompletionKind::KeyPathExprSwift; ParsedExpr = KPE; this->DotLoc = DotLoc; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completePoundAvailablePlatform() { Kind = CompletionKind::PoundAvailablePlatform; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeDeclResultBeginning() { Kind = CompletionKind::TypeDeclResultBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeSimpleBeginning() { Kind = CompletionKind::TypeSimpleBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeDeclAttrParam(DeclAttrKind DK, int Index) { Kind = CompletionKind::AttributeDeclParen; AttrKind = DK; AttrParamIndex = Index; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeEffectsSpecifier(bool hasAsync, bool hasThrows) { Kind = CompletionKind::EffectsSpecifier; CurDeclContext = P.CurDeclContext; ParsedKeywords.clear(); if (hasAsync) ParsedKeywords.emplace_back("async"); if (hasThrows) ParsedKeywords.emplace_back("throws"); } void CodeCompletionCallbacksImpl::completeDeclAttrBeginning( bool Sil, bool isIndependent) { Kind = CompletionKind::AttributeBegin; IsInSil = Sil; CurDeclContext = P.CurDeclContext; AttTargetIsIndependent = isIndependent; } void CodeCompletionCallbacksImpl::completeInPrecedenceGroup(SyntaxKind SK) { assert(P.Tok.is(tok::code_complete)); SyntxKind = SK; Kind = CompletionKind::PrecedenceGroup; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeIdentifierWithDot( IdentTypeRepr *ITR) { if (!ITR) { completeTypeSimpleBeginning(); return; } Kind = CompletionKind::TypeIdentifierWithDot; ParsedTypeLoc = TypeLoc(ITR); CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeIdentifierWithoutDot( IdentTypeRepr *ITR) { assert(ITR); Kind = CompletionKind::TypeIdentifierWithoutDot; ParsedTypeLoc = TypeLoc(ITR); CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeCaseStmtKeyword() { Kind = CompletionKind::CaseStmtKeyword; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeCaseStmtBeginning(CodeCompletionExpr *E) { assert(!InEnumElementRawValue); Kind = CompletionKind::CaseStmtBeginning; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeImportDecl( ImportPath::Builder &Path) { Kind = CompletionKind::Import; CurDeclContext = P.CurDeclContext; DotLoc = Path.empty() ? SourceLoc() : Path.back().Loc; if (DotLoc.isInvalid()) return; auto Importer = static_cast<ClangImporter *>(CurDeclContext->getASTContext(). getClangModuleLoader()); std::vector<std::string> SubNames; Importer->collectSubModuleNames(Path.get().getModulePath(false), SubNames); ASTContext &Ctx = CurDeclContext->getASTContext(); Path.push_back(Identifier()); for (StringRef Sub : SubNames) { Path.back().Item = Ctx.getIdentifier(Sub); SubModuleNameVisibilityPairs.push_back( std::make_pair(Sub.str(), Ctx.getLoadedModule(Path.get().getModulePath(false)))); } Path.pop_back(); } void CodeCompletionCallbacksImpl::completeUnresolvedMember(CodeCompletionExpr *E, SourceLoc DotLoc) { Kind = CompletionKind::UnresolvedMember; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; this->DotLoc = DotLoc; } void CodeCompletionCallbacksImpl::completeCallArg(CodeCompletionExpr *E, bool isFirst) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::CallArg; ShouldCompleteCallPatternAfterParen = false; if (isFirst) { ShouldCompleteCallPatternAfterParen = true; if (Context.LangOpts.CodeCompleteCallPatternHeuristics) { // Lookahead one token to decide what kind of call completions to provide. // When it appears that there is already code for the call present, just // complete values and/or argument labels. Otherwise give the entire call // pattern. Token next = P.peekToken(); if (!next.isAtStartOfLine() && !next.is(tok::eof) && !next.is(tok::r_paren)) { ShouldCompleteCallPatternAfterParen = false; } } } } void CodeCompletionCallbacksImpl::completeLabeledTrailingClosure( CodeCompletionExpr *E, bool isAtStartOfLine) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::LabeledTrailingClosure; IsAtStartOfLine = isAtStartOfLine; } void CodeCompletionCallbacksImpl::completeReturnStmt(CodeCompletionExpr *E) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::ReturnStmtExpr; } void CodeCompletionCallbacksImpl::completeYieldStmt(CodeCompletionExpr *E, Optional<unsigned> index) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; // TODO: use a different completion kind when completing without an index // in a multiple-value context. Kind = CompletionKind::YieldStmtExpr; } void CodeCompletionCallbacksImpl::completeAfterPoundExpr( CodeCompletionExpr *E, Optional<StmtKind> ParentKind) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::AfterPoundExpr; ParentStmtKind = ParentKind; } void CodeCompletionCallbacksImpl::completeAfterPoundDirective() { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::AfterPoundDirective; } void CodeCompletionCallbacksImpl::completePlatformCondition() { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::PlatformConditon; } void CodeCompletionCallbacksImpl::completeAfterIfStmt(bool hasElse) { CurDeclContext = P.CurDeclContext; if (hasElse) { Kind = CompletionKind::AfterIfStmtElse; } else { Kind = CompletionKind::StmtOrExpr; } } void CodeCompletionCallbacksImpl::completeGenericRequirement() { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::GenericRequirement; } void CodeCompletionCallbacksImpl::completeNominalMemberBeginning( SmallVectorImpl<StringRef> &Keywords, SourceLoc introducerLoc) { assert(!InEnumElementRawValue); this->introducerLoc = introducerLoc; ParsedKeywords.clear(); ParsedKeywords.append(Keywords.begin(), Keywords.end()); Kind = CompletionKind::NominalMemberBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeAccessorBeginning( CodeCompletionExpr *E) { Kind = CompletionKind::AccessorBeginning; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeStmtLabel(StmtKind ParentKind) { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::StmtLabel; ParentStmtKind = ParentKind; } static bool isDynamicLookup(Type T) { return T->getRValueType()->isAnyObject(); } static bool isClangSubModule(ModuleDecl *TheModule) { if (auto ClangMod = TheModule->findUnderlyingClangModule()) return ClangMod->isSubModule(); return false; } static void addKeyword(CodeCompletionResultSink &Sink, StringRef Name, CodeCompletionKeywordKind Kind, StringRef TypeAnnotation = "", CodeCompletionResult::ExpectedTypeRelation TypeRelation = CodeCompletionResult::ExpectedTypeRelation::NotApplicable) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(Kind); Builder.addKeyword(Name); if (!TypeAnnotation.empty()) Builder.addTypeAnnotation(TypeAnnotation); Builder.setExpectedTypeRelation(TypeRelation); } static void addDeclKeywords(CodeCompletionResultSink &Sink, bool IsConcurrencyEnabled) { auto AddDeclKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind, Optional<DeclAttrKind> DAK) { if (Name == "let" || Name == "var") { // Treat keywords that could be the start of a pattern specially. return; } // FIXME: This should use canUseAttributeOnDecl. // Remove user inaccessible keywords. if (DAK.hasValue() && DeclAttribute::isUserInaccessible(*DAK)) return; // Remove keywords only available when concurrency is enabled. if (DAK.hasValue() && !IsConcurrencyEnabled && DeclAttribute::isConcurrencyOnly(*DAK)) return; addKeyword(Sink, Name, Kind); }; #define DECL_KEYWORD(kw) AddDeclKeyword(#kw, CodeCompletionKeywordKind::kw_##kw, None); #include "swift/Syntax/TokenKinds.def" // Context-sensitive keywords. auto AddCSKeyword = [&](StringRef Name, DeclAttrKind Kind) { AddDeclKeyword(Name, CodeCompletionKeywordKind::None, Kind); }; #define CONTEXTUAL_CASE(KW, CLASS) AddCSKeyword(#KW, DAK_##CLASS); #define CONTEXTUAL_DECL_ATTR(KW, CLASS, ...) CONTEXTUAL_CASE(KW, CLASS) #define CONTEXTUAL_DECL_ATTR_ALIAS(KW, CLASS) CONTEXTUAL_CASE(KW, CLASS) #define CONTEXTUAL_SIMPLE_DECL_ATTR(KW, CLASS, ...) CONTEXTUAL_CASE(KW, CLASS) #include <swift/AST/Attr.def> #undef CONTEXTUAL_CASE } static void addStmtKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody) { auto AddStmtKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { if (!MaybeFuncBody && Kind == CodeCompletionKeywordKind::kw_return) return; addKeyword(Sink, Name, Kind); }; #define STMT_KEYWORD(kw) AddStmtKeyword(#kw, CodeCompletionKeywordKind::kw_##kw); #include "swift/Syntax/TokenKinds.def" } static void addCaseStmtKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, "case", CodeCompletionKeywordKind::kw_case); addKeyword(Sink, "default", CodeCompletionKeywordKind::kw_default); } static void addLetVarKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, "let", CodeCompletionKeywordKind::kw_let); addKeyword(Sink, "var", CodeCompletionKeywordKind::kw_var); } static void addAccessorKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, "get", CodeCompletionKeywordKind::None); addKeyword(Sink, "set", CodeCompletionKeywordKind::None); } static void addObserverKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, "willSet", CodeCompletionKeywordKind::None); addKeyword(Sink, "didSet", CodeCompletionKeywordKind::None); } static void addExprKeywords(CodeCompletionResultSink &Sink) { // Expr keywords. addKeyword(Sink, "try", CodeCompletionKeywordKind::kw_try); addKeyword(Sink, "try!", CodeCompletionKeywordKind::kw_try); addKeyword(Sink, "try?", CodeCompletionKeywordKind::kw_try); addKeyword(Sink, "await", CodeCompletionKeywordKind::None); } static void addOpaqueTypeKeyword(CodeCompletionResultSink &Sink) { addKeyword(Sink, "some", CodeCompletionKeywordKind::None, "some"); } static void addAnyTypeKeyword(CodeCompletionResultSink &Sink, Type T) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(CodeCompletionKeywordKind::None); Builder.addKeyword("Any"); Builder.addTypeAnnotation(T, PrintOptions()); } void CodeCompletionCallbacksImpl::addKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody) { switch (Kind) { case CompletionKind::None: case CompletionKind::DotExpr: case CompletionKind::AttributeDeclParen: case CompletionKind::AttributeBegin: case CompletionKind::PoundAvailablePlatform: case CompletionKind::Import: case CompletionKind::UnresolvedMember: case CompletionKind::CallArg: case CompletionKind::LabeledTrailingClosure: case CompletionKind::AfterPoundExpr: case CompletionKind::AfterPoundDirective: case CompletionKind::PlatformConditon: case CompletionKind::GenericRequirement: case CompletionKind::KeyPathExprObjC: case CompletionKind::KeyPathExprSwift: case CompletionKind::PrecedenceGroup: case CompletionKind::StmtLabel: break; case CompletionKind::EffectsSpecifier: { if (!llvm::is_contained(ParsedKeywords, "async")) addKeyword(Sink, "async", CodeCompletionKeywordKind::None); if (!llvm::is_contained(ParsedKeywords, "throws")) addKeyword(Sink, "throws", CodeCompletionKeywordKind::kw_throws); break; } case CompletionKind::AccessorBeginning: { // TODO: Omit already declared or mutally exclusive accessors. // E.g. If 'get' is already declared, emit 'set' only. addAccessorKeywords(Sink); // Only 'var' for non-protocol context can have 'willSet' and 'didSet'. assert(ParsedDecl); VarDecl *var = dyn_cast<VarDecl>(ParsedDecl); if (auto accessor = dyn_cast<AccessorDecl>(ParsedDecl)) var = dyn_cast<VarDecl>(accessor->getStorage()); if (var && !var->getDeclContext()->getSelfProtocolDecl()) addObserverKeywords(Sink); if (!isa<AccessorDecl>(ParsedDecl)) break; MaybeFuncBody = true; LLVM_FALLTHROUGH; } case CompletionKind::StmtOrExpr: addDeclKeywords(Sink, Context.LangOpts.EnableExperimentalConcurrency); addStmtKeywords(Sink, MaybeFuncBody); LLVM_FALLTHROUGH; case CompletionKind::ReturnStmtExpr: case CompletionKind::YieldStmtExpr: case CompletionKind::PostfixExprBeginning: case CompletionKind::ForEachSequence: addSuperKeyword(Sink); addLetVarKeywords(Sink); addExprKeywords(Sink); addAnyTypeKeyword(Sink, CurDeclContext->getASTContext().TheAnyType); break; case CompletionKind::CaseStmtKeyword: addCaseStmtKeywords(Sink); break; case CompletionKind::PostfixExpr: case CompletionKind::PostfixExprParen: case CompletionKind::CaseStmtBeginning: case CompletionKind::TypeIdentifierWithDot: case CompletionKind::TypeIdentifierWithoutDot: break; case CompletionKind::TypeDeclResultBeginning: { auto DC = CurDeclContext; if (ParsedDecl && ParsedDecl == CurDeclContext->getAsDecl()) DC = ParsedDecl->getDeclContext(); if (!isa<ProtocolDecl>(DC)) if (DC->isTypeContext() || (ParsedDecl && isa<FuncDecl>(ParsedDecl))) addOpaqueTypeKeyword(Sink); LLVM_FALLTHROUGH; } case CompletionKind::TypeSimpleBeginning: addAnyTypeKeyword(Sink, CurDeclContext->getASTContext().TheAnyType); break; case CompletionKind::NominalMemberBeginning: { bool HasDeclIntroducer = llvm::find_if(ParsedKeywords, [this](const StringRef kw) { return llvm::StringSwitch<bool>(kw) .Case("associatedtype", true) .Case("class", !CurDeclContext || !isa<ClassDecl>(CurDeclContext)) .Case("deinit", true) .Case("enum", true) .Case("extension", true) .Case("func", true) .Case("import", true) .Case("init", true) .Case("let", true) .Case("operator", true) .Case("precedencegroup", true) .Case("protocol", true) .Case("struct", true) .Case("subscript", true) .Case("typealias", true) .Case("var", true) .Default(false); }) != ParsedKeywords.end(); if (!HasDeclIntroducer) { addDeclKeywords(Sink, Context.LangOpts.EnableExperimentalConcurrency); addLetVarKeywords(Sink); } break; } case CompletionKind::AfterIfStmtElse: addKeyword(Sink, "if", CodeCompletionKeywordKind::kw_if); break; } } static void addPoundDirectives(CodeCompletionResultSink &Sink) { auto addWithName = [&](StringRef name, CodeCompletionKeywordKind K, llvm::function_ref<void(CodeCompletionResultBuilder &)> consumer = nullptr) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::Keyword, SemanticContextKind::None, {}); Builder.addBaseName(name); Builder.setKeywordKind(K); if (consumer) consumer(Builder); }; addWithName("sourceLocation", CodeCompletionKeywordKind::pound_sourceLocation, [&] (CodeCompletionResultBuilder &Builder) { Builder.addLeftParen(); Builder.addTextChunk("file"); Builder.addCallParameterColon(); Builder.addSimpleTypedParameter("String"); Builder.addComma(); Builder.addTextChunk("line"); Builder.addCallParameterColon(); Builder.addSimpleTypedParameter("Int"); Builder.addRightParen(); }); addWithName("warning", CodeCompletionKeywordKind::pound_warning, [&] (CodeCompletionResultBuilder &Builder) { Builder.addLeftParen(); Builder.addTextChunk("\""); Builder.addSimpleNamedParameter("message"); Builder.addTextChunk("\""); Builder.addRightParen(); }); addWithName("error", CodeCompletionKeywordKind::pound_error, [&] (CodeCompletionResultBuilder &Builder) { Builder.addLeftParen(); Builder.addTextChunk("\""); Builder.addSimpleNamedParameter("message"); Builder.addTextChunk("\""); Builder.addRightParen(); }); addWithName("if ", CodeCompletionKeywordKind::pound_if, [&] (CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter("condition"); }); // FIXME: These directives are only valid in conditional completion block. addWithName("elseif ", CodeCompletionKeywordKind::pound_elseif, [&] (CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter("condition"); }); addWithName("else", CodeCompletionKeywordKind::pound_else); addWithName("endif", CodeCompletionKeywordKind::pound_endif); } /// Add platform conditions used in '#if' and '#elseif' directives. static void addPlatformConditions(CodeCompletionResultSink &Sink) { auto addWithName = [&](StringRef Name, llvm::function_ref<void(CodeCompletionResultBuilder & Builder)> consumer) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Pattern, SemanticContextKind::ExpressionSpecific, {}); Builder.addBaseName(Name); Builder.addLeftParen(); consumer(Builder); Builder.addRightParen(); }; addWithName("os", [](CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter("name"); }); addWithName("arch", [](CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter("name"); }); addWithName("canImport", [](CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter("module"); }); addWithName("targetEnvironment", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk("simulator"); }); addWithName("swift", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk(">="); Builder.addSimpleNamedParameter("version"); }); addWithName("swift", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk("<"); Builder.addSimpleNamedParameter("version"); }); addWithName("compiler", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk(">="); Builder.addSimpleNamedParameter("version"); }); addWithName("compiler", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk("<"); Builder.addSimpleNamedParameter("version"); }); addKeyword(Sink, "true", CodeCompletionKeywordKind::kw_true, "Bool"); addKeyword(Sink, "false", CodeCompletionKeywordKind::kw_false, "Bool"); } /// Add flags specified by '-D' to completion results. static void addConditionalCompilationFlags(ASTContext &Ctx, CodeCompletionResultSink &Sink) { for (auto Flag : Ctx.LangOpts.getCustomConditionalCompilationFlags()) { // TODO: Should we filter out some flags? CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::ExpressionSpecific, {}); Builder.addTextChunk(Flag); } } static void deliverCompletionResults(CodeCompletionContext &CompletionContext, CompletionLookup &Lookup, SourceFile &SF, CodeCompletionConsumer &Consumer) { llvm::SmallPtrSet<Identifier, 8> seenModuleNames; std::vector<RequestedCachedModule> RequestedModules; for (auto &Request: Lookup.RequestedCachedResults) { llvm::DenseSet<CodeCompletionCache::Key> ImportsSeen; auto handleImport = [&](ImportedModule Import) { ModuleDecl *TheModule = Import.importedModule; ImportPath::Access Path = Import.accessPath; if (TheModule->getFiles().empty()) return; // Clang submodules are ignored and there's no lookup cost involved, // so just ignore them and don't put the empty results in the cache // because putting a lot of objects in the cache will push out // other lookups. if (isClangSubModule(TheModule)) return; std::vector<std::string> AccessPath; for (auto Piece : Path) { AccessPath.push_back(std::string(Piece.Item)); } StringRef ModuleFilename = TheModule->getModuleFilename(); // ModuleFilename can be empty if something strange happened during // module loading, for example, the module file is corrupted. if (!ModuleFilename.empty()) { auto &Ctx = TheModule->getASTContext(); CodeCompletionCache::Key K{ ModuleFilename.str(), std::string(TheModule->getName()), AccessPath, Request.NeedLeadingDot, SF.hasTestableOrPrivateImport( AccessLevel::Internal, TheModule, SourceFile::ImportQueryKind::TestableOnly), SF.hasTestableOrPrivateImport( AccessLevel::Internal, TheModule, SourceFile::ImportQueryKind::PrivateOnly), Ctx.LangOpts.CodeCompleteInitsInPostfixExpr, CompletionContext.getAnnotateResult(), }; using PairType = llvm::DenseSet<swift::ide::CodeCompletionCache::Key, llvm::DenseMapInfo<CodeCompletionCache::Key>>::iterator; std::pair<PairType, bool> Result = ImportsSeen.insert(K); if (!Result.second) return; // already handled. RequestedModules.push_back({std::move(K), TheModule, Request.OnlyTypes, Request.OnlyPrecedenceGroups}); if (Request.IncludeModuleQualifier && seenModuleNames.insert(TheModule->getName()).second) Lookup.addModuleName(TheModule); } }; if (Request.TheModule) { // FIXME: actually check imports. for (auto Import : namelookup::getAllImports(Request.TheModule)) { handleImport(Import); } } else { // Add results from current module. Lookup.getToplevelCompletions(Request.OnlyTypes); // Add the qualifying module name auto curModule = SF.getParentModule(); if (Request.IncludeModuleQualifier && seenModuleNames.insert(curModule->getName()).second) Lookup.addModuleName(curModule); // Add results for all imported modules. SmallVector<ImportedModule, 4> Imports; SF.getImportedModules( Imports, {ModuleDecl::ImportFilterKind::Exported, ModuleDecl::ImportFilterKind::Default, ModuleDecl::ImportFilterKind::ImplementationOnly}); for (auto Imported : Imports) { for (auto Import : namelookup::getAllImports(Imported.importedModule)) handleImport(Import); } } } Lookup.RequestedCachedResults.clear(); CompletionContext.typeContextKind = Lookup.typeContextKind(); // Use the current SourceFile as the DeclContext so that we can use it to // perform qualified lookup, and to get the correct visibility for // @testable imports. DeclContext *DCForModules = &SF; Consumer.handleResultsAndModules(CompletionContext, RequestedModules, DCForModules); } void deliverUnresolvedMemberResults( ArrayRef<UnresolvedMemberTypeCheckCompletionCallback::Result> Results, DeclContext *DC, SourceLoc DotLoc, ide::CodeCompletionContext &CompletionCtx, CodeCompletionConsumer &Consumer) { ASTContext &Ctx = DC->getASTContext(); CompletionLookup Lookup(CompletionCtx.getResultSink(), Ctx, DC, &CompletionCtx); assert(DotLoc.isValid()); Lookup.setHaveDot(DotLoc); Lookup.shouldCheckForDuplicates(Results.size() > 1); // Get the canonical versions of the top-level types SmallPtrSet<CanType, 4> originalTypes; for (auto &Result: Results) originalTypes.insert(Result.ExpectedTy->getCanonicalType()); for (auto &Result: Results) { Lookup.setExpectedTypes({Result.ExpectedTy}, Result.IsImplicitSingleExpressionReturn, /*expectsNonVoid*/true); Lookup.setIdealExpectedType(Result.ExpectedTy); // For optional types, also get members of the unwrapped type if it's not // already equivalent to one of the top-level types. Handling it via the top // level type and not here ensures we give the correct type relation // (identical, rather than convertible). if (Result.ExpectedTy->getOptionalObjectType()) { Type Unwrapped = Result.ExpectedTy->lookThroughAllOptionalTypes(); if (originalTypes.insert(Unwrapped->getCanonicalType()).second) Lookup.getUnresolvedMemberCompletions(Unwrapped); } Lookup.getUnresolvedMemberCompletions(Result.ExpectedTy); } SourceFile *SF = DC->getParentSourceFile(); deliverCompletionResults(CompletionCtx, Lookup, *SF, Consumer); } void deliverDotExprResults( ArrayRef<DotExprTypeCheckCompletionCallback::Result> Results, Expr *BaseExpr, DeclContext *DC, SourceLoc DotLoc, bool IsInSelector, ide::CodeCompletionContext &CompletionCtx, CodeCompletionConsumer &Consumer) { ASTContext &Ctx = DC->getASTContext(); CompletionLookup Lookup(CompletionCtx.getResultSink(), Ctx, DC, &CompletionCtx); if (DotLoc.isValid()) Lookup.setHaveDot(DotLoc); Lookup.setIsSuperRefExpr(isa<SuperRefExpr>(BaseExpr)); if (auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) Lookup.setIsSelfRefExpr(DRE->getDecl()->getName() == Ctx.Id_self); if (isa<BindOptionalExpr>(BaseExpr) || isa<ForceValueExpr>(BaseExpr)) Lookup.setIsUnwrappedOptional(true); if (IsInSelector) { Lookup.includeInstanceMembers(); Lookup.setPreferFunctionReferencesToCalls(); } Lookup.shouldCheckForDuplicates(Results.size() > 1); for (auto &Result: Results) { Lookup.setIsStaticMetatype(Result.BaseIsStaticMetaType); Lookup.getPostfixKeywordCompletions(Result.BaseTy, BaseExpr); Lookup.setExpectedTypes(Result.ExpectedTypes, Result.IsImplicitSingleExpressionReturn, Result.ExpectsNonVoid); if (isDynamicLookup(Result.BaseTy)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(Result.BaseTy, Result.BaseDecl); } SourceFile *SF = DC->getParentSourceFile(); deliverCompletionResults(CompletionCtx, Lookup, *SF, Consumer); } bool CodeCompletionCallbacksImpl::trySolverCompletion(bool MaybeFuncBody) { assert(ParsedExpr || CurDeclContext); SourceLoc CompletionLoc = ParsedExpr ? ParsedExpr->getLoc() : CurDeclContext->getASTContext().SourceMgr.getCodeCompletionLoc(); switch (Kind) { case CompletionKind::DotExpr: { assert(CodeCompleteTokenExpr); assert(CurDeclContext); DotExprTypeCheckCompletionCallback Lookup(CurDeclContext, CodeCompleteTokenExpr); llvm::SaveAndRestore<TypeCheckCompletionCallback*> CompletionCollector(Context.CompletionCallback, &Lookup); typeCheckContextAt(CurDeclContext, CompletionLoc); // This (hopefully) only happens in cases where the expression isn't // typechecked during normal compilation either (e.g. member completion in a // switch case where there control expression is invalid). Having normal // typechecking still resolve even these cases would be beneficial for // tooling in general though. if (!Lookup.gotCallback()) Lookup.fallbackTypeCheck(); addKeywords(CompletionContext.getResultSink(), MaybeFuncBody); Expr *CheckedBase = CodeCompleteTokenExpr->getBase(); deliverDotExprResults(Lookup.getResults(), CheckedBase, CurDeclContext, DotLoc, isInsideObjCSelector(), CompletionContext, Consumer); return true; } case CompletionKind::UnresolvedMember: { assert(CodeCompleteTokenExpr); assert(CurDeclContext); UnresolvedMemberTypeCheckCompletionCallback Lookup(CodeCompleteTokenExpr); llvm::SaveAndRestore<TypeCheckCompletionCallback*> CompletionCollector(Context.CompletionCallback, &Lookup); typeCheckContextAt(CurDeclContext, CompletionLoc); if (!Lookup.gotCallback()) Lookup.fallbackTypeCheck(CurDeclContext); addKeywords(CompletionContext.getResultSink(), MaybeFuncBody); deliverUnresolvedMemberResults(Lookup.getResults(), CurDeclContext, DotLoc, CompletionContext, Consumer); return true; } default: return false; } } // Undoes the single-expression closure/function body transformation on the // given DeclContext and its parent contexts if they have a single expression // body that contains the code completion location. // // FIXME: Remove this once all expression position completions are migrated // to work via TypeCheckCompletionCallback. static void undoSingleExpressionReturn(DeclContext *DC) { auto updateBody = [](BraceStmt *BS, ASTContext &Ctx) -> bool { ASTNode LastElem = BS->getLastElement(); auto *RS = dyn_cast_or_null<ReturnStmt>(LastElem.dyn_cast<Stmt*>()); if (!RS || !RS->isImplicit()) return false; BS->setLastElement(RS->getResult()); return true; }; while (ClosureExpr *CE = dyn_cast_or_null<ClosureExpr>(DC)) { if (CE->hasSingleExpressionBody()) { if (updateBody(CE->getBody(), CE->getASTContext())) CE->setBody(CE->getBody(), false); } DC = DC->getParent(); } if (FuncDecl *FD = dyn_cast_or_null<FuncDecl>(DC)) { if (FD->hasSingleExpressionBody()) { if (updateBody(FD->getBody(), FD->getASTContext())) FD->setHasSingleExpressionBody(false); } } } void CodeCompletionCallbacksImpl::doneParsing() { CompletionContext.CodeCompletionKind = Kind; if (Kind == CompletionKind::None) { return; } bool MaybeFuncBody = true; if (CurDeclContext) { auto *CD = CurDeclContext->getLocalContext(); if (!CD || CD->getContextKind() == DeclContextKind::Initializer || CD->getContextKind() == DeclContextKind::TopLevelCodeDecl) MaybeFuncBody = false; } if (auto *DC = dyn_cast_or_null<DeclContext>(ParsedDecl)) { if (DC->isChildContextOf(CurDeclContext)) CurDeclContext = DC; } if (trySolverCompletion(MaybeFuncBody)) return; undoSingleExpressionReturn(CurDeclContext); typeCheckContextAt( CurDeclContext, ParsedExpr ? ParsedExpr->getLoc() : CurDeclContext->getASTContext().SourceMgr.getCodeCompletionLoc()); // Add keywords even if type checking fails completely. addKeywords(CompletionContext.getResultSink(), MaybeFuncBody); Optional<Type> ExprType; ConcreteDeclRef ReferencedDecl = nullptr; if (ParsedExpr) { if (auto *checkedExpr = findParsedExpr(CurDeclContext, ParsedExpr->getSourceRange())) { ParsedExpr = checkedExpr; } if (auto typechecked = typeCheckParsedExpr()) { ExprType = typechecked->first; ReferencedDecl = typechecked->second; ParsedExpr->setType(*ExprType); } if (!ExprType && Kind != CompletionKind::PostfixExprParen && Kind != CompletionKind::CallArg && Kind != CompletionKind::KeyPathExprObjC) return; } if (!ParsedTypeLoc.isNull() && !typecheckParsedType()) return; CompletionLookup Lookup(CompletionContext.getResultSink(), P.Context, CurDeclContext, &CompletionContext); if (ExprType) { Lookup.setIsStaticMetatype(ParsedExpr->isStaticallyDerivedMetatype()); } if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(ParsedExpr)) { Lookup.setIsSelfRefExpr(DRE->getDecl()->getName() == Context.Id_self); } else if (ParsedExpr && isa<SuperRefExpr>(ParsedExpr)) { Lookup.setIsSuperRefExpr(); } if (isInsideObjCSelector()) Lookup.includeInstanceMembers(); if (PreferFunctionReferencesToCalls) Lookup.setPreferFunctionReferencesToCalls(); auto DoPostfixExprBeginning = [&] (){ SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getValueCompletionsInDeclContext(Loc); Lookup.getSelfTypeCompletionInDeclContext(Loc, /*isForDeclResult=*/false); }; switch (Kind) { case CompletionKind::None: case CompletionKind::DotExpr: case CompletionKind::UnresolvedMember: llvm_unreachable("should be already handled"); return; case CompletionKind::KeyPathExprSwift: { auto KPE = dyn_cast<KeyPathExpr>(ParsedExpr); auto BGT = (*ExprType)->getAs<BoundGenericType>(); if (!KPE || !BGT || BGT->getGenericArgs().size() != 2) break; assert(!KPE->isObjC()); if (DotLoc.isValid()) Lookup.setHaveDot(DotLoc); bool OnRoot = !KPE->getComponents().front().isValid(); Lookup.setIsSwiftKeyPathExpr(OnRoot); Type baseType = BGT->getGenericArgs()[OnRoot ? 0 : 1]; if (OnRoot && baseType->is<UnresolvedType>()) { // Infer the root type of the keypath from the context type. ExprContextInfo ContextInfo(CurDeclContext, ParsedExpr); for (auto T : ContextInfo.getPossibleTypes()) { if (auto unwrapped = T->getOptionalObjectType()) T = unwrapped; // If the context type is any of the KeyPath types, use it. if (T->getAnyNominal() && T->getAnyNominal()->getKeyPathTypeKind() && !T->hasUnresolvedType() && T->is<BoundGenericType>()) { baseType = T->castTo<BoundGenericType>()->getGenericArgs()[0]; break; } // KeyPath can be used as a function that receives its root type. if (T->is<AnyFunctionType>()) { auto *fnType = T->castTo<AnyFunctionType>(); if (fnType->getNumParams() == 1) { const AnyFunctionType::Param &param = fnType->getParams()[0]; baseType = param.getParameterType(); break; } } } } if (!OnRoot && KPE->getComponents().back().getKind() == KeyPathExpr::Component::Kind::OptionalWrap) { // KeyPath expr with '?' (e.g. '\Ty.[0].prop?.another'). // Although expected type is optional, we should unwrap it because it's // unwrapped. baseType = baseType->getOptionalObjectType(); } Lookup.getValueExprCompletions(baseType); break; } case CompletionKind::StmtOrExpr: case CompletionKind::ForEachSequence: case CompletionKind::PostfixExprBeginning: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); DoPostfixExprBeginning(); break; } case CompletionKind::PostfixExpr: { Lookup.setHaveLeadingSpace(HasSpace); if (isDynamicLookup(*ExprType)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); Lookup.getOperatorCompletions(ParsedExpr, leadingSequenceExprs); Lookup.getPostfixKeywordCompletions(*ExprType, ParsedExpr); break; } case CompletionKind::PostfixExprParen: { Lookup.setHaveLParen(true); ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); if (ShouldCompleteCallPatternAfterParen) { ExprContextInfo ParentContextInfo(CurDeclContext, ParsedExpr); Lookup.setExpectedTypes( ParentContextInfo.getPossibleTypes(), ParentContextInfo.isImplicitSingleExpressionReturn()); if (!ContextInfo.getPossibleCallees().empty()) { for (auto &typeAndDecl : ContextInfo.getPossibleCallees()) Lookup.tryFunctionCallCompletions(typeAndDecl.Type, typeAndDecl.Decl, typeAndDecl.SemanticContext); } else if (ExprType && ((*ExprType)->is<AnyFunctionType>() || (*ExprType)->is<AnyMetatypeType>())) { Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); } } else { // Add argument labels, then fallthrough to get values. Lookup.addCallArgumentCompletionResults(ContextInfo.getPossibleParams()); } if (!Lookup.FoundFunctionCalls || (Lookup.FoundFunctionCalls && Lookup.FoundFunctionsWithoutFirstKeyword)) { Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); Lookup.setHaveLParen(false); DoPostfixExprBeginning(); } break; } case CompletionKind::KeyPathExprObjC: { if (DotLoc.isValid()) Lookup.setHaveDot(DotLoc); Lookup.setIsKeyPathExpr(); Lookup.includeInstanceMembers(); if (ExprType) { if (isDynamicLookup(*ExprType)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); } else { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getValueCompletionsInDeclContext(Loc, KeyPathFilter, /*LiteralCompletions=*/false); } break; } case CompletionKind::TypeDeclResultBeginning: case CompletionKind::TypeSimpleBeginning: { auto Loc = Context.SourceMgr.getCodeCompletionLoc(); Lookup.getTypeCompletionsInDeclContext(Loc); Lookup.getSelfTypeCompletionInDeclContext( Loc, Kind == CompletionKind::TypeDeclResultBeginning); break; } case CompletionKind::TypeIdentifierWithDot: { Lookup.setHaveDot(SourceLoc()); Lookup.getTypeCompletions(ParsedTypeLoc.getType()); break; } case CompletionKind::TypeIdentifierWithoutDot: { Lookup.getTypeCompletions(ParsedTypeLoc.getType()); break; } case CompletionKind::CaseStmtBeginning: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); Lookup.setIdealExpectedType(CodeCompleteTokenExpr->getType()); Lookup.getUnresolvedMemberCompletions(ContextInfo.getPossibleTypes()); DoPostfixExprBeginning(); break; } case CompletionKind::NominalMemberBeginning: { CompletionOverrideLookup OverrideLookup(CompletionContext.getResultSink(), P.Context, CurDeclContext, ParsedKeywords, introducerLoc); OverrideLookup.getOverrideCompletions(SourceLoc()); break; } case CompletionKind::AccessorBeginning: { if (isa<AccessorDecl>(ParsedDecl)) { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); DoPostfixExprBeginning(); } break; } case CompletionKind::AttributeBegin: { Lookup.getAttributeDeclCompletions(IsInSil, AttTargetDK); // TypeName at attribute position after '@'. // - VarDecl: Property Wrappers. // - ParamDecl/VarDecl/FuncDecl: Function Builders. if (!AttTargetDK || *AttTargetDK == DeclKind::Var || *AttTargetDK == DeclKind::Param || *AttTargetDK == DeclKind::Func) Lookup.getTypeCompletionsInDeclContext( P.Context.SourceMgr.getCodeCompletionLoc()); break; } case CompletionKind::AttributeDeclParen: { Lookup.getAttributeDeclParamCompletions(AttrKind, AttrParamIndex); break; } case CompletionKind::PoundAvailablePlatform: { Lookup.getPoundAvailablePlatformCompletions(); break; } case CompletionKind::Import: { if (DotLoc.isValid()) Lookup.addSubModuleNames(SubModuleNameVisibilityPairs); else Lookup.addImportModuleNames(); break; } case CompletionKind::CallArg: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); bool shouldPerformGlobalCompletion = true; if (ShouldCompleteCallPatternAfterParen && !ContextInfo.getPossibleCallees().empty()) { Lookup.setHaveLParen(true); for (auto &typeAndDecl : ContextInfo.getPossibleCallees()) { auto apply = ContextInfo.getAnalyzedExpr(); if (apply && isa<SubscriptExpr>(apply)) { Lookup.addSubscriptCallPattern( typeAndDecl.Type, dyn_cast_or_null<SubscriptDecl>(typeAndDecl.Decl), typeAndDecl.SemanticContext); } else { Lookup.addFunctionCallPattern( typeAndDecl.Type, dyn_cast_or_null<AbstractFunctionDecl>(typeAndDecl.Decl), typeAndDecl.SemanticContext); } } Lookup.setHaveLParen(false); shouldPerformGlobalCompletion = !Lookup.FoundFunctionCalls || (Lookup.FoundFunctionCalls && Lookup.FoundFunctionsWithoutFirstKeyword); } else if (!ContextInfo.getPossibleParams().empty()) { auto params = ContextInfo.getPossibleParams(); Lookup.addCallArgumentCompletionResults(params); shouldPerformGlobalCompletion = !ContextInfo.getPossibleTypes().empty(); // Fallback to global completion if the position is out of number. It's // better than suggest nothing. shouldPerformGlobalCompletion |= llvm::all_of( params, [](const PossibleParamInfo &P) { return !P.Param; }); } if (shouldPerformGlobalCompletion) { Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); DoPostfixExprBeginning(); } break; } case CompletionKind::LabeledTrailingClosure: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); SmallVector<PossibleParamInfo, 2> params; // Only complete function type parameters llvm::copy_if(ContextInfo.getPossibleParams(), std::back_inserter(params), [](const PossibleParamInfo &P) { // nullptr indicates out of bounds. if (!P.Param) return true; return P.Param->getPlainType() ->lookThroughAllOptionalTypes() ->is<AnyFunctionType>(); }); bool allRequired = false; if (!params.empty()) { Lookup.addCallArgumentCompletionResults( params, /*isLabeledTrailingClosure=*/true); allRequired = llvm::all_of( params, [](const PossibleParamInfo &P) { return P.IsRequired; }); } // If there're optional parameters, do global completion or member // completion depending on the completion is happening at the start of line. if (!allRequired) { if (IsAtStartOfLine) { // foo() {} // <HERE> auto &Sink = CompletionContext.getResultSink(); if (isa<Initializer>(CurDeclContext)) CurDeclContext = CurDeclContext->getParent(); if (CurDeclContext->isTypeContext()) { // Override completion (CompletionKind::NominalMemberBeginning). addDeclKeywords(Sink, Context.LangOpts.EnableExperimentalConcurrency); addLetVarKeywords(Sink); SmallVector<StringRef, 0> ParsedKeywords; CompletionOverrideLookup OverrideLookup(Sink, Context, CurDeclContext, ParsedKeywords, SourceLoc()); OverrideLookup.getOverrideCompletions(SourceLoc()); } else { // Global completion (CompletionKind::PostfixExprBeginning). addDeclKeywords(Sink, Context.LangOpts.EnableExperimentalConcurrency); addStmtKeywords(Sink, MaybeFuncBody); addSuperKeyword(Sink); addLetVarKeywords(Sink); addExprKeywords(Sink); addAnyTypeKeyword(Sink, Context.TheAnyType); DoPostfixExprBeginning(); } } else { // foo() {} <HERE> // Member completion. Expr *analyzedExpr = ContextInfo.getAnalyzedExpr(); if (!analyzedExpr) break; // Only if the completion token is the last token in the call. if (analyzedExpr->getEndLoc() != CodeCompleteTokenExpr->getLoc()) break; Type resultTy = analyzedExpr->getType(); // If the call expression doesn't have a type, fallback to: if (!resultTy || resultTy->is<ErrorType>()) { // 1) Try to type check removing CodeCompletionExpr from the call. Expr *removedExpr = analyzedExpr; removeCodeCompletionExpr(CurDeclContext->getASTContext(), removedExpr); ConcreteDeclRef referencedDecl; auto optT = getTypeOfCompletionContextExpr( CurDeclContext->getASTContext(), CurDeclContext, CompletionTypeCheckKind::Normal, removedExpr, referencedDecl); if (optT) { resultTy = *optT; analyzedExpr->setType(resultTy); } } if (!resultTy || resultTy->is<ErrorType>()) { // 2) Infer it from the possible callee info. if (!ContextInfo.getPossibleCallees().empty()) { auto calleeInfo = ContextInfo.getPossibleCallees()[0]; resultTy = calleeInfo.Type->getResult(); analyzedExpr->setType(resultTy); } } if (!resultTy || resultTy->is<ErrorType>()) { // 3) Give up providing postfix completions. break; } auto &SM = CurDeclContext->getASTContext().SourceMgr; auto leadingChar = SM.extractText({SM.getCodeCompletionLoc().getAdvancedLoc(-1), 1}); Lookup.setHaveLeadingSpace(leadingChar.find_first_of(" \t\f\v") != StringRef::npos); if (isDynamicLookup(resultTy)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(resultTy, /*VD=*/nullptr); Lookup.getOperatorCompletions(analyzedExpr, leadingSequenceExprs); Lookup.getPostfixKeywordCompletions(resultTy, analyzedExpr); } } break; } case CompletionKind::ReturnStmtExpr : { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); SmallVector<Type, 2> possibleReturnTypes; collectPossibleReturnTypesFromContext(CurDeclContext, possibleReturnTypes); Lookup.setExpectedTypes(possibleReturnTypes, /*isImplicitSingleExpressionReturn*/ false); Lookup.getValueCompletionsInDeclContext(Loc); break; } case CompletionKind::YieldStmtExpr: { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); if (auto FD = dyn_cast<AccessorDecl>(CurDeclContext)) { if (FD->isCoroutine()) { // TODO: handle multi-value yields. Lookup.setExpectedTypes(FD->getStorage()->getValueInterfaceType(), /*isImplicitSingleExpressionReturn*/ false); } } Lookup.getValueCompletionsInDeclContext(Loc); break; } case CompletionKind::AfterPoundExpr: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); Lookup.addPoundAvailable(ParentStmtKind); Lookup.addPoundLiteralCompletions(/*needPound=*/false); Lookup.addObjCPoundKeywordCompletions(/*needPound=*/false); break; } case CompletionKind::AfterPoundDirective: { addPoundDirectives(CompletionContext.getResultSink()); // FIXME: Add pound expressions (e.g. '#selector()') if it's at statements // position. break; } case CompletionKind::PlatformConditon: { addPlatformConditions(CompletionContext.getResultSink()); addConditionalCompilationFlags(CurDeclContext->getASTContext(), CompletionContext.getResultSink()); break; } case CompletionKind::GenericRequirement: { auto Loc = Context.SourceMgr.getCodeCompletionLoc(); Lookup.getGenericRequirementCompletions(CurDeclContext, Loc); break; } case CompletionKind::PrecedenceGroup: Lookup.getPrecedenceGroupCompletions(SyntxKind); break; case CompletionKind::StmtLabel: { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getStmtLabelCompletions(Loc, ParentStmtKind == StmtKind::Continue); break; } case CompletionKind::AfterIfStmtElse: case CompletionKind::CaseStmtKeyword: case CompletionKind::EffectsSpecifier: // Handled earlier by keyword completions. break; } deliverCompletionResults(CompletionContext, Lookup, P.SF, Consumer); } void PrintingCodeCompletionConsumer::handleResults( MutableArrayRef<CodeCompletionResult *> Results) { unsigned NumResults = 0; for (auto Result : Results) { if (!IncludeKeywords && Result->getKind() == CodeCompletionResult::Keyword) continue; ++NumResults; } if (NumResults == 0) return; OS << "Begin completions, " << NumResults << " items\n"; for (auto Result : Results) { if (!IncludeKeywords && Result->getKind() == CodeCompletionResult::Keyword) continue; Result->printPrefix(OS); if (PrintAnnotatedDescription) { printCodeCompletionResultDescriptionAnnotated(*Result, OS, /*leadingPunctuation=*/false); OS << "; typename="; printCodeCompletionResultTypeNameAnnotated(*Result, OS); } else { Result->getCompletionString()->print(OS); } llvm::SmallString<64> Name; llvm::raw_svector_ostream NameOs(Name); Result->getCompletionString()->getName(NameOs); OS << "; name=" << Name; StringRef comment = Result->getBriefDocComment(); if (IncludeComments && !comment.empty()) { OS << "; comment=" << comment; } OS << "\n"; } OS << "End completions\n"; } namespace { class CodeCompletionCallbacksFactoryImpl : public CodeCompletionCallbacksFactory { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; public: CodeCompletionCallbacksFactoryImpl(CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CompletionContext(CompletionContext), Consumer(Consumer) {} CodeCompletionCallbacks *createCodeCompletionCallbacks(Parser &P) override { return new CodeCompletionCallbacksImpl(P, CompletionContext, Consumer); } }; } // end anonymous namespace CodeCompletionCallbacksFactory * swift::ide::makeCodeCompletionCallbacksFactory( CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) { return new CodeCompletionCallbacksFactoryImpl(CompletionContext, Consumer); } void swift::ide::lookupCodeCompletionResultsFromModule( CodeCompletionResultSink &targetSink, const ModuleDecl *module, ArrayRef<std::string> accessPath, bool needLeadingDot, const DeclContext *currDeclContext) { CompletionLookup Lookup(targetSink, module->getASTContext(), currDeclContext); Lookup.lookupExternalModuleDecls(module, accessPath, needLeadingDot); } void swift::ide::copyCodeCompletionResults(CodeCompletionResultSink &targetSink, CodeCompletionResultSink &sourceSink, bool onlyTypes, bool onlyPrecedenceGroups) { // We will be adding foreign results (from another sink) into TargetSink. // TargetSink should have an owning pointer to the allocator that keeps the // results alive. targetSink.ForeignAllocators.push_back(sourceSink.Allocator); if (onlyTypes) { std::copy_if(sourceSink.Results.begin(), sourceSink.Results.end(), std::back_inserter(targetSink.Results), [](CodeCompletionResult *R) -> bool { if (R->getKind() != CodeCompletionResult::Declaration) return false; switch(R->getAssociatedDeclKind()) { case CodeCompletionDeclKind::Module: case CodeCompletionDeclKind::Class: case CodeCompletionDeclKind::Struct: case CodeCompletionDeclKind::Enum: case CodeCompletionDeclKind::Protocol: case CodeCompletionDeclKind::TypeAlias: case CodeCompletionDeclKind::AssociatedType: case CodeCompletionDeclKind::GenericTypeParam: return true; case CodeCompletionDeclKind::PrecedenceGroup: case CodeCompletionDeclKind::EnumElement: case CodeCompletionDeclKind::Constructor: case CodeCompletionDeclKind::Destructor: case CodeCompletionDeclKind::Subscript: case CodeCompletionDeclKind::StaticMethod: case CodeCompletionDeclKind::InstanceMethod: case CodeCompletionDeclKind::PrefixOperatorFunction: case CodeCompletionDeclKind::PostfixOperatorFunction: case CodeCompletionDeclKind::InfixOperatorFunction: case CodeCompletionDeclKind::FreeFunction: case CodeCompletionDeclKind::StaticVar: case CodeCompletionDeclKind::InstanceVar: case CodeCompletionDeclKind::LocalVar: case CodeCompletionDeclKind::GlobalVar: return false; } llvm_unreachable("Unhandled CodeCompletionDeclKind in switch."); }); } else if (onlyPrecedenceGroups) { std::copy_if(sourceSink.Results.begin(), sourceSink.Results.end(), std::back_inserter(targetSink.Results), [](CodeCompletionResult *R) -> bool { return R->getAssociatedDeclKind() == CodeCompletionDeclKind::PrecedenceGroup; }); } else { targetSink.Results.insert(targetSink.Results.end(), sourceSink.Results.begin(), sourceSink.Results.end()); } } void SimpleCachingCodeCompletionConsumer::handleResultsAndModules( CodeCompletionContext &context, ArrayRef<RequestedCachedModule> requestedModules, DeclContext *DCForModules) { for (auto &R : requestedModules) { // FIXME(thread-safety): lock the whole AST context. We might load a // module. llvm::Optional<CodeCompletionCache::ValueRefCntPtr> V = context.Cache.get(R.Key); if (!V.hasValue()) { // No cached results found. Fill the cache. V = context.Cache.createValue(); (*V)->Sink.annotateResult = context.getAnnotateResult(); lookupCodeCompletionResultsFromModule( (*V)->Sink, R.TheModule, R.Key.AccessPath, R.Key.ResultsHaveLeadingDot, DCForModules); context.Cache.set(R.Key, *V); } assert(V.hasValue()); copyCodeCompletionResults(context.getResultSink(), (*V)->Sink, R.OnlyTypes, R.OnlyPrecedenceGroups); } handleResults(context.takeResults()); } //===----------------------------------------------------------------------===// // ImportDepth //===----------------------------------------------------------------------===// ImportDepth::ImportDepth(ASTContext &context, const FrontendOptions &frontendOptions) { llvm::DenseSet<ModuleDecl *> seen; std::deque<std::pair<ModuleDecl *, uint8_t>> worklist; StringRef mainModule = frontendOptions.ModuleName; auto *main = context.getLoadedModule(context.getIdentifier(mainModule)); assert(main && "missing main module"); worklist.emplace_back(main, uint8_t(0)); // Imports from -import-name such as Playground auxiliary sources are treated // specially by applying import depth 0. llvm::StringSet<> auxImports; for (const auto &pair : frontendOptions.getImplicitImportModuleNames()) auxImports.insert(pair.first); // Private imports from this module. // FIXME: only the private imports from the current source file. // FIXME: ImportFilterKind::ShadowedByCrossImportOverlay? SmallVector<ImportedModule, 16> mainImports; main->getImportedModules(mainImports, {ModuleDecl::ImportFilterKind::Default, ModuleDecl::ImportFilterKind::ImplementationOnly}); for (auto &import : mainImports) { uint8_t depth = 1; if (auxImports.count(import.importedModule->getName().str())) depth = 0; worklist.emplace_back(import.importedModule, depth); } // Fill depths with BFS over module imports. while (!worklist.empty()) { ModuleDecl *module; uint8_t depth; std::tie(module, depth) = worklist.front(); worklist.pop_front(); if (!seen.insert(module).second) continue; // Insert new module:depth mapping. const clang::Module *CM = module->findUnderlyingClangModule(); if (CM) { depths[CM->getFullModuleName()] = depth; } else { depths[module->getName().str()] = depth; } // Add imports to the worklist. SmallVector<ImportedModule, 16> imports; module->getImportedModules(imports); for (auto &import : imports) { uint8_t next = std::max(depth, uint8_t(depth + 1)); // unsigned wrap // Implicitly imported sub-modules get the same depth as their parent. if (const clang::Module *CMI = import.importedModule->findUnderlyingClangModule()) if (CM && CMI->isSubModuleOf(CM)) next = depth; worklist.emplace_back(import.importedModule, next); } } }
// Font generated by stb_font_inl_generator.c (4/1 bpp) // // Following instructions show how to use the only included font, whatever it is, in // a generic way so you can replace it with any other font by changing the include. // To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_arial_27_latin_ext_*, // and separately install each font. Note that the CREATE function call has a // totally different name; it's just 'stb_font_arial_27_latin_ext'. // /* // Example usage: static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS]; static void init(void) { // optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2 static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH]; STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT); ... create texture ... // for best results rendering 1:1 pixels texels, use nearest-neighbor sampling // if allowed to scale up, use bilerp } // This function positions characters on integer coordinates, and assumes 1:1 texels to pixels // Appropriate if nearest-neighbor sampling is used static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0); glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0); glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1); glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance_int; } glEnd(); } // This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels // Appropriate if bilinear filtering is used static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f); glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance; } glEnd(); } */ #ifndef STB_FONTCHAR__TYPEDEF #define STB_FONTCHAR__TYPEDEF typedef struct { // coordinates if using integer positioning float s0,t0,s1,t1; signed short x0,y0,x1,y1; int advance_int; // coordinates if using floating positioning float s0f,t0f,s1f,t1f; float x0f,y0f,x1f,y1f; float advance; } stb_fontchar; #endif #define STB_FONT_arial_27_latin_ext_BITMAP_WIDTH 512 #define STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT 202 #define STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT_POW2 256 #define STB_FONT_arial_27_latin_ext_FIRST_CHAR 32 #define STB_FONT_arial_27_latin_ext_NUM_CHARS 560 #define STB_FONT_arial_27_latin_ext_LINE_SPACING 18 static unsigned int stb__arial_27_latin_ext_pixels[]={ 0x000aaa00,0x9998804c,0x99999999,0x00d54019,0x3002f640,0x20440155, 0x8804c418,0x3104b809,0x98800cc1,0x06a62a80,0x9806b260,0x99999999, 0x40b80999,0x4c03264b,0x2aa000ac,0x23971002,0x004c4098,0x01bcaa88, 0x2b2e2000,0x2a609300,0xeeee8802,0x4732005e,0x32a004c8,0x200072e3, 0x0f6c4000,0x005dd300,0x801b51d5,0x03db14eb,0x26004eb8,0xa88002ee, 0x262001ac,0x41999999,0x09880019,0x000cccc4,0x2000bfe6,0xfff702fa, 0xffffffff,0x3fee03ff,0x3fe2001f,0x013fa001,0x2a3641f5,0xb09f905f, 0x7c57ea0f,0x43fd800f,0x07fb0ff8,0x2fffff5c,0x7fffffc4,0x42ffffff, 0x3a3ec0fe,0x01dff704,0x805fff30,0xbf53fff8,0x6d402fd8,0xefffffff, 0xff30001c,0x213a09ff,0x4403fff9,0x003ccccc,0x017f5bea,0xdf53fd10, 0x800fa000,0x7ec001fd,0x0bfb6005,0x3f6bfa20,0x007f7003,0xc88037dc, 0x2efffffe,0x3fffff20,0x3e67ffff,0x44fb8007,0x000ffffb,0x6c0013f2, 0x3bbbaa05,0xeeeeeffe,0xf9ff981e,0x07f9000e,0xe8037d40,0x7d42fedf, 0xfb09f905,0x7fc57ea0,0x443fd800,0x207fb0ff,0xfeb9bff8,0x7777fc42, 0x2eeeeeee,0x51f607fc,0x9fb5101f,0xff9ff880,0x42fbee01,0x817ec5fa, 0x9bdfffe8,0x03fffdb9,0x1bbefd80,0x7f440fb8,0x2a201fea,0xf9000a60, 0xf30009fd,0x10001ffd,0xa9a8803f,0xdf100298,0x35351001,0xfff30053, 0x5315100b,0x0bf20053,0x2f3bff60,0xfe83fffd,0xffeeffff,0x001fe66e, 0xf55313ee,0x17e2001f,0x002ef800,0xe88027ec,0x200bf72f,0x07f4003c, 0x81bda880,0x09f90098,0x442620fb,0x3fd800ff,0x43fc8000,0x0ffc46fa, 0x6c0ff800,0x3e604e87,0xfa9ff406,0x885fb00e,0x4404c409,0xfa801dfe, 0x0ffc004f,0x9fb07f10,0x7c403fe6,0x36001b62,0x3ae0005e,0x0f70001e, 0x036c5f10,0xf1000ca8,0xca8036c5,0x22f8800c,0x00f2006d,0x3f201dfb, 0x3fffee1f,0xf30bf25f,0x09f7000f,0xea8007fc,0x7ff0000d,0x004fd800, 0x00000000,0xc8000000,0x1007d84f,0x7fb001ff,0x05fd0000,0x0ffc4199, 0x33ff2a00,0x3f70fb0c,0x0001be20,0x00003fa0,0x98007fd1,0xff1003ff, 0x0000fc80,0x53054466,0x95300262,0x00330015,0x13600262,0x260a88cc, 0x1a981312,0x22330551,0x04c4a60a,0x415446a6,0x94c15119,0x88d4c098, 0x00ffc82a,0xffd97fa2,0x0bf25fff,0xf7000ff3,0x4007fc09,0x20009368, 0x7ec00099,0x5ee54004,0x36a03c88,0x980f2a03,0x17b9503c,0x40f26791, 0x307d84fc,0x003fe259,0x01e54ff6,0x0efb8793,0x001ff880,0x8fffffe4, 0x205f887d,0x203ca86f,0x40fe83c9,0x20e5c3c9,0x2cc983fc,0x01fa2551, 0x199ffb97,0x64c05f88,0x800ff882,0xfff703fd,0x2207dfff,0x3fd800ff, 0x83fedb98,0xfd800ff8,0x7f99fe43,0x6c007fc4,0xf99fe43f,0x4007fc47, 0x99fe43fd,0x802ff87f,0x3fffe4ea,0x30bf25ff,0x9f7000ff,0x44007fc0, 0xb8800b15,0x03c88bdc,0xf88027ec,0x6fbfffff,0x20771b10,0x7f900ff9, 0xffffff88,0x20bf56fb,0x507d84fc,0x003fe2bf,0x07fccff6,0xffe83fc8, 0x00ffc402,0x867fe620,0x203fd07d,0x00ff987f,0x81fd07f9,0x317ec5fa, 0xffff88bf,0x3ee6f9cf,0x3ffffa01,0x402fc87f,0x0ff885fa,0x7443fd80, 0xffcabdff,0x00ff884f,0x7fdc3fd8,0x7c43ffff,0x43fd800f,0x88ff33fc, 0x3fd800ff,0x47f99fe4,0xfd800ff8,0x7f99fe43,0xd0003fcc,0x64bfffff, 0x003fcc2f,0x1ff027dc,0x00bb7600,0xfffffe98,0x27ec06fb,0xb8aefe80, 0x27506fff,0x40bfa049,0x577f40ff,0xf56fffb8,0x3613f20b,0x3e2bf507, 0x23fd800f,0x81ff02fe,0x00dfffe9,0x20003ff1,0xb83ec0ff,0x3a0ff03f, 0xf01ff02f,0xfd8bf50f,0xfe887f22,0x4fefc88b,0xd9980fe6,0x0fe819bf, 0x7c42fd40,0x43fd800f,0xff501efe,0x800ff889,0x4bfea3fd,0x3e21ffec, 0x03fd800f,0x001ff100,0x220007fb,0x3fd800ff,0x00df5000,0x7ffffe40, 0xff30bf25,0x409f7000,0xffb000ff,0x3bfe2005,0x80dffd32,0x5fc804fd, 0x6740dff0,0x217ee01e,0x82fe45fa,0x20bf56ff,0x507d84fc,0x003fe2bf, 0x85fb8ff6,0x46fd45fa,0xf882fffb,0xffffffff,0x40ff85ff,0x209f507d, 0x85fb80fe,0x50ff05fa,0x3a2fd8bf,0x7ec1fec7,0x7402fc2f,0x201fe01f, 0x0ff885fa,0x3ee3fd80,0x1ffd400f,0xfb001ff1,0xbf87fe27,0x03fe25fc, 0x4000ff60,0xfd800ff8,0x1ff10003,0x0007fb00,0x880017f2,0x325fffff, 0x003fcc2f,0x1ff027dc,0x0dfff100,0x7fc1bee0,0x4027ec06,0x0df701fd, 0x7fc400a8,0x3f617ec0,0x3eadf701,0xd909f905,0x7fc57ea0,0x223fd800, 0x217ec0ff,0x3ff620fd,0x7ffffc45,0x85ffffff,0x983ec0ff,0x107f905f, 0x82fd81ff,0x45fa84fa,0xfa97e2fd,0xd81ff706,0x100ff807,0x0bf500df, 0xfb001ff1,0x400bfe27,0x03fe26fb,0x2fccff60,0x443511f3,0x3fd800ff, 0x4b260593,0xfd800ff8,0x32605933,0xb001ff12,0x4c0b267f,0x0009fb2c, 0x25fffe98,0x03fcc2fc,0xff027dc0,0xfd7f7001,0x207fd003,0x27ec06fd, 0xf9807fc0,0xcddca886,0xf88ff602,0xf300ff87,0x7e417ead,0x8afd4004, 0x3fd800ff,0x0ff11fec,0x93fee0ff,0xf0001ff8,0xf107d81f,0x02ffa20f, 0x23fc47fb,0xfa81ffb8,0x3f997ec5,0x3fcc0ff2,0x1fe60374,0xfa805fa8, 0x800ff885,0x00ff53fd,0xff887fcc,0xf73fd800,0xff1035c9,0x2e7fb001, 0x22bf504f,0x3fd800ff,0x57ea09f7,0xfd800ff8,0x3ea09f73,0x0000bf75, 0x2fc97ee6,0x5c003fcc,0x003fe04f,0x013ee7fa,0x37dc07fe,0xf1013f60, 0x2a37c40f,0x5fffffff,0x27dcdf50,0x6f881fe2,0x13f20bf5,0x7fcbf500, 0x542fe801,0x3613ee6f,0x21ff503f,0xf0001ff8,0x3e07d81f,0x85fd100f, 0x513ee6fa,0x17ea01df,0xe87ee5fb,0x88bf501f,0x02fd405f,0xbf500bf7, 0xb001ff10,0x001bee7f,0x03fe23ff,0x1fe4ff60,0x07fc409b,0x4fb9fec0, 0x3fe2bf50,0xf73fd800,0x7c57ea09,0x73fd800f,0x557ea09f,0x2600007f, 0xf30bf25f,0x09f7000f,0x3e6007fc,0xf880ff17,0xb01be607,0x0ff8809f, 0x7fc4df30,0x05ff731b,0x20ff43fe,0xdf300ff8,0x27e417ea,0xfe97ea00, 0xf81ff802,0xf503fd0f,0x447fa07f,0xff0001ff,0xff107d81,0x7c0ffdc0, 0xf983fd0f,0xd8bf503f,0x3e21f92f,0xf50ff207,0x204fb807,0x5fa805fa, 0xd800ff88,0x800bf93f,0x01ff13fe,0x53f27fb0,0x3fe202f8,0xf73fd800, 0x7c57ea09,0x73fd800f,0x457ea09f,0x3fd800ff,0x57ea09f7,0xf8800ff8, 0x64bf301d,0x003fcc2f,0x1ff027dc,0x3fa4fc80,0x403fe202,0x27ec06f9, 0xfa80ffc0,0x7ec17ee6,0xdf17f904,0x7d407fe0,0x3f20bf56,0xbf501884, 0x3e201ff4,0xf8bfc80f,0x07bfee06,0x00ffc4fd,0x3ec0ff80,0xbf506f98, 0x37c5fe40,0xbf507fb0,0x43f72fd8,0x2ff880ff,0xfb003fa2,0x4037c405, 0x0ff885fa,0x9fb3fd80,0xf14fd800,0x27fb001f,0x2c8f55fa,0x36003fe2, 0x2a09f73f,0x001ff15f,0x413ee7fb,0x01ff15fa,0x13ee7fb0,0x07ff2fd4, 0x2601ff90,0xf30bf25f,0x09f7000f,0x3fe007fc,0xff01bee1,0xb01bea03, 0x09f9009f,0x00989bfa,0x3be60bf7,0x09f903fb,0x82fd5bfa,0x507d84fc, 0x0077dcbf,0x3be60ff9,0x7f4c03fb,0x224fc8cf,0xfd0001ff,0x9f507d83, 0xf9807f60,0x3e203fbe,0x7ec5fa86,0x1ff43f32,0x5fd07fe4,0xf803fd00, 0x885fa807,0x3fd800ff,0xfe8009f9,0xb001ff13,0x2e5be27f,0x07fc4df5, 0x4fb9fec0,0x3fe2bf50,0xf73fd800,0x7c57ea09,0x73fd800f,0xa97ea09f, 0x3fe602ff,0xfc97e605,0x4003fcc2,0x03fe04fb,0x7fc46fa8,0x7413f201, 0x027ec06f,0xd9867fc4,0x32a206ff,0x3fa05ffd,0x9ff100fe,0x55bff661, 0xb09f905f,0xf897ea0f,0x2ffb81ef,0x003fbfa0,0x217fffe4,0xb0001ff8, 0x41f63dff,0x01ff03fc,0x400fefe8,0x6c5fa87f,0x7dc9f12f,0x23fff21e, 0xff005fd9,0x401fd801,0x03ff05fa,0x1bea5fd0,0x7fc3ff00,0x3a2fe801, 0x7fd13fcf,0xfe801ff8,0x3ea09f72,0x3a007fe5,0x2a09f72f,0x2007fe5f, 0x209f72fe,0x57fe45fa,0x03bfae20,0x0bf25f98,0xf7000ff3,0xb007fc09, 0x409fb07f,0xfb30cff8,0x04fd80df,0xffdfff50,0xffd98dfb,0x205fefff, 0x7d405ffb,0x6fdffeff,0x13f20bf5,0x22fd41f6,0xfeeffffa,0x7fdc04ff, 0x7ff4c005,0x7ffffc41,0x6fffffff,0x7d9fff4c,0x1fe03fb0,0x2017fee0, 0x6c5fa87f,0xffb1fa2f,0xffff7ffd,0x1be6009f,0xf500bf20,0x200bfa0b, 0x01ff11ff,0x5fd1fe20,0x7443ff00,0x85ffcbff,0x1ff802fe,0x97ee0bf7, 0x1ff802fe,0x97ee0bf7,0x1ff802fe,0x17ee0bf7,0x3f7bfff6,0x7cc01fff, 0xff30bf25,0xffffffff,0x3e04fb89,0x35ff100f,0x01ff7333,0x7ff7ffd4, 0x27ec06fd,0x3bfd9300,0x77fccbf5,0x40bf51bc,0xc9802ff8,0x55fa9dfe, 0x213f20bf,0x30bf507d,0x5dfffffb,0x005ff100,0xf883ff60,0xffffffff, 0x41106fff,0x7c0ff07d,0x02ff8807,0x2fd40fe8,0x43fb8bf6,0xff90ceeb, 0xa804c45b,0x04fa805f,0x3fc82fd4,0xff07fc40,0x917f6009,0x0ff8807f, 0x16ffff44,0x7c403fc8,0x320bf70f,0x100ff25f,0x417ee1ff,0x00ff25fc, 0x17ee1ff1,0xfeb82fe4,0x800cffff,0x30bf25f9,0xffffffff,0x04fb89ff, 0x7fdc03fe,0xffffffff,0x6ff64c03,0x00005fa9,0xfe97ea00,0xf80bf904, 0xafd40007,0x6c13607b,0x980bf507,0x3fc000af,0x2fe814c0,0x2e017c00, 0x3ea1f61c,0x7c01be04,0x001fd007,0x05fb0bf6,0x807fd400,0x1fd004fb, 0xfb82fd40,0x31ff200e,0xffa803ff,0x90077dc1,0x0273a0ff,0x6401df70, 0x741bea7f,0x803bee5f,0x41bea7fc,0x03bee5fe,0x1bea7fc8,0x3ea02ff4, 0x2fcc000a,0x153005f9,0x7fc02a80,0xddddfd00,0x00dfdddd,0x97017ee0, 0x203d9005,0x407fe3fd,0x13ee05fd,0x3f603d90,0x81f40b93,0x809f707d, 0x7dc000f9,0xd81ff804,0x03e6002f,0x43ec5fb0,0x0df100fe,0x36009f70, 0x83fd000f,0xc8003ff8,0x0bf601ff,0xf701fd40,0x07bfa209,0x3ea0bfee, 0x05ff903f,0xf703dfd1,0x003f105f,0x2e07bfa2,0x0bfe62ff,0x7f44bff7, 0x22ffb81e,0x7fdc2ff9,0x207bfa25,0x3fe62ffb,0x202ffdc2,0x4c002efb, 0x200bf25f,0x3f205fea,0x301ff02f,0x1ff880ff,0x7fb01ec8,0xb804fe80, 0x07fdc0ef,0xbff907fb,0x801fd308,0x7fdc0efb,0x82fc0fb0,0x807fb07d, 0xd30802fa,0x1bf7001f,0x30007fd4,0x22fb805f,0x701fd47d,0x7f4c20bf, 0x007fb000,0xfd301ff1,0x2a20159d,0x3e202efd,0x81fa000f,0x3fe203fd, 0x3fffeeff,0x37bffee0,0x2202fffe,0xffeeffff,0x800f703f,0xfeeffff8, 0xdffd83ff,0x445fcfec,0xffeeffff,0xcdffd83f,0x7c45fcfe,0xfffeefff, 0xecdffd83,0xff005fcf,0x325f9800,0x07f6002f,0x1ff06f88,0xfd009f90, 0xb81df709,0x27e400ff,0x6f7ff440,0x7fd41fff,0x6fdfecbd,0x401fffe4, 0xffdeffe8,0x3b3bea1f,0x43f7bf22,0x0fff6c7d,0x1777fe20,0x001fffe4, 0x7fffdfff,0xbbbff000,0x23ec1f30,0x5fff506d,0x00ffff20,0x882eff98, 0x75406ffe,0xeeceffff,0xdf103fff,0xf98009ff,0x00fff6c2,0x3bfffb26, 0xfdb9802c,0x9801bdff,0x2cefffec,0x26001760,0x2cefffec,0x2bbfff20, 0xfec985f8,0x3202ceff,0x5f8aefff,0xefffec98,0x3fff202c,0x2e05f8ae, 0x4c005fdc,0x500bf25f,0x3320df99,0x3ffee4fd,0x801ff80f,0xffe80ffa, 0x001fffde,0x32a2005b,0xb701cdfe,0x3fe3dfff,0x8013bee1,0x1cdfeca8, 0x220beeb8,0xf1f63dfc,0x36a005df,0x9df701cf,0xffec8800,0xfb50002d, 0x7d89b05b,0x7fdc0be6,0x013bee03,0x2a0ffee0,0x95000eff,0x59bdffdb, 0x6fff4c01,0x7c6d8000,0x098003ff,0x0000c000,0x02c8004c,0x40009800, 0x01300009,0x30000980,0x00098001,0x0005efec,0x01eb93a2,0xe80df7dc, 0x3baa0bdf,0x03fd40ee,0xc883ff88,0x001bdffe,0x000001f7,0x00000310, 0x00000000,0x00000000,0x00000000,0x00000020,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x004fd800,0x00001bf2,0x0000005c,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x44033260,0x01310009, 0x91cc8800,0x05990059,0x0015c400,0x80003310,0x80014429,0x2a0003cb, 0x9910004c,0x53060003,0x01333310,0x8000aa88,0x80001cc9,0x50002cc8, 0x00000199,0x9912cb80,0x21991001,0x751003ca,0x99000137,0x33260007, 0x4004cc00,0x1e5c0098,0x00265c00,0x000d40a8,0x73000dd7,0x99980157, 0x00199999,0x13310033,0x20002cc8,0x17ea05fd,0x0002fd40,0x077dd7f2, 0x0007fd40,0x00165744,0x0002ffd8,0x02ec4be6,0x000ffc40,0x20005ff0, 0x2000fffe,0x4eacffe9,0x02ffffa8,0x8001ffcc,0xd80005fc,0xe8002fef, 0xeea8003f,0x9801fa9b,0x004fd8ff,0x07fe37f2,0xfffffd10,0x3f6001bf, 0x7c4002fe,0x3fe206ff,0x203fd805,0x54001ff8,0xe8004fef,0xc8007e65, 0xffb7007f,0x101dffff,0xffffffff,0x3e607dff,0x077fcc07,0x5fe83fea, 0x2a037cc0,0x0bf5005f,0xfd0ff800,0x01fe4003,0x00589d40,0x006fff88, 0x0ffffec0,0x001fe400,0x20009f70,0x006facfc,0x3fff2bb2,0x0aaefa81, 0x001ffcc0,0x40003fd0,0x01ff8dfb,0x20017ea0,0x6fffddf8,0x17fbea00, 0x0bfbfa00,0x97bfff30,0xb801dffd,0x001ff8ef,0x417eeffa,0x6c02fff8, 0x00ff203f,0x7fb1ff30,0xfeffa800,0x03fe4005,0x2f3bffa2,0x442ffecb, 0xcccccdff,0xf984fffe,0x03bfe607,0x0bfd1fe4,0x7d400ca8,0x00bf5005, 0x2c88e4c0,0x0003b800,0x7000595d,0x0003fd7f,0x20002b88,0x25c0003c, 0x325e9800,0x1835003e,0x30017ea0,0x64400013,0x19910002,0x4b800f2a, 0x22193000,0xdec8002a,0x3ed88000,0xd105fd80,0x30cc80bf,0x93aa0079, 0xfff882ed,0x80ff600f,0x2cb8003c,0x88001991,0x000001ba,0xfd80bffa, 0x803fe20f,0x7cc1ffc8,0x01bff307,0x98b2e3b8,0x2a131001,0x0bf5005f, 0x31001980,0x98800cc1,0x85710660,0x4ff40098,0x066004fb,0x22004c40, 0x98001aca,0x10000aca,0x19803595,0x3ea13100,0x2b2a2005,0xaca98001, 0x00cc0000,0x40d65440,0x5654c01c,0x5dd44000,0x65440009,0x00ffc01a, 0x95300ff7,0xba880015,0xdff1009b,0x81fec0bf,0x2009bba8,0x01310019, 0x00157730,0x6445ee54,0x2003fee3,0x03fe23fd,0xf987ff10,0x805ff987, 0x44262098,0x3fd800ff,0x19930bf5,0x5eedd7ea,0x800ff880,0x01ff13fd, 0x3fe27fb0,0x203fd800,0x00ff17f9,0x36003fe2,0xffec883f,0xb802efff, 0x3effffff,0xfffec880,0xff882eff,0xf53fd800,0xffec880b,0xb802efff, 0x3effffff,0x01ff8800,0xfffffd90,0x5c0fee5f,0x3effffff,0x7ffff440, 0x32200dff,0x2efffffe,0x6c00ff88,0xffff700c,0xe8807dff,0x0dffffff, 0x17fcffc4,0x7f443fd8,0x40dfffff,0xfd800ff8,0xffffb703,0x7c401dff, 0x6fbfffff,0x7d400ffa,0x2003fe24,0x23fcc4fd,0xfb005ff9,0xff89fec7, 0xf53fd800,0x2a3ff98b,0xfffffeef,0x4007fc42,0x01ff13fd,0x3fe27fb0, 0x203fd800,0x00bfa4fc,0x36003fe2,0xceffd83f,0x103fffdb,0xf957bffd, 0xffd809ff,0x3fffdbce,0x6c007fc4,0xd80bf53f,0xffdbceff,0xbffd103f, 0x09fff957,0x801ff880,0xdbabdffd,0xe884feff,0xffcabdff,0xbfff304f, 0x01dffd97,0x36f3bff6,0x5fe83fff,0xbffd1000,0x09fff957,0x32f7ffe6, 0x3e20effe,0xfb01ff97,0x5efffcc7,0x220effec,0x3fd800ff,0x5e77ff44, 0xd02ffecb,0xfff715df,0x00007fcd,0xff001ff1,0x3e67f985,0x8ff6005f, 0x01ff13fd,0x97ea7fb0,0x7fd42ff9,0x1ffc88cf,0x36003fe2,0x001ff13f, 0x03fe27fb,0xff80ff60,0x2201bee1,0x3fd800ff,0xfc8077ec,0x01efe81f, 0x3f609ff5,0x43ff900e,0xfd800ff8,0x7ec0bf53,0x03ff900e,0x3ea03dfd, 0x3fe2004f,0x80f7ec01,0xdfd07ffa,0x213fea03,0xbfd105fd,0x3201dfb0, 0x7ffd41ff,0xdfd000ac,0x213fea03,0xbfd105fd,0x0bfd3fc4,0x82fec7fb, 0x3fe25fe8,0x743fd800,0x3ff602ff,0xff82fe40,0x8000ff36,0x7ec00ff8, 0xff37f986,0x23fd800b,0x01ff13fd,0x57ea7fb0,0xffa82ff9,0x3e26fb82, 0x13fd800f,0x7fb001ff,0x36003fe2,0x88df503f,0x7fc401ff,0x323fd800, 0x3fa200ff,0x2007fdc5,0x7fe43ffa,0x897fa200,0x3fd800ff,0x3ff20bf5, 0x717fa200,0xffa801ff,0x03ff1003,0x3e6037e4,0x07fdc2ff,0xff0ffea0, 0x323fdc03,0x3fa200ff,0xfffffa85,0x1ff701ce,0x7c3ffa80,0x89fee01f, 0xb0bfe67f,0x700ffc7f,0x007fc4ff,0x1ff71fec,0xfd87fb00,0x3eedf701, 0x7fc40006,0xfedccccd,0x9ff983ff,0x2000ffff,0x44ff63fd,0x3fd800ff, 0x05ff3bf5,0x27f81bea,0xfd800ff8,0xb001ff13,0x003fe27f,0x1fec0ff6, 0x3e2027ec,0x23fd800f,0x4ea802ff,0x5c00bfe2,0x4017fc6f,0x03fe24ea, 0x2fd4ff60,0xea802ff8,0x400bfe24,0xff1006fb,0x1017fc03,0x7c4dfbdf, 0x4df7002f,0x66c00ff8,0x2a00bfe0,0xffb7104e,0xff889fff,0x44df7002, 0x866c00ff,0x07fe47f8,0x03fe27fb,0x3fe219b0,0x3a3fd800,0x89f5003f, 0x2df300ff,0x3bba05fc,0xff11eeee,0xffffffff,0x3ffe603b,0x2005fecf, 0x44ff63fd,0x3fd800ff,0x01dffdf5,0x1fe817ea,0xfb001ff1,0x2003fe27, 0x01ff13fd,0xff107fb0,0xff733335,0x007fc401,0x07f99fec,0x801fea00, 0x0ff30ff9,0x007fc400,0x85fa9fec,0x2a0007f9,0x3fe6007f,0x01ff8800, 0x77440df3,0xff51ffa8,0xd07fcc00,0x7f9800bf,0xd7300000,0x1fea1dff, 0x3a0ff980,0x3fc4005f,0x47fb2ff4,0x7c4005fe,0x23fd800f,0x220000ff, 0x5dbe207f,0x3fffe06f,0x7ff11fff,0x07ff9555,0xf34fff98,0x8ff6007f, 0x01ff13fd,0x3fea7fb0,0x9f504fef,0xff897ec0,0xf13fd800,0x27fb001f, 0xfd800ff8,0xfffffb83,0x203fffff,0xfd800ff8,0x4000df53,0x7fc006fb, 0x4000df51,0xfd800ff8,0xdf50bf53,0x037dc000,0x22007fe0,0x0bf701ff, 0x2ff88ff4,0xff800df7,0x2b3ffea1,0x0037d400,0x97fdc000,0x7fc006fb, 0x2b3ffea1,0x4c3fc400,0x547fb2ff,0x400acfff,0xfd800ff8,0x8000ff33, 0xdf300ff8,0x4cc03fe6,0xf11ff999,0x09ff301f,0x3ee27fcc,0x23fd801f, 0x01ff13fd,0x3fea7fb0,0xfa81ff99,0x7c47f604,0x13fd800f,0x7fb001ff, 0x36003fe2,0xeeefe83f,0x06feeeee,0x36003fe2,0x000bf93f,0x3a002fe4, 0x000bf93f,0x6c007fc4,0xf90bf53f,0x2fe4000b,0x200ffa00,0x9f901ff8, 0x7fd07f60,0xfd0017f2,0xfffffa87,0x05fc81ce,0x20072e00,0x00bf94fc, 0x7fd43fe8,0x881cefff,0xb1ff907f,0xffffa87f,0xff881cef,0xf73fd800, 0x3ff0000d,0x1ff9bea0,0x7c47fe00,0x07ff500f,0x77ec1fe6,0xfb1fec00, 0x2003fe27,0x5cbf53fd,0x02fd40ef,0x03fe21fd,0x7fc4ff60,0xf13fd800, 0x87fb001f,0x7fc407f9,0x001ff101,0x013f67fb,0x4004fd80,0x009fb4fd, 0x4007fc40,0xb0bf53fd,0x7ec0009f,0x027ec004,0xfe80ffc4,0xfd82fc83, 0xd8009fb4,0xffdb884f,0x27ec4fff,0x009f9000,0x013f6bf7,0xb7109fb0, 0x889fffff,0x377fa07f,0xffdb883f,0x7fc44fff,0xf93fd800,0x7777740b, 0x413f21ee,0x017f66fe,0x1ff11ff8,0x4c0ffe40,0x0bff107f,0x4ff63fd8, 0xfd800ff8,0x4fe8bf53,0x7cc07fd4,0x2003fe26,0x01ff13fd,0x3fe27fb0, 0x643fd800,0x04fe804f,0xfb001ff1,0x80017ee7,0x7f4004fc,0x4000bf73, 0xfd800ff8,0xbf70bf53,0x027e4000,0x2200ffa0,0x89fb01ff,0x25fd03fc, 0x7f4004fc,0xffeb9803,0x000bf70e,0x3600ffcc,0x8009f93f,0xeb9803fe, 0x0ff10eff,0x01ffffcc,0x877ff5cc,0xfd800ff8,0x7fc0df73,0x221fffff, 0xffb30cff,0x402ffd4d,0x1ff11ff9,0x4c37f440,0x0ffea07f,0x8ff63fd8, 0x2fe801ff,0x2ff98bf5,0xe9837fea,0x400ffc3f,0x007fe2fe,0x01ff8bfa, 0x0ffc2fe8,0xf807fd40,0x52fe801f,0x7d4000ff,0xa8ffc006,0x7fc0007f, 0xf52fe801,0x000ff50b,0x3e0037d4,0x1ff8801f,0x27dcbf90,0x1bea1ff0, 0x8003ff00,0x0ff52ffb,0x0bffe800,0xfa87fec4,0x00ffc006,0x7c4bfee0, 0x1fffe407,0xf8bfee00,0x32fe801f,0x266601ff,0x7d41ff99,0x6fdffeff, 0x1056ffe4,0x223fffb3,0x7fd400ff,0x3603fcc3,0x47fb01ff,0x00bfa3fd, 0x42fd47fe,0xfff50efc,0xd09ffb9f,0x43ff005f,0x1ff802fe,0x3fe00bfa, 0x4401fea1,0x05fd03ff,0x3fe23ff0,0x11df8800,0x3e2001ff,0x2003fe27, 0x0bfa1df8,0x2fd47fe0,0x44007fc4,0x01ff11df,0x2021fe20,0xff500ff8, 0x7f9817ea,0x44003fe2,0x20072e7f,0x01ff14fc,0x6c43bf10,0xfffeffff, 0x003fe21e,0x03973fc4,0x1fe29f90,0x65cfffa0,0x3a4fc801,0x21ff802f, 0x3fe001ff,0x9dfec981,0xfffb85fa,0xcffffeef,0x2003fe20,0x1fe60ffd, 0x360dff10,0xfc8ff63f,0xa87fc403,0x2a9fd05f,0x3efffadf,0xf8807f90, 0x100ff20f,0x01fe41ff,0x4fd83fe2,0x641bf200,0x07fc403f,0xff9007ff, 0xd8027fc1,0x401ffc5f,0x0ff20ffc,0x3ea1ff10,0x9007ff05,0x027fc1ff, 0x1fe65fd8,0x9fd01fe2,0x45fd80bf,0xbfb004ff,0x7dc027e4,0x3200ffe5, 0xffeb80ff,0xff80ceff,0x64bfb004,0x15fb804f,0x7ff300ff,0x3ee013f2, 0xf100ff25,0x002fec1f,0x7d4003ff,0xffdb7105,0xff103bdf,0x4bff1001, 0xff9807f9,0x3f63fd84,0xc803bee3,0xa80d407f,0xf700225f,0x23fe401d, 0x3f200efb,0x90077dc7,0xd90000ff,0x90077dc0,0x02ffa8ff,0xff317fe6, 0x41ffa803,0x3e602ffa,0x0077dc5f,0x82fd4ff9,0x3e602ffa,0x00ffcc5f, 0xff887fea,0x2a037cc1,0x3ee00eff,0x00ffcc1f,0xff987fea,0xf51fec01, 0x2ffcc05f,0x30033e20,0xffa803ff,0xb007fe61,0x0153007f,0x3600ffcc, 0x803bee3f,0x2ffd47fc,0xd90ffcc0,0x400ff603,0x54c0006e,0x00d40000, 0x1fec7fb0,0xf703dfd1,0x1ffe805f,0x22002fd4,0xffb81efe,0x40f7f442, 0x7f442ffb,0x02ffb81e,0x2204d800,0xffb81efe,0x20affc82,0xa80efeb8, 0x5ff903ff,0x882bff20,0x7440efeb,0x2ffb81ef,0xffc817ea,0x3bfae20a, 0x903ffa80,0x19fd05ff,0xf1017fa2,0xffb107ff,0x40ffea03,0xffe82ffc, 0x07fec40b,0xb882bff2,0x74c00efe,0x3ffa804f,0xfd05ff90,0xffd8817f, 0x03ffc800,0xb102fffa,0x77f441ff,0xc82ffb81,0x2620adff,0x3ee1fffd, 0x007fdc0e,0x0000cfe8,0x40007ff9,0xfd801ffe,0xff10ff63,0x7fffddff, 0xf513ea00,0xfff1000b,0x07fffddf,0x3bbfffe2,0xff103fff,0x7fffddff, 0x01fa0000,0xfddffff1,0x7fec07ff,0x1ffffdef,0x37bffee0,0x6c02fffe, 0xfffdefff,0xffff101f,0xa87fffdd,0x7ffec05f,0x01ffffde,0x3b7bffee, 0xff502fff,0x401fffdf,0xefffdfe8,0x401fffed,0xfedefffb,0xffb102ff, 0x3dfffdff,0x37bfff60,0x2001ffff,0xffb801fd,0x2fffedef,0xdffffb10, 0x4003dfff,0x3f6207f8,0xefffefff,0xeffff881,0x2e03fffe,0xffeeffff, 0x7f440cff,0x01fffdef,0x0001fdc0,0xa8000ff1,0x23fd804f,0xfec983fd, 0x4402ceff,0x7d42fecc,0xfd930005,0x98059dff,0x2cefffec,0x7fff64c0, 0x200002ce,0x981fdffb,0x2cefffec,0xffffeb80,0xdb9800cf,0x001bdfff, 0x9fffffd7,0xffec9801,0xffa82cef,0xffd702ff,0x30019fff,0x37bfffb7, 0xdffffa80,0xd98fec01,0x01bdffff,0xbfffb730,0xffd70037,0xb8019dff, 0x0cfffffe,0x06feca80,0x3fff6e60,0xfeb801bd,0x000cefff,0x700bfb97, 0x19dffffd,0x7fff64c0,0xdb8802ce,0x01defffe,0x337fb2a2,0xff993001, 0xfb970003,0xd991000b,0x47fb005f,0x009803fd,0x20b3fa60,0x300004ea, 0x004c0001,0x00001300,0x801eedc0,0x33100009,0x00180001,0x0004cc40, 0xee980130,0x4cc401ee,0x000c0000,0x06600188,0x180000c4,0x004c4000, 0x0004cc40,0x0002f7b2,0x4c400018,0xbdfd8000,0x004c4000,0x40000980, 0x00000018,0x001677d4,0x000bdfd8,0x002dfe98,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x23991000,0xc88002cc,0x43b8001c,0x19910049, 0x66400f26,0x40009931,0x00002cc8,0x4000e644,0x0ccccccc,0x53000000, 0x00355555,0x0000cca8,0x965c0000,0x64c004c8,0x6540000c,0x00000004, 0x0001e5c0,0x64400599,0x3320002c,0x0b322002,0x00166400,0x70016644, 0x00332259,0x59901554,0xe99f5c00,0xcc880005,0x66664001,0x1d800ccc, 0x2e03cc80,0x001ff56f,0x001fffb0,0x09d32fa8,0x7f477dc0,0xd1df5001, 0x7ec0005f,0x200002fe,0xff0006fc,0x003fffff,0x6c006fd8,0x04ffffff, 0x017fbe60,0x456fe440,0x3fe6006d,0xd8002fd8,0x3e20005f,0xea80002f, 0x3e60000d,0xdf50001f,0x07fb8001,0x001ff500,0x0017f7ec,0x20003fea, 0x3002fefd,0x007fb1ff,0x7d40bfe2,0x53f2000f,0xc80007f9,0xfff8006f, 0x2a01ffff,0xf500aefd,0xd87f401f,0xdfb8001f,0x6c000ef9,0x4000efff, 0x4003fefd,0x0003fefc,0x07fe37ee,0x03fe2000,0x4ccccc00,0x6fd80019, 0x55554c00,0xff1001aa,0x70009f93,0x07fffd9f,0x04fffb80,0x001fd100, 0x00013ee0,0x00024da2,0x740005fb,0x7f90001f,0x003fd000,0x07fc6fdc, 0x0003fd00,0x01ff1bf7,0x017fbee0,0x3fa04fc8,0x89654001,0x7c40004c, 0x9998000f,0xff501999,0xb05fffff,0x8964405f,0xee88002c,0x10007d70, 0x36200035,0x9db0004e,0x86644000,0x980003ca,0x54c0001c,0x950000ac, 0x20033007,0x8f2a0098,0x1dc000cc,0x2e000373,0x6440004c,0x00970002, 0x02c56200,0x40007900,0x640002c8,0x01644003,0x32a19910,0x00591003, 0x32a19910,0x017b2003,0x16440bb0,0x31001980,0x01c98001,0x2a235300, 0xf8cff882,0x3221ffca,0x15953002,0x55dcc000,0xaca98000,0x4cccc400, 0x99999999,0x4ccccc41,0x20999999,0x04cc0098,0x22002620,0xff700019, 0x407dffff,0x99999998,0x3e209999,0x03fd800f,0x80001988,0x26600198, 0x80098800,0x26600198,0x01999999,0x0176ec00,0x98800998,0x44003310, 0x26666609,0x09999999,0x26666666,0x26099999,0x99999999,0x26620999, 0x99999999,0x80066209,0x26666098,0x10019999,0x40033013,0xfd800ff8, 0x33331003,0x33333333,0xf33fc813,0x8fcdf70f,0x004c44fe,0xdffffff7, 0x3ff6e007,0x800effff,0xeffffffb,0xfffff703,0xffffffff,0x7ffffdc3, 0x26ffffff,0x3fe206fb,0x00bfe00f,0x8800bff6,0xfcabdffe,0xfff704ff, 0xffffffff,0x4007fc4d,0xffd803fd,0x7fec0002,0x05ff8802,0xfd803fd8, 0xfff8802f,0xefffffff,0x2ffd8003,0x805ff880,0x05ff53fd,0x3e25ff30, 0xffffffff,0xfff12fff,0xffffffff,0x3fffe25f,0xffffffff,0x3ffffee2, 0x26ffffff,0xf9802ffa,0xfffff12f,0x07dfffff,0x1fe627dc,0x800ff880, 0xff8803fd,0xffffffff,0x7e43ffff,0x7f90ff33,0x6c2c98fc,0xdffe883f, 0x04fffcab,0x2f3bffa2,0x102ffecb,0xf957bffd,0xddd509ff,0xddddffdd, 0x777543dd,0xffeeeeee,0xfa81fe66,0x0ff302ff,0x00dfff10,0xfa80f7f4, 0xeeeea84f,0x6ffeeeee,0x36003fe2,0x7ffc403f,0x3fe20006,0xfff8806f, 0x201fec02,0x8806fff8,0xcccccdff,0x2004fffe,0x8806fff8,0x7ec02fff, 0xd003ff63,0x777fc4bf,0xeeeeeeee,0xddddff12,0x25dddddd,0xeeeeeff8, 0x2a2eeeee,0xeeeeeeee,0x7fec6ffe,0xf12ff400,0xd99999bf,0x3ee09fff, 0x1003fcc4,0x7fb001ff,0xfddff700,0xdddddddf,0x7e40005d,0x7fb007e4, 0x2a03dfd0,0x5ffd04ff,0x7407fec0,0x9ff501ef,0x0013f600,0x3e0ffdc0, 0x9f9fb01f,0x2e017ee0,0xb801febf,0x7fd400ff,0x1ffb8003,0x36003fe2, 0x75fdc03f,0x7f70001f,0xff8803fd,0x0ff600ff,0x03fd7f70,0x2200ff88, 0xf7001ffc,0xf8803fd7,0x3f600fff,0xc813fe23,0x07fe20ff,0x003ff100, 0x0001ff88,0x883ff700,0x3ff204ff,0x8803fe20,0x4fb81ffc,0xf1003fcc, 0x07fb001f,0x1bee7ff0,0xdf500000,0x7fb007e1,0x5400ffb8,0x07fdc3ff, 0x3ee1fec0,0x1ffd400f,0x00027ec0,0x7ec1ffd4,0x0df1ff03,0x3fa00ff6, 0x7c404fb9,0x0df7002f,0x443ffa80,0x3fd800ff,0x27dcff40,0xfb9fe800, 0x7f7fc404,0xd00ff605,0x8809f73f,0x7fc400ff,0xf73fd003,0xfeff8809, 0xf50ff605,0x83ff305f,0x44001ff8,0x7c4001ff,0xa800001f,0x5ff503ff, 0xf883ff30,0x1ffc400f,0x1fe627dc,0x800ff880,0x3fdc03fd,0x64c00df7, 0x74459302,0x6c01fbff,0x00bfe23f,0x0ffa37dc,0xff127d40,0x01bee005, 0x300013f6,0x17ee09ff,0x407f57e6,0xbfcc01ff,0x3fd407f8,0x001ff300, 0x3e213fe6,0x03fd800f,0x03fc5fe6,0x7f8bfcc0,0x7fcffc40,0x4c07fb02, 0x880ff17f,0x4fd800ff,0xff17f980,0xff9ff880,0xfb07fb02,0x884fe81d, 0x7c4001ff,0x7fc4001f,0x7cc00001,0x077ec04f,0x3fe213fa,0xb84fd800, 0x003fcc4f,0xfb001ff1,0x2e3ff807,0x13ee006f,0x3fa22fd4,0xfb01ceff, 0x3003fd47,0x007fc1ff,0x400ff500,0x7ec00ff9,0x3fa20004,0x2e1fe206, 0xf887f92f,0x3a4fc807,0x01bee02f,0xd1003ff0,0x03fe20df,0xfc80ff60, 0x9000bfa4,0x1017f49f,0x203ff2ff,0x93f203fd,0x3fe202fe,0x802ff800, 0x80bfa4fc,0x01ff97f8,0x9ff107fb,0xff8837dc,0x0ffc4001,0x007fe200, 0x06fe8800,0x3ee4ff88,0x001ff106,0x89f705ff,0x3e2007f9,0x03fd800f, 0x0df71fee,0xfa827dc0,0xffff9305,0x7dc7fb09,0x98ffc006,0x7dc0007f, 0x00ffc006,0xd80013f6,0x0ff400ff,0x22fd43fa,0x1ff805fa,0x5fc81bee, 0x401ff400,0xff100ffd,0x407fb001,0x01bee1ff,0x37dc3ff0,0x2ff4ff10, 0x3ff01fec,0xff1037dc,0x006fd801,0x037dc3ff,0x42ff4ff1,0x3ff503fd, 0x3e203ff1,0x7fc4001f,0x0ffc4001,0x1ffb0000,0x227fea00,0x1ff101ff, 0xf706fd80,0x2007f989,0xfd800ff8,0xf70ffa03,0x827dc00d,0x6dfc05fa, 0x91fec3ff,0x3fe800bf,0xc8000df7,0x1ff4005f,0x40013f60,0xfc801ffc, 0x8ff1be22,0x37d402fc,0x7ec07fe2,0x027ec004,0xf8807ff2,0x03fd800f, 0x1ff88df5,0xf88df500,0x4cff101f,0x81fec2ff,0x0ffc46fa,0xcccdff88, 0x03fffedc,0x7fc46fa8,0x7ccff101,0xb01fec2f,0x4409fbdf,0xffffffff, 0x3fe25fff,0xffffffff,0x3fffe25f,0x5fffffff,0x001ffc80,0x027ef7ec, 0x9999bff1,0x207fffdb,0x03fcc4fb,0xb001ff10,0x03fea07f,0xfffffff7, 0x827dcdff,0xb8fc05fa,0xfb1fec7f,0x94fd8009,0x777740bf,0x09fb1eee, 0x6c04fd80,0xffa8004f,0x549f5002,0xfd0fec4f,0xd83fd801,0x009f904f, 0x3ea03fe8,0x07fc402f,0xfd81fec0,0xb004fd83,0x209fb07f,0x07fe47f8, 0x0ff607fb,0x7fc413f6,0xffffffff,0x07fb001d,0x1fe209fb,0x1fec1ff9, 0x80dfff10,0xfffffff8,0x3e25ffff,0xffffffff,0x3ffe25ff,0xffffffff, 0x017fd405,0x037ffc40,0x3fffffe2,0x201dffff,0x03fcc4fb,0xb001ff10, 0x20ffa07f,0xfffffffb,0x413ee6ff,0x47e045fa,0x8ff61ff8,0x7f4004fc, 0x7fc0df73,0xf91fffff,0x03fe8009,0x260027ec,0x3e2004ff,0x7f707f26, 0xff101be2,0xff733335,0x800df501,0x9ff301ff,0x2007fe00,0xaff882fe, 0x0ffb9999,0x4cd7fc40,0x880ffb99,0x365fe87f,0x9aff883f,0x80ffb999, 0xcaaabff8,0x3e2003ff,0xfb9999af,0xe87f880f,0x700ff65f,0xff8803ff, 0x0ffc4001,0x007fe200,0x009ff300,0x200ffdc0,0xcaaabff8,0x4fb803ff, 0x3e003fcc,0x82fe801f,0x6fb80ffa,0x5413ee00,0x1f87fa5f,0x23fd87fe, 0x7fc006fa,0x2601ff31,0x51ff9999,0x1ff800df,0x10027ec0,0xfd000bfd, 0x57e61fe1,0x7fdc04fa,0xffffffff,0x000ff883,0x3fa20ff1,0x00bfa005, 0x3fee07fe,0xffffffff,0x7fffdc03,0x83ffffff,0x2ff987f8,0xfff707fb, 0x7fffffff,0xf301ff10,0x3fee009f,0xffffffff,0xf987f883,0x9807fb2f, 0x1ff8807f,0x00ffc400,0x0007fe20,0x0005fe88,0x7c403fcc,0x04ff980f, 0x1fe627dc,0xf005fd00,0xffffd03f,0x00dfffff,0x5fb82fdc,0xf51f93f6, 0x3e23fd8f,0x8ff1000f,0x3fe001ff,0x2001ff11,0x4fd807f8,0x003bf600, 0x17e6bf20,0x401fcbfc,0xeeeeeefe,0x9ff06fee,0x6c17f600,0x3f2000ef, 0x407fc403,0xeeeeeefe,0x7f406fee,0xeeeeeeee,0x907f886f,0xd07fb1ff, 0xdddddddf,0x1ff10dfd,0x200ffea0,0xeeeeeefe,0x7f886fee,0x7fb1ff90, 0x8807f980,0x7c4001ff,0x7fc4001f,0x3bf60001,0x3fcc0000,0xa807fc40, 0x13ee03ff,0xfc800ff3,0x207fc403,0xfffffffa,0x2e006fff,0x5cbf905f, 0xfb13f2ff,0x7fc3fd8b,0xd8bfb004,0x87fe005f,0xbfb004ff,0x2009fb00, 0x50001ffc,0x3607f79f,0x7cc07e8f,0x40ffc407,0x7d401ff9,0x01ffc81f, 0x90077dc0,0x80ff30ff,0xff301ff8,0x441ff880,0x377fa07f,0x203fcc3f, 0x7fc41ff8,0x807ff200,0x7fc407f9,0xfd03fc41,0xf9807fbb,0x01ff8807, 0x000ffc40,0x40007fe2,0x80001ffc,0xff8807f9,0x407ff200,0x03fcc4fb, 0xc803bee0,0x204fd87f,0x3ea006fb,0xfd8bfd06,0x0fffdfdf,0x3fe61fec, 0x20ffd401,0xf9805ffa,0x007fe61f,0xfb003ff5,0x05ff5009,0x7eefc400, 0x0bf7f501,0xfe804fc8,0x207ff504,0xffa82ffc,0xefe88002,0xc82ffb81, 0x04fe804f,0x9fd009f9,0x3e607f88,0x27e43fff,0x3e227f40,0x1bfa200f, 0xfe804fc8,0xf303fc44,0xf9807fff,0x01ff8807,0x000ffc40,0x20007fe2, 0x00002ffa,0xff100ff3,0x837f4401,0x03fcc4fb,0x207bfa20,0x7fcc2ffb, 0x801bee00,0x7fdc2ff9,0xfffffc85,0xa83fd80d,0x5ff903ff,0x82b7ff20, 0x41fffd98,0xff903ffa,0x013f6005,0x00007ff3,0x7c40dffd,0x0ffc03fe, 0xb807fd40,0xffedefff,0x03ff982f,0x3fffe200,0xf03fffee,0x1ff5003f, 0xf5003ff0,0x203fc41f,0x7fc3fffc,0x20ffa801,0x7d400ff8,0x003ff03f, 0x3fc41ff5,0x00ffff20,0xff100ff3,0x1ff88003,0x00ffc400,0x000ffe60, 0x8807f980,0x7fd400ff,0x7cc4fb83,0xfff88007,0x83fffeef,0x37dc05fd, 0x337ff600,0x2605fcfe,0x0ff600bf,0x76f7ffdc,0x7dc02fff,0xfffeefff, 0xfff700cf,0x05fffdbd,0x2e027ec0,0xffffffff,0x700fffff,0xffe809ff, 0x401fea01,0x2e603ff8,0x01bdfffd,0xfffffff7,0x01ffffff,0x9dfffd93, 0x401fea05,0x3fd43ff8,0x223ff880,0x3ffe807f,0x7c401fea,0x003fe23f, 0xff503ff6,0x88ffe200,0x3ffe807f,0x4403fcc0,0xffffffff,0xff16ffff, 0xffffffff,0x3ffe2dff,0xffffffff,0xfffff76f,0xffffffff,0x807f9801, 0xfd800ff8,0x2627dc0f,0xffffffff,0xfec984ff,0xf982ceff,0x7ffdc01f, 0x6fffffff,0x4577ffe4,0x200fc05f,0x36e603fd,0x001bdfff,0xdfffdb71, 0xfb73003b,0x80037bff,0x7fdc04fd,0xffffffff,0xff300fff,0x407fc805, 0x3f2004fd,0x5c006006,0xffffffff,0x800fffff,0x04fd8009,0x9fb1bf20, 0xf137e400,0x47ff300f,0x3f2004fd,0x2003fe26,0x27ec5ff8,0x7c4df900, 0x03ff9807,0x7c403fcc,0xffffffff,0xfff16fff,0xffffffff,0x3fffe2df, 0xffffffff,0xffffff76,0x1fffffff,0x8807f980,0xff8800ff,0x3e627dc5, 0xffffffff,0x4009804f,0xffb805fd,0xffffffff,0x50001306,0x003fd801, 0x0c400006,0x0000c000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x0e647950,0x00a82880,0x4ea8f6c0,0x05707200, 0x1cc8b2a0,0x32e4c980,0x84409802,0x07930cc8,0x400bba20,0x00003cc8, 0x40144130,0x00001cc9,0x401e5c00,0x407b65e9,0x227d71ed,0x01999999, 0x0ee8a754,0x75c3b600,0x55553003,0x55400355,0x000aaaaa,0x20003751, 0x2620aca9,0x19999999,0x2000dcc0,0x55401808,0x55402aa1,0x51002aa1, 0x18800377,0x40590018,0x202bca98,0x2a60cc2a,0x155000ac,0x3e202aa2, 0x2005fb9f,0x003ee3f8,0x17ee3fd0,0x3f50ed80,0x2e7fe200,0x2ffa005f, 0x8d9006fa,0x3a37f24e,0x7ff1001f,0x0bfbf600,0xd1037ec0,0x80dd7bff, 0x000fffe8,0xbb15bf91,0x09fdf700,0x07fa6fa8,0x54fc8ffc,0x0fffffff, 0x1ff15fb8,0xfc8ffc00,0xffffb004,0x3e2009ff,0x01ffffff,0x3ffffb22, 0xff9803df,0xffb4ffff,0x0fffffff,0x07bfffaa,0x0d907d40,0x5fc8efa8, 0x3ee3fe60,0x3fff6205,0x9801dfff,0x3003ee1f,0x3fff205f,0x7c43ffff, 0x3627fe0f,0x01efffff,0x04fcb7dc,0x001bfbe6,0x013fffee,0x164c32e0, 0xbffff300,0xefef9800,0x3bfe2000,0xbdf3000f,0xfefd81ff,0x0bba2003, 0x3fe37ee0,0x206fd801,0x2ffebafb,0x77cdfec0,0xfecfb800,0x7fcc02ff, 0x32602fe8,0x664032e3,0x33265950,0x5404cccc,0x8009912c,0x005950cc, 0x2aaaaaa6,0x26666001,0x3fa20199,0xfffdbbdf,0x33bfe603,0xefdcfeba, 0x06eeeeee,0x0df937ff,0x1ff6ff40,0x037efe40,0x8077efdc,0xcbcefff9, 0xfd801ffe,0xfc803fee,0x5efff4c0,0x10dfffca,0x7e7fc1ff,0xfffcabdf, 0x2fefec00,0x0006f5c0,0x0000bb88,0x0002b2a6,0xb800054c,0xe98001ee, 0x6dc4001e,0x04ed880b,0x0055dcc0,0x0f2a1991,0x2980f2e0,0x93260044, 0x23b802cb,0x1cb801b9,0x00cc4993,0x09881310,0x10002620,0x4ccc0033, 0x99999999,0x01988009,0x26666660,0x40999999,0xff500efd,0x20dff107, 0x4002fffd,0x00ff44fb,0x40037b50,0xfb000ffe,0x077fc03f,0xa800efb8, 0x0dd001cc,0x3e603dfd,0xfff1e26f,0x0dfd101d,0x3301dfd0,0x33333333, 0x33100133,0x3ffee000,0x2603efff,0x99999999,0x98800999,0x26666001, 0x44001999,0x00262009,0x3fffff6e,0x04c400ef,0x99999998,0x88099999, 0x20033009,0x00266098,0x004c4262,0x9802ffa8,0x01fec2ff,0xfd8007fb, 0xfff8802f,0xffffffff,0x2ffd802f,0xfffff880,0x2fffffff,0x3ee01bf6, 0x007fdc2f,0xd8005fff,0x0017ec3f,0x00000000,0xc805ff70,0x8800006f, 0x007fdc4f,0x22dcffea,0x3e200fff,0x3e20003f,0xffffffff,0xfd802fff, 0x3fa2002f,0xfffcabdf,0xfffff884,0x2fffffff,0x802ffd80,0xfffffff8, 0xfd801dff,0x880ff603,0xcbbceffe,0x3f602ffe,0xfffff883,0x2fffffff, 0x3ff03fd8,0x3e27fb00,0x53fd805f,0x7fec00bf,0x6c2ff400,0x00ff603f, 0x806fff88,0xeeeeeff8,0x402eeeee,0x8806fff8,0xeeeeeeff,0xff12eeee, 0xd17f6003,0x2ffb807f,0x8877dc00,0x3b2a007f,0xeca800bc,0x02c980bc, 0x02f5c593,0x32a02ff8,0x7d400bdd,0x400ffe21,0xff85bffb,0x205fd804, 0x7c41bdb9,0xeeeeeeef,0x7c402eee,0x3fa006ff,0x89ff501e,0xeeeeeff8, 0x402eeeee,0x8806fff8,0xfeeeeeff,0x7ec04fff,0xe80ff603,0x3ff602ff, 0xf107fb00,0xdddddddf,0x7fb05ddd,0x36007fe0,0x05fff13f,0x0bf53fd8, 0x9027fc40,0x07fb01ff,0xf7001fec,0xf8803fd7,0xf700001f,0xf8803fd7, 0x37d4001f,0x7c4ff500,0x17fcc01f,0x2b7fa200,0xfe9803ff,0x302fffff, 0x5ffffffd,0xbf504fb8,0x41fe4000,0xffffffd8,0xff51f602,0x827fc400, 0x7fa802ff,0xffffffb0,0x0007fe21,0x0ff5fdc0,0x2007fdc0,0x3fe23ffa, 0x7f700001,0xff8803fd,0x80bff600,0x0ff603fd,0x6c007fdc,0x107fb03f, 0x6c0003ff,0x003ff03f,0x3ffe27fb,0x54ff600f,0x7fd4005f,0xb01ff982, 0x01fec07f,0x09f73fd0,0x0001ff88,0x09f73fd0,0x4001ff88,0x3e2004fb, 0x801ff30f,0x98002ff8,0xd002ffff,0xffb517df,0x517dfd03,0x27dc3ffb, 0x20005fa8,0xbefe85fb,0xf01ffd98,0x4006fb8b,0x05ff03ff,0xfd81ff30, 0x15fc98be,0x200003ff,0x404fb9fe,0xf7002ff8,0x000ffc4d,0x4fb9fe80, 0x2007fc40,0x7fb00ffd,0xfe81fec0,0x209f5003,0x1ff883fd,0x40ff6000, 0x3fd801ff,0x40bfdff1,0x00bf53fd,0xfe81dfb0,0xd80ff604,0x2ff3003f, 0x7fc407f8,0x7f980001,0xff880ff1,0x01fec001,0x3fd4bfe0,0xffffff80, 0xff703fff,0x1bee007f,0x1bee37dc,0x09f737dc,0x7fff57ea,0xffffffff, 0x7fd47fff,0xf985fb80,0x2002fe43,0x03ff04fe,0x7d41ff10,0xff13fd06, 0xff300003,0xff501fe2,0x887fcc00,0x980001ff,0x880ff17f,0x3fe800ff, 0x7ec07fb0,0x0001ff03,0x3e20ff60,0x3f60001f,0xb003ff03,0x3e7fe27f, 0x2a7fb02f,0x059d955f,0xdf727fc4,0x3603fd80,0x49f9003f,0x3fe202fe, 0x4fc80001,0xff880bfa,0x01ff4001,0x37dcffa0,0xffffff80,0x7ec43fff, 0xe801ffdf,0xe87fe02f,0x5c7fe02f,0x36bf504f,0xffffffff,0x47ffffff, 0x1ff104fd,0x27ec0fb8,0x7c13f600,0x0ff8801f,0x454c0ff2,0x80001ff8, 0x80bfa4fc,0x7fc006fb,0x0003ff11,0x17f49f90,0x7001ff10,0x80ff60bf, 0x07f983fd,0x20ff6000,0x20001ff8,0x03ff03fd,0x5fe27fb0,0x3fd80ffc, 0xffffbbf5,0x4ffd409f,0x7ec01ff8,0x400ff603,0x81bee1ff,0x80001ff8, 0x81bee1ff,0x6c001ff8,0x97fc003f,0x5ff007fa,0xe877f400,0xf83df0ef, 0xf8bf600f,0x5cbf600f,0x32bf504f,0x1fea004f,0x555559fd,0x86d83ff5, 0x7f4004fc,0x3003ff03,0x801fe8ff,0x80001ff8,0x81bee1ff,0x7f4005fc, 0x0003ff13,0x37dc3ff0,0x5001ff10,0x80ff60df,0x06fb83fd,0x20ff6000, 0x20001ff8,0x35ff03fd,0xd3333333,0xfe9fe27f,0xff53fd85,0x5ff9317f, 0x27ef7ec0,0xfb01fec0,0x88df5007,0xfff101ff,0xffffffff,0x2237d40b, 0xfff101ff,0xffffffff,0x1002fdcb,0x03fe63ff,0x2005ff10,0x6ffc46fa, 0x03fc46fa,0x03fc4ff2,0x827dcff2,0x00bf75fa,0x3ffe37dc,0xffffffff, 0x3ea13e22,0x80ffc006,0x7fa801ff,0x7c4007fc,0xffffffff,0x1bea05ff, 0x3f603ff1,0x8a7ec004,0xffffffff,0x3ea05fff,0x880ffc46,0x7f9800ff, 0x7ec07fb0,0x3a05fc83,0x81eeeeee,0xfff883fd,0xffffffff,0x3e07fb05, 0xffffffff,0xff13ffff,0x3f617fcc,0xfb05ff53,0x37ffc407,0x3603fd80, 0x83fd803f,0xfff104fd,0xffffffff,0x6c1fec0b,0xffff104f,0xbfffffff, 0xf30037cc,0x200ffc4f,0xfb002ff9,0x7ffff307,0x3600ff88,0x401ff12f, 0x20bf72fd,0x00ff55fb,0x2bfe2fec,0x99999999,0x3e20bea0,0x0ff3000f, 0x7dc00ffc,0x4400ffc6,0xffffffff,0x3f605fff,0xf904fd83,0x13fe8009, 0xffffffff,0x7ec0bfff,0xf104fd83,0x1ff3001f,0x7ec07fb0,0x3e06fb83, 0x81ffffff,0xfff883fd,0xffffffff,0x3e07fb05,0xeeeeeeef,0xff13ffee, 0x3f60ffc8,0x3ee0ff53,0x00ffdc05,0x3f603fd8,0x4d7fc403,0x80ffb999, 0x20001ff8,0x9999aff8,0xff880ffb,0x83ff8001,0x362ff438,0x17fe404f, 0xf703fe80,0x03ff01ff,0x03ff07f4,0x05fb87f4,0x01ffcbf9,0x3fa0ffcc, 0x807e4003,0xbfb004ff,0x6c00ffc0,0x9817f44f,0x001ff8ab,0x266bfe20, 0xa80ffb99,0x8ffc006f,0x20001ff8,0x9999aff8,0xff880ffb,0xb07fa800, 0x41fec07f,0x33300ff9,0xfb03ff33,0x003ff107,0xff81fec0,0xf13fd801, 0x7ecbfd0f,0x3ea0df53,0x003fcc05,0x1fec07fb,0x3ffffee0,0x883fffff, 0x2e0001ff,0xffffffff,0x1ff883ff,0x40ffb800,0x0ffcbffb,0xf8807fd4, 0xdf7002ff,0x20bffe20,0x8ff304fd,0x4ff304fd,0x4bfd06fa,0x7ec00ffb, 0xf306fd86,0xf502f41d,0x1ffa803f,0xf3007fe0,0xb04fc83f,0x003ff19f, 0x7ffffdc0,0x883fffff,0xff1000ff,0x0000ffc4,0xfffffff7,0xff107fff, 0x20df7001,0x0ff603fd,0xff000ffc,0xf107fb03,0x7ec0003f,0xb003ff03, 0x261fe27f,0x2a7fb2ff,0x80bf505f,0x3f6007f9,0xd00ff603,0xdddddddf, 0x3ff10dfd,0x777f4000,0x6feeeeee,0x0001ff88,0xfea87ff7,0x3dfd02ff, 0x02fefe98,0x4c19ff10,0x4c2fffff,0x27f4c3ff,0xfd30ffe6,0x2e17fcc9, 0x3ffa25ff,0x81ffe882,0x7f40bff8,0xf500fe23,0x07ff207f,0x10883ff0, 0x5ff10dfd,0xff89ff98,0x3bfa0001,0xfeeeeeee,0x2009ff06,0x07fe25fd, 0xeeefe800,0x86feeeee,0xfd800ff8,0x6c07fb05,0x00bfb03f,0x1fec0ffc, 0x0000ffc4,0x07fe07fb,0x3fc4ff60,0x3fd8ffc8,0x17ea0bf5,0x6c00ff30, 0x80ff603f,0x7fc407f9,0x000ffc41,0x7c407f98,0x00ffc41f,0xbdfff900, 0x019ffffd,0xfb9bffb1,0xfffffb3f,0x7e45ffff,0x8dffecff,0x7fe41ffe, 0x905ffecf,0xbffd9fff,0xfd9bffb0,0xffd88bf9,0x1effeddf,0x373ffee0, 0x00fdc6ff,0x76f7ffdc,0xff802fff,0x7fff7f41,0xb9fff701,0x07fe29ff, 0x203fcc00,0xff981ff8,0x10ffd401,0x260003ff,0x0ffc407f,0xf3003fe2, 0x80ff605f,0xbff503fd,0xb03ff300,0x03ff107f,0xf81fec00,0x13fd801f, 0x6eff40ff,0x2a0bf53f,0x03fcc05f,0x7ec07fb0,0x2013f203,0x0ffc44fe, 0x804fc800,0x0ffc44fe,0x3fae6000,0xffdabdff,0xbfffd903,0x3fffff65, 0x7d42ffff,0x3623efff,0xdfffd506,0xfffea807,0x3fff203e,0xd705f8ae, 0x019dffff,0x7dfffd30,0x26007d81,0x1bdfffdb,0x6c43ff00,0x4c01efff, 0x221cfffe,0xf90001ff,0x209fd009,0xff903ffa,0x001ff885,0xfd009f90, 0x400ff889,0x0ff606fd,0x3f203fd8,0x36620adf,0x3fd81fff,0x0001ff88, 0x0ffc0ff6,0x7f89fec0,0x4ffffe60,0x0bf505fa,0x36007f98,0x80ff603f, 0xffa801ff,0x0007fe20,0x7d400ffc,0x007fe20f,0xd5018800,0x00018809, 0x02009880,0x88001310,0x00260009,0x20000c40,0x00022009,0x30000018, 0x10188001,0x3e0003ff,0x0ffa801f,0xdbdfff70,0xff105fff,0x07fe0003, 0xf883fea0,0x7f5cc40f,0x80ff601f,0x7fdc03fd,0xffffeeff,0x107fb00c, 0x6c0003ff,0x003ff03f,0x01fe27fb,0x3ea7fff9,0x980bf505,0x0ff6007f, 0xff503fd8,0x88ffe200,0xffffffff,0x3ea6ffff,0x47ff1007,0xfffffff8, 0x006fffff,0x00000100,0x00000000,0x00000000,0x00000000,0x00000000, 0xf8800000,0xffffffff,0x1fea6fff,0x301ffc40,0x37bfffb7,0x3ffffe20, 0x6fffffff,0x7c401fea,0x3fffe23f,0x2fffffff,0xfb01fec0,0xfdb71007, 0xd803bdff,0xffff883f,0xffffffff,0xff03fd86,0x227fb003,0x3ffe807f, 0x17ea0bf5,0x6c00ff30,0x40ff603f,0x3f2004fd,0x3ffffe26,0x6fffffff, 0xfc8013f6,0x3ffffe26,0x6fffffff,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x10000000,0xffffffff,0x7ecdffff,0x01bf2004, 0xfff10018,0xffffffff,0x0027ecdf,0x7ffc4df9,0x0bdeffff,0x3603fd80, 0x0188003f,0x7c41fec0,0xffffffff,0x3fd86fff,0xfb003ff0,0x2601fe27, 0x20bf53ff,0x000005fa,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x4c400000,0xa8554400,0x84c4001a,0x262a9809, 0x3551001a,0x355154c0,0x2200cc00,0x088000aa,0x300aa980,0x01950057, 0x67654b26,0x40301102,0x19809818,0x26213100,0x4007b500,0xb95001aa, 0x2aa8017b,0x2a000553,0x46a6002a,0x154c02a8,0x40355100,0x04c002a9, 0x20013100,0x005511a9,0x2a600220,0x03550002,0x4c01aa88,0x0059302c, 0x00000133,0x4c415540,0x2e131000,0x2fd40003,0x77ddbf20,0x4efd4000, 0x8afe886f,0xdf9000ff,0x4cffc401,0x443200ef,0x2fff407f,0xf35bfb30, 0x209fd007,0x203ffffa,0x333ea05f,0x984fffff,0xf981b21f,0xff103ee1, 0x327fb001,0x3b8d984f,0x00fffc80,0x3fffff62,0x25ff102f,0xf88003ff, 0x4ff2002f,0x3fe607f9,0x1df7002f,0x2017fc40,0x02ffffd9,0x0bbfff6a, 0x1fe69f90,0xf359fd30,0x3fff9805,0x007fd400,0x3ee037e4,0x500bf504, 0x207f75ff,0xffffffff,0x40ffcc04,0x7fb003fd,0xff7001f6,0x105fffff, 0x007fa1ff,0x1ba77ea0,0x017f7fcc,0xa800ff88,0x3a01feef,0x640fd10f, 0xdb04fccf,0x803fffd9,0x23ba06fa,0x1fb81fd8,0x273ffea0,0xfe82ffc9, 0x7ec03fed,0xff884fee,0xf93fd800,0x01267509,0x40df5df5,0xfd98befe, 0xf74fc81f,0x13f2000b,0x3e67f900,0xfd5fd107,0x003ff003,0x7fc40df3, 0xa83ffcbf,0x2ffdbdff,0x3fcd3f20,0x3fff3ba0,0x2bfa200f,0x3fa001fe, 0x80bf6002,0x0bf504fb,0x02fffea0,0x3fffffe6,0x1fe404ff,0xfb003fd8, 0x98007ea7,0x1cefdccc,0x07f52fb8,0x2d57ea00,0x4007ff50,0x3f2002fb, 0x307fc02f,0xfe9bea0d,0x02e62c82,0x7c403f60,0xbf113ea4,0xd82ffa80, 0x037b504f,0x440732a0,0x3fd800ff,0x3b3a0791,0x647fe201,0x80ffa84f, 0x3a5f85fb,0x5f88000e,0xfd800000,0x5c01df54,0x0bee003f,0x3fe627ec, 0x3ea0ff40,0x64400007,0xfb002e61,0x2003fe69,0x744004f9,0x5413ee06, 0x77e4405f,0x09f500ff,0xd817e200,0x27fb003f,0x2a0004f8,0x0000005f, 0x001ed7ea,0x00000000,0x009907fc,0x00000000,0x22fc45f7,0x3fd401fb, 0x00005fb8,0x007fc400,0x405b1fec,0x6c00000a,0x01ff104f,0x00000000, 0x00000000,0x07f98000,0x837dc7f9,0x000001fe,0x00000000,0x4fb80000, 0xeb80bf50,0x3f20bf32,0x36000003,0x47fb003f,0xdca8806e,0x5405fa8b, 0x4400bcec,0xdfa8bdca,0xbb951048,0xecb88059,0x32a0d92c,0xfca81bde, 0x4c049ccf,0x2c981bdb,0x2e605930,0x22fb81bd,0x017e25f8,0xb7d41bea, 0x059302c9,0x059bb951,0xfb001ff1,0x164c3aa7,0xeca82c98,0x59fd01bd, 0x3ff55555,0x164c0b26,0x0de765c4,0x30159b73,0x4cb26059,0x2659302c, 0x2659302c,0x2e59302c,0x44df304f,0x405fd01a,0x800bceca,0x800bceca, 0x800bceca,0x800bceca,0xb80bceca,0x00bf504f,0x05fb5751,0x950003fb, 0x7fb037bd,0xfc8ff600,0x3fffe200,0xd305fcef,0x05ffffff,0x3bffffe2, 0x3fea05fc,0x505fffff,0xffffffff,0xfffffd05,0xffffc87f,0x7ffec01f, 0x13ee0fff,0x7fec2fd4,0x3ea0ffff,0x0fc93ea4,0xf305fa80,0x7d413eed, 0x7ffffd45,0x07fc45ff,0x076efec0,0x17ea09f7,0x7ffffffd,0xfffffff0, 0x3ee5ffff,0xfa8bf504,0xbbffffff,0x42ffffff,0x2bf504fb,0x2bf504fb, 0x2bf504fb,0x2bf504fb,0x0ff102fc,0x2603fea0,0x2ffffffe,0xfffffd30, 0x3ffa605f,0xd302ffff,0x05ffffff,0x3fffffa6,0xa827dc2f,0x7ffec05f, 0x3fc0ffff,0xffe80353,0x7ec3ffff,0x4c7fb003,0x2bbfa02f,0xd05fffb8, 0xffb517df,0x715dfd03,0x3e20bfff,0x5ff731bf,0xd52eff98,0x1dfc81ff, 0x4c43ff51,0x7ec019ff,0x25fc98be,0x8bf504fb,0xfc98befd,0x3627be25, 0x2009f11f,0x2df305fa,0x4bf504fb,0xf731bff8,0x007fc45f,0x7dc067ec, 0x7e4bf504,0x83ff511d,0x99999aff,0x09f70999,0xaff897ea,0x7dfff930, 0x5c1ff711,0x2ebf504f,0x2ebf504f,0x2ebf504f,0x36bf504f,0x803fe02f, 0xfd03ffb9,0x3ffb517d,0xb517dfd0,0x7dfd03ff,0xd03ffb51,0xffb517df, 0x517dfd03,0x2fdc3ffb,0x3fa05fb8,0x3fffb9cf,0x3fff3fe2,0x1dfc81ef, 0x7ec3ff51,0xf87fb003,0xf10bf705,0x20df70bf,0x42fdc6fb,0xbf705ff8, 0x9fd13f60,0xfe89ffd0,0xff83ec81,0xe837d400,0x2a09f71f,0x741bea5f, 0x3bffaa1f,0x54003f22,0x2edf305f,0x5cbf504f,0x449fb05f,0x3fd800ff, 0x3ea09f70,0x3b207fa5,0x7001ff43,0xc97ea09f,0x03fff03f,0x827dcdf7, 0x209f75fa,0x209f75fa,0x209f75fa,0x403fd5fa,0xfff900ff,0x5c1bee07, 0xb837dc6f,0xb837dc6f,0xb837dc6f,0xb837dc6f,0x6417ea6f,0x01df505f, 0x7ffd4bfb,0x41fffdbd,0x23ec81fe,0x7fb003fd,0x05fb07d8,0x0bfa17f2, 0x0bf61ff8,0x09882fe4,0x7fc4bf70,0x23fd7e40,0x3e000dfd,0x81fe400f, 0x209f70a9,0x40ff25fa,0x442980a9,0x540aa24f,0x2edf305f,0x44bf504f, 0x44bf7009,0x3fd800ff,0x3ea09f70,0x40037f65,0x1df306fd,0x2fd413ee, 0x1bf60131,0x4fb87fc4,0x13eebf50,0x04fbafd4,0x413eebf5,0x403ff5fa, 0xfd9901fe,0x405fd07f,0x80bfa1ff,0x80bfa1ff,0x80bfa1ff,0x80bfa1ff, 0x20df31ff,0x07fb05fd,0x0efa9fe2,0x3f637f44,0x03fd800d,0x1fb87fb0, 0xbf500ff8,0x7ec01ff0,0x7d403fe2,0xfb951005,0x2e37ccbf,0x7d41ff2f, 0x7c00bdff,0x00ff400f,0xbf504fb8,0x80000ff4,0xfffd30fc,0xf305fa87, 0x7d413eed,0x3f72a205,0x007fe25f,0x27dc0ff6,0x3fea5fa8,0x3e200bdf, 0x71ff40bf,0x817ea09f,0xadffdba8,0x1feaaaaa,0x57ea09f7,0x2bf504fb, 0x2bf504fb,0x2bf504fb,0x03fe01fe,0xff13fa60,0xff17ec01,0xff17ec01, 0xff17ec01,0xff17ec01,0xf897ec01,0x82ffdc2f,0x03fa01ff,0xf507fd40, 0x36017bff,0x87fb003f,0x03fc43f8,0x07f88bf3,0x07f89fe4,0xfd9817e6, 0x25feffff,0xf8fe65fa,0x7fff4c1f,0x01ff02ef,0xf7000ff8,0xff97ea09, 0x4f880000,0x8bf22bf2,0x2df305fa,0x8bf504fb,0xefffffd9,0x400ffc5f, 0x09f702fe,0xffd317ea,0x3ee05dff,0x46ffdcff,0x8bf504fb,0xfffffed8, 0xffffffff,0x209f73ff,0x209f75fa,0x209f75fa,0x209f75fa,0x405fb5fa, 0x9bee007f,0x9fe407f8,0x9fe407f8,0x9fe407f8,0x9fe407f8,0x1fe407f8, 0x9fd9bff9,0x01ff10bf,0xf88017ec,0x7fff4c2f,0x01fec2ef,0x85e83fd8, 0x8bf300ff,0x3f600ff8,0x7cc03fe2,0x79dff305,0x6fa97ea3,0x00ff8bd1, 0x07fffd73,0x1ff801ff,0x2e0bf700,0x0007fe5f,0x25f83f60,0x417ea5f8, 0x20bf76f9,0x3bfe65fb,0xe8bf51bc,0x01ff802f,0x17ee0bf7,0x1ffff5cc, 0xbefffe98,0xfb82fdc0,0x2b3ffe65,0x33339fb1,0x3ee13333,0x3eebf705, 0x3eebf705,0x3eebf705,0x3f6bf705,0x400df102,0x1ff11ff8,0xff897ec0, 0x7c4bf600,0x44bf600f,0x4bf600ff,0x3f600ff8,0x577ffe42,0x01ff05f8, 0xfd0017f4,0x3ffae605,0x010ff63f,0x03f20ff6,0x17ea03fd,0x0fe807fe, 0x2fd407fa,0xbf904fe8,0x07ec7fcc,0x36200ff1,0x400ff86f,0x257302fe, 0x4bf905fb,0x057302fe,0x13e64f98,0xb7cc00df,0x4bf905fb,0x8bf904fe, 0x7fc403fc,0x320bf700,0x6fd8805f,0x3ee04e80,0x7f4bf905,0x4009fb04, 0x2bf905fb,0x2bf905fb,0x2bf905fb,0x2bf905fb,0x4bf504fc,0x3ff101eb, 0x1fd00ffc,0x1fd00ffc,0x1fd00ffc,0x1fd00ffc,0x1fd00ffc,0x00f98220, 0x8ffc03ff,0x3ff101cc,0x6cdfb100,0x3a07fe3f,0x642fa82f,0xb0bfb04f, 0x91fe609f,0x417f609f,0x8bfb01ff,0x7dc1fdff,0x2203fa26,0x007fc0ff, 0xa7ec13f2,0x4bfd06fa,0x09fb04fc,0x0fea0fd8,0xafd400ff,0x4bfd06fa, 0x8bfb01ff,0x3f200efb,0x741bea07,0x101fd15f,0x03f801ff,0xaff41bea, 0xff880ff8,0x2a1ff106,0x2abfd06f,0x2abfd06f,0x2abfd06f,0x26bfd06f, 0x6c7f907f,0xd8ff705f,0xd8ff304f,0xd8ff304f,0xd8ff304f,0xd8ff304f, 0x00ff304f,0x09fb03dc,0x06fd9fea,0x07f44ff7,0x3fd87fc4,0x07fe0ffa, 0x5ff313e2,0xf985ffb8,0x227f4c3f,0x7fdc2ff9,0xf907fb05,0x44ffc8bf, 0x27e41ffb,0x0ff42fdc,0xf30bfe20,0x70bfe63f,0x17fc4bff,0xf9807fe6, 0xdf12fcc3,0xf9a7e400,0xb2ffdc2f,0x8bff907f,0xfb81efe8,0x0bfe602f, 0x27e4bff7,0x2fc02fdc,0xfb85ff30,0x360ffa5f,0x4fd84fff,0xff70bfe6, 0xf70bfe6b,0x70bfe6bf,0x0bfe6bff,0x27ecbff7,0x5ff51be6,0x7cc4fe98, 0x227f4c3f,0x7f4c3ff9,0x261ffcc4,0x1ffcc4fe,0xff313fa6,0x004fe987, 0x7fcc07ee,0xf51ff542,0x43fea85f,0x25fb84fc,0x87bf23fd,0x21b607fc, 0xeffceffa,0x9fff905f,0x3ea0bffd,0x5feffcef,0xd97bff50,0xff98dfbf, 0x84fffcdf,0xfeccfff8,0x1effe81f,0x373ffee0,0x6ffec4ff,0x5c5fcfec, 0x4ffdcfff,0x7f407ec0,0xd9007f91,0x6ffec5ff,0x2a5fcfec,0xdfecbdff, 0xffff886f,0x803fffee,0xcfecdffd,0x33ffe25f,0xd801ffec,0xffd87def, 0x25fcfecd,0xffdbdffa,0xfccefe9b,0xcdffd86f,0x3f65fcfe,0x5fcfecdf, 0x3fb37ff6,0x37ff65fc,0x265fcfec,0x1ffdbdff,0xfeceffc8,0x9fff906f, 0x3f20bffd,0x05ffecff,0xffd9fff9,0x33fff20b,0xff905ffe,0x00bffd9f, 0x44ecff98,0xffecfffb,0xebeffc85,0xfff885ff,0x361ffecc,0x3bffe23f, 0x3ee02fff,0xbfffda80,0x3faa05f9,0x6d403eff,0x05f9cfff,0x47bfff6e, 0x36fba1ff,0x2602efff,0x01dffffe,0x9807ffd3,0x901cfffe,0xbf15dfff, 0x39fffd30,0xd303f980,0x3a009fff,0xfffc83ff,0x6dc5f8ae,0x3ff1efff, 0xdfffd930,0x7fe40059,0x4c5f8aef,0x01dffffe,0x207df910,0xf8aefffc, 0x6fffedc5,0x3bfff621,0xdfff900b,0xffc8bf15,0x645f8aef,0x5f8aefff, 0x4577ffe4,0x7fff445f,0x3ffea02d,0x7f5403ff,0x75403eff,0x5403efff, 0x403efffe,0x03efffea,0x1f7fff54,0x1ceeb800,0x3ffffea8,0x3bfffee0, 0x3fffa603,0x21fec1df,0x03efffe9,0x03101fcc,0x00026200,0x06200031, 0x00260640,0x22001988,0x80062000,0x00c40009,0xb9801950,0x09800000, 0x00006200,0x09800013,0x00066200,0x80026000,0x00088018,0x00980026, 0x09800260,0x10006200,0x09880013,0x0004c400,0x31000262,0x00988001, 0x04c00000,0x40013100,0x22000198,0x00260009,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x10000000,0x2604a859,0x2005511a,0x550002a9,0x01aa8803, 0x0aa86a60,0xa8003300,0x2353003d,0x130002a8,0x00055300,0x2aa006aa, 0x055cc002,0x22f72a00,0x407953c8,0x262003c9,0x80001310,0x4000aba8, 0x40000bb9,0x1c81aca8,0x98026a60,0x20131001,0x0009bba8,0x0005654c, 0x5cc00660,0xa88000ab,0x057001ac,0x2b80b220,0x98039500,0x0aa8800a, 0x70059100,0x004c4059,0x0dd0bea0,0x07f9a7e4,0x003fff98,0x64007fd4, 0x3fe6006f,0x6c406fa8,0x400befff,0xc803b8d8,0xa80ff34f,0x02f99cfe, 0x001fffcc,0x26003fea,0xffa801ff,0x4400dfff,0xfbffffff,0x3201ff36, 0x57ea003f,0xb50005fa,0x805fffff,0xffffffda,0x3fb2001c,0xf72fffff, 0xfffff507,0x001ff107,0xffe887fb,0x400dffff,0xeffffffb,0x1ff88003, 0xfffffb70,0xec8801df,0x02efffff,0x7ec013f6,0x1009fb00,0x7ffd40bf, 0xfdf902df,0x01fb009f,0x7dc09fb0,0x10fe4004,0x9a7e40bf,0x57f4407f, 0x3fa001fe,0x00bf6002,0x00ffefa8,0x3f2fbfa2,0x499d406f,0xff34fc80, 0xfffcee80,0x2bfa200f,0x3fa001fe,0x017ee002,0xfb539ff3,0x8aefe809, 0x3fa6fffb,0x4001ff02,0x00bf55fa,0xb55bff30,0x3bea05ff,0x07fae61b, 0x2af7ff60,0x84feffdb,0xffdbeffa,0x4007fc45,0x3ffe63fd,0x0effecbd, 0xabdffe88,0x4004fffc,0x7f441ff8,0xfecbbcef,0x3bff602f,0x43fffdbc, 0xb804fffa,0x4fffa82f,0xf900fd80,0x85ffb7ff,0x803fa4e8,0x7d9002fb, 0x20027dc0,0x001fcc7d,0xf9a7ec00,0x04fa800f,0x20037440,0x7e401ffc, 0x200ff445,0x00001ece,0x05d43910,0x7fcd3f60,0x004fa800,0x3f601fc8, 0xc807fc43,0x5cdff05f,0x005fa85f,0x05faafd4,0xfc84fe80,0xd804fa86, 0x07bf601f,0xff83ffd4,0xf10ffcc3,0x47fb001f,0xbfd105fd,0x2a03dfd0, 0x3e2004ff,0x017ff41f,0xdfb01ffb,0xd87ff201,0x7cc04f8b,0x09f17b04, 0xff302fb8,0x200ff987,0x13e606f9,0x09f70000,0x0fdc5f80,0x00000000, 0x00000000,0x501ff100,0x001500bf,0x00000000,0x00000000,0x3fe03fe0, 0x2e03fb00,0xb03fe26f,0x5fa8005f,0xf8800bf5,0x20ff881f,0x355554fa, 0xfc81fd81,0x17ffcc06,0x3f603fe6,0x2003fe23,0x807fe3fd,0x07fdc7fb, 0x400ffea0,0x3fee1ff8,0x643fd800,0x3fa200ff,0x7404f885,0x204f8806, 0x1bf204f9,0xefc82fe4,0x1001ba00,0x027dc013,0x33bf332e,0x00ccfecc, 0x0017bb95,0x0017bb95,0x0017bb95,0x0017bb95,0x2017bb95,0x510004fc, 0x88059bb9,0x402cddca,0x02cddca8,0x166ee544,0x33772a20,0x6ee54402, 0xa87f882c,0x403fe05f,0x11fec6f9,0x6e5440ff,0xbf55fa8b,0x4c06f76e, 0x9f0100ff,0x1ffffffc,0x80bfe1b6,0x4c6fdef8,0x447f907f,0x3fd800ff, 0xcd801ff1,0x2005ff10,0xff1006fb,0xa801ff43,0x4017fc4f,0x04f884ea, 0x3e2007f2,0xfd01ba04,0x4c1fe607,0x1fc80eeb,0x701fe400,0xfffd809f, 0xffffffff,0x7ffec40f,0xfb102fff,0x205fffff,0xffffffd8,0xffffb102, 0x3f6205ff,0xd82fffff,0x7d40042f,0x05ffffff,0xfffffff5,0x3fffea0b, 0xff505fff,0x20bfffff,0xfffffffa,0xfffff505,0x87f88bff,0x0ff101fe, 0x9bea37c4,0xfff104fb,0x2abf9dff,0xfffffddf,0x001ff883,0x3227c3f3, 0xf983ea0f,0x2a3ba206,0x217f41ff,0x3fe21ff8,0x3a3fd800,0x3fd4005f, 0x001ff300,0x07fc3ff1,0x00ff3000,0x2a09f100,0x09f1003f,0x3ff007f2, 0xa807fe20,0x001fd43f,0x9f7017ec,0xafd99880,0x819df999,0xfd98befe, 0x8befe81f,0xfe81ffd9,0x1ffd98be,0xd98befe8,0xbefe81ff,0x741ffd98, 0x4fffe99f,0x2637ff10,0x7fc42ffb,0x85ff731b,0xf731bff8,0x1bff885f, 0xf885ff73,0x5ff731bf,0x731bff88,0x23fc45ff,0x3fe206fa,0xff0df300, 0x7f407fa1,0x5fffb8ae,0xb319fff5,0x07fd03ff,0xa89f1ee0,0xfb8be21f, 0x7c47fa05,0x4e7fd42f,0x7fc44feb,0x2a3fd800,0x400acfff,0x7fc006fb, 0x31ff8801,0xfa8000ff,0x4f880006,0x22005f88,0x803fa84f,0x3ff503fe, 0x21fc8fea,0xf98005f8,0x013ee00f,0x81fcc7d8,0x5fb80ffa,0x7dc07fd4, 0x5c07fd45,0x407fd45f,0x07fd45fb,0x2ffe2fdc,0x86fffeff,0x89fb05fb, 0x89fb05fb,0x89fb05fb,0x89fb05fb,0x89fb05fb,0x49fb05fb,0x01fec7f8, 0x37d407fe,0x837c5fe4,0x5ff885fb,0xdf705ff5,0x6677f64c,0xcf8bb01c, 0x4e86ea99,0x0fec13f2,0x3fe20ffa,0xff883fff,0x543fd800,0x1cefffff, 0x74005fc8,0x1ff8803f,0xc8000df7,0xf880005f,0x2000fd84,0x02fc44f8, 0xffb06fc8,0x2ffffec5,0xf10003f6,0x74fb809f,0x2e2fc0ff,0x209fb01f, 0x13f60ff8,0x9fb07fc4,0xfd83fe20,0x6c1ff104,0x41ff104f,0x3aa1dfff, 0xb804c43f,0xb804c45f,0xb804c45f,0xb804c45f,0xb804c45f,0xb804c45f, 0xf91fe25f,0x827e401d,0xbef986fe,0x205fb03f,0x40df55fc,0xffff70ff, 0x13a05fff,0x019fffff,0x641ff4bb,0x4c4fd82f,0x2ffecffe,0x6c007fc4, 0xffdb883f,0x27ec4fff,0x2013f600,0x0bf91ff8,0x77777774,0x00009fb1, 0x205f706a,0xfd83501a,0x3e6054c0,0xfff711cf,0x5c0ab885,0xd103502f, 0x29f700bf,0x89f107fb,0x59fd00fd,0x3ff55555,0x555567f4,0x3fa1ffaa, 0xfaaaaaac,0x2ab3fa1f,0x21ffaaaa,0xaaaaacfe,0x3ffe1ffa,0x4407fb80, 0x405ffdca,0x05ffdca8,0x2ffee544,0x3ff72a20,0x7ee54405,0x6e54405f, 0x11fe25ff,0x3e203dff,0xdffb30cf,0x403fbfa0,0x2bf500ff,0x47fa04fa, 0x999ff998,0x9cf8d900,0x6c7f03fb,0xe81fe44f,0x30bfe62f,0x07fc47fd, 0x4c01fec0,0xf90effeb,0x03fe8009,0xdf71ff88,0x7fffffc0,0x000bf71f, 0x6c13e600,0x45f7004f,0x5c6ffffa,0xdcffefff,0x09f3001f,0xbfd113f6, 0x5453ee00,0x567e54c2,0x42aaffaa,0xffffffff,0x3ffe2fff,0xffffffff, 0x3fffffe2,0x3e2fffff,0xffffffff,0x3fffe2ff,0x2fffffff,0x7fc417fa, 0x7fffecc0,0xfd985fef,0x85feffff,0xefffffd9,0xfffd985f,0xd985feff, 0x5fefffff,0xfffffd98,0x21fe25fe,0xf502ffe8,0xdfbffdff,0x4417fee0, 0x557e607f,0x20bf604f,0x0fa800ff,0x4c1fb93e,0xfb97f21f,0xfc83fe04, 0xff8df705,0x002fe801,0x6fa97fdc,0x400ffc00,0x1ff31ff8,0x3e666660, 0x000ff51f,0x3203ba00,0x5f9804ff,0x1fdc3be2,0x74f7ffa6,0x01dd001f, 0x5fc89ff9,0xb013ee00,0xffffffff,0x7fc1ffff,0x9999999a,0x266bfe09, 0x20999999,0x99999aff,0x2bfe0999,0x99999999,0x2666bfe0,0x3a099999, 0x987fe02f,0xf51bceff,0xbceff98b,0xff98bf51,0x8bf51bce,0x51bceff9, 0xceff98bf,0xf98bf51b,0xbf51bcef,0xff903fc4,0x37fb2605,0xff105fa9, 0x9807fc05,0x740bf55f,0x803fcc2f,0xfd13e2f8,0x5fea3dc1,0x1fe605fa, 0x0ffc05fd,0x3ff005fd,0x3f20072e,0x2001ff14,0xf88087f8,0x8007fe0f, 0x01ff11ff,0xc803bf10,0x4fdfa81f,0x04c0ee80,0x7fc007f5,0xa81fc800, 0x0ff44fdf,0x404fb810,0xb999fe98,0x7f4199bf,0x01ff4003,0xd000ffa0, 0x3fe8007f,0x8827ec00,0x413fa0ff,0x827f45fc,0x827f45fc,0x827f45fc, 0x827f45fc,0x827f45fc,0x01fe25fc,0xfa800bf7,0xfd01fe05,0x7d57ea03, 0xf703fe06,0xf8774009,0x5f8a7cc4,0x405fcfe8,0x00ffc5fd,0x01fe43ff, 0x27e43fe2,0x9ff2fdc0,0xf997f600,0x7ec7f887,0xf87fe005,0x0ffc803f, 0x3e60fe60,0x7e404f8d,0x107f4401,0x201be601,0x8df983f9,0x407fe24f, 0x013ee6fb,0x807ee2fc,0x1df306fd,0xef9837ec,0x7cc1bf60,0x4c1bf60e, 0x41bf60ef,0x1be60ef9,0x07fe37dc,0x07fe2fec,0x07fe2fec,0x07fe2fec, 0x07fe2fec,0x07fe2fec,0x4ff12fec,0x3237cc08,0x207fb01e,0x27e404fb, 0x0ff55fd8,0x03fa1fea,0x098ee880,0x80ef8988,0x2e00effa,0x81fec1ff, 0x3bee0ffa,0xf99ff200,0x31fec01f,0xffa803ff,0xf307fe21,0x805ffa8d, 0x3fea1ff9,0x817fe602,0x15f886e8,0x01fcc09f,0x5fb87fe6,0xf8807f90, 0x9f16f886,0x9fd04fe8,0x7cc027dc,0x3e203ec4,0x21ff40bf,0x7f40bff8, 0x205ffc43,0x5ffc43fe,0x3e21ff40,0x41ff40bf,0x1ff4c4fe,0x3ff20ff6, 0x7e41fec5,0x641fec5f,0x41fec5ff,0x1fec5ffc,0x3f62ffe4,0x225ffc83, 0x641df37f,0x2077dc3f,0x74c20ffb,0x17fcc00f,0x7fd57fee,0x3617f4c5, 0x0c09abcf,0xf300f744,0x3ffe201d,0x81ffd883,0x7f442ffa,0x40f7f445, 0x7ff42ffb,0x07fec40b,0x7e40ffea,0x10cfe82f,0xbff90bfd,0x7fecc415, 0x057fe41f,0x401dfd71,0xeefc80fd,0x6f884ffe,0x74077d40,0x402fdc0f, 0xeefc80fd,0x3fee4ffe,0x43ff910a,0x2fa804fb,0x7fdc037c,0x706ffdcf, 0xdffb9fff,0x373ffee0,0xfff706ff,0x2e0dffb9,0x6ffdcfff,0xfb7dff30, 0x7bff509f,0xa8dfbfd9,0xdfecbdff,0x5effd46f,0x546fdfec,0xdfecbdff, 0x5effd46f,0x546fdfec,0xdfecbdff,0xfd9fe26f,0x440ffdbe,0xfffdeffe, 0x01fffe41,0xffceffa8,0xdfdf55fe,0xfb8bffb9,0xefffffff,0xefe882ff, 0x0effdaac,0xfffbfd10,0x03fffdbd,0x7edeffe4,0xfff880ef,0x83fffeef, 0xfeffffd8,0xff701eff,0x5fffdbdf,0x3fbffea0,0xfff700ff,0x9ffffddf, 0x3bfff601,0x201ffffd,0x999502fa,0x1fb07df9,0xf702fdc0,0x01ffb7bf, 0x99502fa8,0xfd87df99,0x42fffdff,0x0fc804fb,0x74c013e2,0x200befff, 0x0befffe9,0x3bfffa60,0x3ffa600b,0x3a600bef,0x200befff,0x04efffd8, 0x47bfff6e,0x7fedc1ff,0xb83ff1ef,0xff1efffd,0xefffdb83,0xfdb83ff1, 0x83ff1eff,0xf1efffdb,0xf91fe23f,0x2a2039ff,0xb81cdfec,0x6d4004ef, 0x55f9bfff,0x7ffff59f,0x7335bf30,0x407ffffd,0x1beffec9,0xfd98fec0, 0x801bdfff,0x04fffffa,0x77fff64c,0x7ff5c02c,0x4c00ceff,0x1bdfffdb, 0x6ffffd40,0x7f6dc401,0xb801deff,0x0cfffffe,0x88017e20,0x202fa84f, 0x5ffffff9,0x0e77fed4,0x88017e20,0xdffb504f,0x009f703b,0x00013031, 0x01300013,0x30001300,0x00130001,0x0c400130,0x4000c400,0x01880018, 0x88001880,0x00180001,0x10000000,0x40088003,0x00066200,0x80cc0011, 0x26200018,0x00130000,0x80002620,0x00310001,0x10000c40,0x32a00133, 0x640d4000,0x55554c03,0x001101aa,0x2a000654,0x00000001,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x98005dcc,0x19809881,0x2204c400, 0x26603309,0x00199999,0x166ee544,0x037b7300,0x99999988,0x220aa600, 0x10260009,0x20013001,0x99999998,0x40999999,0x81310019,0x0adc89c9, 0x2007ba60,0x09999999,0x26666660,0x21550019,0x902642a8,0x00eea809, 0x00def654,0x26666662,0x220aaa00,0x99999999,0x20019999,0x20554418, 0x40aa8838,0x54c00019,0x06602aa1,0x26666200,0x55100099,0x4004cc00, 0x02aa8019,0x22035510,0x805510aa,0xffffffda,0x90ff301c,0x007f98df, 0x37ea27d4,0xfff887f8,0x1dffffff,0x7ffffd40,0xffd805ff,0xfd00ffff, 0x407fffff,0x05fa83ff,0x5c7d1760,0x00fb9bee,0xffffff88,0xffffffff, 0x6c00ffc3,0x7f5fd43f,0x3fea00ff,0xfffff801,0xfff102ff,0x3bffffff, 0x3fdafe40,0x07f81fe2,0xfd007fdc,0x407fffff,0x4ffffffd,0xb85fff50, 0xffffffff,0x441fffff,0x45d8bdfc,0x837cc6fc,0x03fe25fe,0xa8ff9800, 0x007f986f,0xffffffe8,0x4ffe8803,0xc80bf900,0x0ffcc06f,0x200efc80, 0x405fd4fc,0x2e61befa,0x87f981fe,0x03fcc6fc,0xbf513ea0,0xdff10fd1, 0xffffdddd,0x46ffe209,0x3602ffb9,0x5fc98bef,0x99999970,0x3617ee03, 0x06eeeffe,0x43ff7fe6,0x6fffddf8,0xfddff700,0xdddddddf,0x801ff85d, 0x7ffd43fd,0x7fd404bc,0xccccc801,0xdff101cc,0xffffdddd,0x27eff409, 0x07f81fe2,0xfc807fdc,0x03ff511d,0x3333332e,0xff9ff882,0x3bbbbaa0, 0xeeeeeeff,0x7ff67dc1,0x303fe23f,0x43fa20df,0x40000ff8,0x980ffefa, 0xccb8007f,0xd801cccc,0x8803fdbf,0x5ff102ff,0x1003fd80,0xbfd003ff, 0x027d409f,0x1fe60fec,0x0ff31722,0x7d44fa80,0x1ff10d35,0x20bff220, 0x09fb05fb,0x0ff41bea,0x80ee8000,0x6eeeffed,0x3056dc40,0x800aa219, 0x00df73ff,0x7777ff5c,0xffeeeeee,0x00bfea6e,0x10000000,0x3f2201ff, 0x0dff102f,0x03fc0ff1,0x640ff400,0xfd00003e,0xb003bea7,0x88ee009f, 0x4c17e41b,0x453e606f,0xc80000ff,0x0ff301ff,0xfb800000,0x7003ff16, 0x017f20df,0x7dc00bf1,0x0bff1002,0x795127d4,0x3e61fd83,0x7f987b07, 0x2a27d400,0xff10995f,0x40ffb801,0x0bf70098,0x054c0ff2,0x00bceca8, 0x0017ea00,0xfb800000,0xc801bee7,0xffffffff,0x7fffffff,0xca801fea, 0xca800bdd,0x3e200bdd,0x07fdc00f,0xf03fc400,0x0dedcc0f,0x4000dfd8, 0x02cddca8,0x04fd8000,0xfb700000,0xff10099f,0x79bddddd,0x3e600001, 0x059301c7,0x00000b26,0xff987fd0,0x00000001,0xe893e000,0x360efdef, 0x3ae1fe66,0x2003fcc0,0x46fd44fa,0x001ff104,0xca8807fd,0x3fd05ffd, 0xfffe9800,0x4e4c2fff,0x3ea0adc8,0x4037b955,0x072a01ca,0x3ee3ff80, 0x01ff8006,0x37d43fd8,0x7fffec40,0xffb102ff,0x2205ffff,0x3fe800ff, 0x56e44e4c,0x3e20ff10,0xfffffb07,0xdfffa81f,0x7ffd400b,0x2a05ffff, 0x13f6001c,0x3b2a3930,0x3a0e542c,0xca87ffff,0xffffff11,0x985fffff, 0x059d951c,0x7036cff3,0x5d7ea09f,0x703c981c,0x41ff5019,0x999904fd, 0x21999999,0x59d951c9,0x99999990,0x47e61999,0x93e21ee8,0x10ff30fa, 0x800ff301,0xbf508cfa,0x800ff880,0xffd985fc,0xf05fefff,0xefe8001f, 0x21ffda8b,0x0fffebfa,0x3fff77ea,0x07f905ff,0xfb801fe4,0x40037dc7, 0x3fd801ff,0x7f402fd4,0x1ffd98be,0xd98befe8,0x0ff881ff,0x7d45fc80, 0xf10fffeb,0x361fe20f,0x5fc98bef,0xeffffe98,0x31bff882,0x3f205ff7, 0x013f6003,0xffff97f5,0x221fe4bf,0xfc819efa,0x3335ff13,0x43ffd753, 0xffffcbfa,0x747fcc5f,0x413ee02f,0x907f95fa,0x07f881ff,0x07fcd3f6, 0xfffffff8,0x97f50fff,0xf8bfffff,0xffffffff,0x1fccf70f,0x265f10cc, 0x1fe6007f,0x23fdf500,0x7fc405fa,0x4c6fb800,0xf51bceff,0x8007fe0b, 0x4df706fb,0x44bcfffa,0xc99cfffa,0x03fc82ff,0x7f400ff2,0x40037dc3, 0x99999aff,0x543fe999,0x07fd405f,0x3fea2fdc,0xf885fb80,0x46fb800f, 0x24bcfffa,0x8ff107f8,0x03fd06fa,0x0ffffae6,0x13f60bf7,0xfb001fe4, 0xcfffa809,0xf92ffb89,0x640df307,0x401ff13f,0x3fea5fe8,0x2ffb89cf, 0x007fbfe6,0x57ea09f7,0x2ffe86fa,0xff3027d4,0x4cc07fb1,0x4ff99999, 0x2273ffea,0x26662ffb,0x24ff9999,0x4003ee5d,0x400ff34e,0x87fb87f9, 0x17ea5ffa,0xaabffba8,0x747f982a,0x20bf904f,0x457302fe,0x47fe02fe, 0x3ea02ffa,0xc84fd82f,0x00ff203f,0xff703fea,0xdfffffff,0xfffffff0, 0x87ffffff,0x27ec05fa,0x3f60ff88,0x541ff104,0x2aaabffb,0x7fd47f98, 0x301ff102,0x303fc8ff,0xdfb10015,0xbf700988,0xd800ff20,0x17fd404f, 0x83fca7e4,0x4ff206f9,0x7dc00ff8,0x320bfea6,0x03bfe64f,0x7d413ee0, 0xef883fe5,0x2017ec4f,0x0006fefc,0x2ffa8bfb,0xfd804fc8,0x00f92745, 0x007f9aec,0x1fee1fe6,0x0bf517f2,0x7ffffffc,0x20ff986f,0x0bfb01ff, 0x27ec13f2,0x97ec01ff,0x3fd407fa,0x3fc85fb8,0x3a00ff20,0xffffb83f, 0xf86fffff,0xeeeeeeef,0x7d43ffee,0x5567f405,0x21ffaaaa,0xaaaaacfe, 0x3ffe1ffa,0x986fffff,0x81fea0ff,0x7fb82ff8,0xe8800ff4,0x00ff880f, 0x17ff72a2,0xff901fe4,0x5fffffff,0xbf707fa8,0xffb70ff2,0x227f9079, 0x3fd400ff,0x97ee0ff5,0xf7000ffb,0xfd97ea09,0xf1befee2,0xfffff30f, 0x09ffffff,0xfa81df90,0xc80bf707,0xf73640ef,0x7ccfe003,0x21fe6007, 0x27fec2a8,0xf99817ea,0xa80999af,0x641fec7f,0x5ff105ff,0xff11ff98, 0xdf53fc80,0xf505fa80,0x6407f90b,0x07fd403f,0x7c0037dc,0x43fd801f, 0x7ffc05fa,0xffffffff,0x3fffffe2,0x262fffff,0x0999aff9,0x37d47fa8, 0x4c1dff10,0x007fc7ff,0xbf709f90,0xfffffb30,0x0ff20bfd,0xefeccca8, 0x37d41ccc,0x87f95fa8,0xc86ffffe,0x801ff13f,0x41bea6fd,0x0fff95fa, 0xfa827dc0,0x8fd93ea5,0x30bf30fe,0xdffddddd,0xfb807ddd,0x506fa80f, 0x07fdc0bf,0x83fa87d4,0x7cc7e67c,0x01fe6007,0x7d44fdf8,0x007fc405, 0x3fea2fdc,0x6fdfecbd,0x373ffee0,0x03fe24ff,0x0bf52fd8,0xbf505fa8, 0x7e407f90,0x7ffff403,0x006fffff,0xfd801ff8,0x3e02fd43,0x999999af, 0x26bfe099,0x09999999,0x5c007fc4,0x102fd45f,0xffdbffff,0x001ff8ff, 0x3b33ffe2,0x77fcc1ff,0x20bf51bc,0x3f6003fc,0xa82fd404,0xf307f95f, 0xf89fe40d,0x93fe600f,0x2bf505fa,0x2e007fdf,0x44bf705f,0x97e5be6f, 0xbf5002fc,0x01ffa800,0x17ea0bf5,0xf880ffd4,0x2e233f62,0x7f99ee2f, 0x801fe600,0x2fd44fa8,0x2003fe20,0xffdb84fd,0x403ff1ef,0x81cfffe9, 0x43fa01ff,0x2fd405fa,0x3fc85fa8,0xfa80ff20,0xffffffff,0x1ff8006f, 0x7d43fd80,0x001ff405,0x22000ffa,0x4fd800ff,0xff102fd4,0xfd3dfff3, 0x57302fe8,0xdffffe98,0xf904fe81,0x800ff20b,0x2fd404fd,0x07f95fa8, 0x9fe40df3,0xcccccff8,0x7d46ffec,0x26abf505,0x17ee007f,0x27f62fe4, 0x3a9f54f9,0xaaaa880f,0x1aaaaefc,0x5405ff30,0x30bf505f,0x0ee805ff, 0x49ffffb1,0x01fe65f8,0x54007f98,0x202fd44f,0x7cc00ff8,0x3a06202f, 0xd80dd003,0x54ff304f,0x82fd405f,0x03fc85fa,0x4fd80ff2,0x2001bee0, 0x3fd801ff,0x37ec0350,0x3f60ef98,0x881df306,0x7fcc00ff,0xf102fd42, 0x3f20044f,0x2a09fb04,0x80ffc03f,0x07f905fd,0x2a027ec0,0x32bf505f, 0x206f983f,0xffff13fc,0x19ffffff,0xbf505fa8,0xf5003fcc,0xf717fa0d, 0x3be25f77,0xfff305f8,0xffffffff,0x809ff109,0x8bf505fa,0xe8804ff8, 0xf106a20e,0x003fcc1d,0xfa800ff3,0x2202fd44,0x37ec00ff,0x8017c400, 0xff300efc,0x2a4fe987,0x82fd405f,0x03fc85fa,0x7fcc0ff2,0x001bee00, 0x3f6007fe,0x103ffd03,0x3fe817ff,0x3a05ffc4,0x00ff883f,0x2fd437ec, 0x8800ff10,0x0ffcc2ff,0x3604fd98,0x05ffc83f,0x7ec007f9,0xa82fd404, 0xf307f95f,0xf89fe40f,0x9aaaaabf,0x2a0bf500,0x801fe65f,0x7fdc2ff9, 0x07eefcc5,0x4c07f9fd,0x99efb999,0x2ff44099,0xfa82fd40,0x8017fa25, 0x3e601ee8,0x003fcc0e,0xfa800ff3,0x2202fd44,0x75cc40ff,0xf88000ff, 0x3fb8030d,0x3b3fff20,0x02fd45ff,0x2fd417ea,0x7f901fe4,0xf7017f60, 0x03ff000d,0x7d407fb0,0xb9fff704,0x3fee0dff,0x106ffdcf,0xeb9881ff, 0x05fa80ff,0x2e001fe2,0x4ffdcfff,0xf500fe80,0xfbfd97bf,0x800ff20d, 0x2fd404fd,0x07f95fa8,0xf90dfff1,0x0003fe27,0x2fd417ea,0xfd800ff3, 0x5fcfecdf,0x7dc6ffe8,0x3ea000ff,0x005fd805,0x97ea0bf5,0xe88005fd, 0xffdaacef,0xffff980e,0x34ffffff,0xffffffff,0x227d49ff,0x7fc405fa, 0xffffffff,0x3f60002f,0xfee987ff,0x7ff5400f,0x05fa83ef,0x5fa82fd4, 0x3f203fc8,0x401ff983,0xfffffffb,0x0ffc6fff,0x3221fec0,0x3a602fec, 0x200befff,0x0befffe9,0xffffff10,0x205fffff,0x1fe205fa,0x7fff4c00, 0x3ffb201c,0x7ffedc05,0xf903ff1e,0x027ec007,0xafd417ea,0xffd503fc, 0xff13fc81,0x0bf50001,0xfff997ea,0x4fffffff,0x4577ffe4,0x43ffc85f, 0x54006ff9,0x77fdc05f,0x3eeeeeee,0x57ea0bf5,0xeeeeeffb,0x32603eee, 0x201beffe,0xfffffff9,0xfff34fff,0x9fffffff,0x17ea27d4,0xffffff10, 0x00005bdf,0x32606f2a,0x262000ad,0x5017ea00,0x217ea0bf,0x0ff203fc, 0x3ee017f6,0xffffffff,0x400ffc6f,0x6ff4c3fd,0x00026002,0x3fe20026, 0x2defffff,0xd102fd40,0x0188000b,0x40037b70,0x1fe40018,0xa809fb00, 0x32bf505f,0xfc80403f,0x0001ff13,0x97ea0bf5,0xfffffff9,0x01304fff, 0x3e07fe60,0x2fd4003f,0x3ffffee0,0xf54fffff,0x7dd7ea0b,0xffffffff, 0x0011004f,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x98664400,0x059d951c,0x1aa8b2e6,0x00d4c2aa, 0x1a985540,0x98800666,0x4cccccc1,0x09880199,0x40026200,0x13530019, 0x02e00000,0x814c0133,0xc88bdca8,0x372e5932,0x5e54c00b,0x01988002, 0x26666660,0x44262009,0x26660009,0x88019999,0x20013109,0x99999998, 0x10199999,0x4ccc3795,0x99999999,0x26666609,0x20999999,0x21310019, 0x20066098,0x00cc0998,0x22002660,0x26666609,0x26201999,0x2004cc00, 0x00266098,0x019884cc,0x99882620,0x99999999,0xf88b2e09,0xff97f51f, 0xffc8bfff,0x2e3fe66f,0x0017ee5f,0x9afdcbfa,0xf8803fff,0xffff11ff, 0x7dffffff,0xd801bf20,0x07fa804f,0x6fffffdc,0x7fffff40,0x742fffff, 0x882ffc0f,0xffff887f,0x9f55faef,0x05fffffb,0xdfffffb1,0x17fec005, 0x7ffffcc0,0xfb84ffff,0x2200bf54,0xffffffff,0x2bf501df,0xff7005fa, 0xffffffff,0xff883fff,0xffff12ff,0xffffffff,0x7fffffc5,0x3e4fffff, 0xb3fd801f,0x301fe67f,0x3fcc1dff,0x00bff100,0x3ffe27fb,0xcfffffff, 0xf1037dc0,0x17fc01ff,0xfc803ff7,0x200bfea6,0x3fee2ff9,0xffffffff, 0xe893fa6f,0x39fff51e,0x3e25ff71,0x6fdc2adf,0x017ee0ef,0xafdcbfa0, 0xa806fff9,0xbff11fff,0xffd99999,0x03ff309f,0x8803ff10,0x3ff207ff, 0x20fffdbe,0xfffffffe,0x07fc1fff,0x3ff417fe,0xffb8eff4,0x19fff55f, 0xfd83ff91,0x1ffeb9cf,0x06fff880,0xeeeeff98,0x2e0efffe,0x200bf54f, 0xeeeeeff8,0xfa84ffff,0x2a00bf55,0xeffeeeee,0x6c1eeeee,0xff10abef, 0xdddddddd,0x777fc5dd,0x3eeeeeee,0x3f6007fe,0x1fe67fb3,0x4c0eff98, 0x3fe2007f,0x89fec02f,0xeeeeeeff,0x3fcc6ffe,0x205fff50,0x06fe87f9, 0xffb03fea,0x545fe801,0xeeeeeeee,0x0fb66ffe,0xf905ff50,0xfb01fe69, 0x0009703f,0x1fdff300,0x11fffd80,0x7e4401ff,0x804fe81f,0xffd806fb, 0x883ff307,0x3f6005fe,0x7fc0ff85,0x23fff4c5,0x5ff885fb,0xdf705ff5, 0x7ec0ffd4,0xfebfb806,0x303fcc01,0xaa7dc7ff,0x1ff1005f,0x2217fec0, 0x000bf509,0xfd004fd8,0x003ff105,0xf8003ff0,0xb3fd801f,0x4c1fe67f, 0x7f980dff,0x3fffe200,0x7c4ff600,0x0ffee00f,0x33f603ff,0x10bf704f, 0x5ff109ff,0x6409ff10,0xfb8000ff,0x2a08801f,0x2abf707f,0x1740005f, 0x7fcc0000,0x37e203fc,0x01ff11fe,0xfa83ff88,0x403fe807,0xf907fdfb, 0x401fea0d,0x3f2a0efa,0x4bfd0ccf,0x6c7feffc,0x2abf902f,0xfd9fe06f, 0x801ff305,0x404fb9fe,0x2fdc07f9,0x017ea9f7,0x36007fc4,0x17ea00ff, 0x009fb000,0x3fe207fa,0x01ff8001,0x6c00ffc0,0x3e67fb3f,0x205ff987, 0x3e2007f9,0x3f605fef,0xc801ff13,0xf81fec5f,0x7fb06f8f,0xfd07fea0, 0x417fd409,0xa8001ff9,0x4bb003ff,0x2bf506fa,0x1e4c05fa,0x951ca9dc, 0x072a039b,0x40df3ff3,0xf11feafa,0x09fb001f,0x7c403ff1,0x27be600f, 0x205d707f,0x7c400ff8,0x7fffe41f,0x3ea9fd1f,0x7fc7f8bf,0x3eabf500, 0x6547fa05,0x9803fe01,0x980ff17f,0x737d407f,0x2617ea9f,0x01ff10cc, 0x9e4c7fd0,0x59d955fa,0x7013f600,0x4459bff9,0xff8001ff,0x00ffc001, 0x33fd9fec,0x05ff98ff,0xf1003fcc,0x3605ff3f,0x801ff13f,0x42fdc7fa, 0xf01fd5f9,0x877ec03f,0xefd806fc,0x40027f40,0x36004ff9,0x7d417ea6, 0xfa80bf55,0x7ed7e405,0xfc84ffff,0x0febfcc3,0x23fd1fb0,0xff800ff8, 0x6409f902,0x447f404f,0xff70007f,0x3109fb00,0xa7ec33ff,0x44ff10ca, 0x557e607f,0x00bf604f,0x3f2037d4,0xf980bfa4,0xf727e407,0xff317ea9, 0x4007fc47,0x557ea5fb,0xfffffddf,0x404fd804,0x24fffffd,0xf8001ff8, 0x0ffc001f,0x3fd9fec0,0x2ffccff3,0x1003fcc0,0x203ff2ff,0x01ff13fd, 0x3fc47fc8,0x43fc97dc,0x7f4407f8,0x8801ffac,0x01bee4ff,0x001bfa20, 0xa82fd4dd,0xa80bf55f,0x77fe405f,0x40ffc88b,0xcbfcc3fc,0xfd5f883f, 0xb003fe23,0x03fcc0df,0x9fe403fd,0xfd0007f8,0x407fa809,0x81fec0ff, 0x807fc7f8,0x409f55f9,0xff9801fd,0xf70ffc02,0x443fcc0d,0x3ee0efc9, 0x7fccbf54,0x4007fc42,0x557ea6fa,0xfc98bfff,0x027ec02f,0x826bfa62, 0xf8001ff8,0x57fc001f,0x99999999,0x267fb3fe,0x00bff37f,0xf8801fe6, 0x3f617fa7,0xf801ff13,0x741fe85f,0xfa8bf50f,0xffff9805,0x27fea003, 0xd8001ff8,0x3f4000ff,0x57ea0bf5,0x2fd405fa,0x3a03ff20,0x261fe43f, 0xf70df37f,0x7fc47fa5,0xfedccccd,0x17f403ff,0xbf3037cc,0x5c003fc4, 0x1ff400ff,0x7f903fe0,0x3fd1fe20,0x2fd57ea0,0xf9801fd0,0x237d403f, 0xff301ff8,0xdfffffff,0xbf54fb81,0x3e20bfe6,0x27f9800f,0x05ff55fa, 0x4fd807fb,0xf103fd00,0xffffffff,0xffff8bff,0x42ffffff,0xffffffff, 0xfb3fffff,0x3fe7fe67,0x7f9800ff,0xf99fe200,0xf89fec2f,0xffd9980f, 0x3e22fc81,0x0bf23fc6,0x002ffe40,0x027ef7ec,0x000ffe40,0x20bf53fc, 0x80bf55fa,0x2fe405fa,0x1fe44fc8,0x40fe9fe6,0x7c47fa7d,0xffffffff, 0x5fb801df,0xfd103fc8,0x2003fc41,0x7cc02ffb,0x207fc00f,0x8ff102fc, 0x2bfb04fc,0x6f980ffa,0x4027fcc0,0x04fd83fd,0xfffffff3,0x4fb89fff, 0x05ff3bf5,0x26003fe2,0x2abf50ff,0x80bf707f,0x3fd004fd,0xffffff10, 0xf8bfffff,0xffffffff,0x7777fc2f,0xffeeeeee,0x3fe67fb3,0x805fecff, 0x3e2007f9,0xfb07fe47,0x3ffffe27,0x03ffffff,0x227d49f5,0x003fa1fd, 0x40037fe4,0x8006fff8,0xf0002ffa,0x5417ea1f,0xa80bf55f,0x827e405f, 0x21fe44fb,0x88ff27f9,0x7c47fa4f,0xffcaaabf,0x83fe2003,0x5fb00ff8, 0x32007f88,0x5fc802ff,0x7dc0ff80,0xf88ff102,0xaaffdc3f,0x3fa60dff, 0x4027f403,0x9999aff8,0x7f980ffb,0x5cdfd530,0xdffdf54f,0x003fe201, 0x55fa9fea,0x017ea0df,0x3fa009fb,0x001ff881,0x9999aff8,0x0ffc0999, 0x3fd9fec0,0x3e69fff3,0x03fcc03f,0xbfd0ff10,0xfff89fec,0x0cdeffff, 0x1fc9be20,0x06f89fdc,0x09ffff50,0x003ff700,0xa804ff98,0x543fe21a, 0x2abf505f,0x02fd405f,0x27dc0ff2,0x4ff30ff2,0xe8bee6f9,0x301ff11f, 0x7ec009ff,0x7d417ea2,0xb007f885,0x3fe005ff,0x5c0ff801,0x70ff101f, 0xffff9fff,0x33fffeab,0x7c404ffd,0xffff7007,0x07ffffff,0xff880ff3, 0x3fea9f72,0xff104fef,0x54df7001,0x2a0bf55f,0x027ec05f,0xff881fe8, 0x01ff8001,0x6c00ffc0,0x3e67fb3f,0x00ffdc4f,0x7c400ff3,0xfb2ff987, 0x0003fe27,0x21fe1fd0,0x009f55f9,0x3ff57ff1,0x007f9800,0xe802ff44, 0x547fe24f,0x2abf505f,0x02fd405f,0x27dc0ff2,0x8ff30ff2,0xfe8fd0fe, 0x2a01ff11,0xbf5003ff,0xffd817ec,0xffffffff,0x03ffb01f,0x7c01bea0, 0x880fd40f,0xfffd307f,0x37eabf57,0x803efffa,0xdfd005fa,0xfddddddd, 0x900ff30d,0x7d53ee9f,0x881ff99f,0x5fd800ff,0x82fd57ea,0x27ec05fa, 0xf881fe80,0x1ff8001f,0x400ffc00,0x267fb3fd,0x01dfb07f,0xf8801fe6, 0xfb1ff907,0x0003fe27,0x0bf35f90,0x400fe5fe,0x03ff66fd,0x4007f980, 0xfd000efd,0x9817fcc9,0x80bf500a,0x1fe405fa,0x1fe44fb8,0x17f71fe6, 0xf11fe89f,0x0ffe401f,0x6f88ff80,0x3bbbbb20,0x41eeffee,0x2000efd8, 0x1ff003fd,0xff100e98,0x57ea1880,0x800225fa,0x7f9803ea,0x260ffc40, 0x75fc807f,0xfb97ea9f,0x007fc40e,0x5fa8bfe6,0x17ea0bf5,0x3a009fb0, 0x01ff881f,0x4001ff80,0x3fd801ff,0x41fe67fb,0xff305ff8,0xd03fc400, 0x3e27fbbf,0x7d40000f,0x1fb03fbc,0x1ff700fd,0x3002ffc4,0x7fe400ff, 0xf31ec001,0x17fea05f,0xbf5017ea,0xf703fc80,0x7cc3fc89,0x0fdf7cc7, 0x07fc47fa,0x200dfd10,0x003fbbfc,0x7ec0ff10,0x17f4000e,0x4001fe80, 0x7d4007f8,0x0000bf55,0x2013f200,0x03fcc4fe,0xa7dcffa2,0x227f45fa, 0x7ec00ff8,0x5faafd46,0xfd80bf50,0x103fd004,0xff0003ff,0x01ff8003, 0x27fb3fd8,0x3fea07f9,0x2007f983,0x3fe607f8,0x01ff13ff,0xfddf8800, 0x0bf7f501,0xfa82ff98,0x0ff3003f,0x000bfea0,0x17fcc3f1,0xbf503fa0, 0x6405fa80,0xc89f703f,0x743fcc3f,0x11fe87ef,0xffa801ff,0xfedf8803, 0x0ff10000,0x20003fea,0xffb000ff,0x4406aa3d,0xafd4007f,0x260005fa, 0x01ff802a,0x3e60ffa8,0x1ffd5107,0x22fd53ee,0x3fe22ff9,0x7ff5cc40, 0x5faafd41,0xfd80bf50,0x103fd004,0xff0003ff,0x01ff8003,0x27fb3fd8, 0x7fec07f9,0x1003fcc1,0xfffc80ff,0x0001ff13,0x440dffd0,0x3a203fef, 0x03ff204f,0x2601fe60,0x4d8003ff,0x65417fcc,0x05fa86fd,0x3f202fd4, 0xfc89f703,0x7dc3fcc3,0xf11fe84f,0x1ffb001f,0x00bffb00,0xff83fc40, 0xffffffff,0x003fc40f,0x3fa7ffd3,0x800ff104,0x00bf55fa,0x2a037e40, 0x7ff1007f,0x7fffffcc,0x2e2fffff,0xf90bf54f,0x3fffe21d,0x2fffffff, 0x0bf55fa8,0x9fb017ea,0x2207fa00,0xffffffff,0x3fe6ffff,0x00ffc001, 0x33fd9fec,0x6ff880ff,0x7fffffcc,0xff14ffff,0x227ffd00,0xb80000ff, 0x7ff404ff,0x201bf601,0x7f9806fe,0xfffffb80,0xffffffff,0x03dd3010, 0xf5037df9,0x405fa80b,0x89f703fc,0x43fcc3fc,0x1fe81ff9,0xf1001ff1, 0x5ff500bf,0x43fc4000,0xfffffff8,0x7d40ffff,0x3a088006,0x00ff104f, 0x09d54ea8,0x2037e400,0x3f2004fd,0x3ffffe66,0x5c0ceeff,0x3a0bf54f, 0xfffff14f,0x2017bdff,0x20bf55fa,0x27ec05fa,0xf881fe80,0xffffffff, 0x07fe6fff,0xb003ff00,0x7ccff67f,0x24ff9807,0xfffffff9,0x0ff14fff, 0x3e27ff30,0xf980000f,0x03fe402f,0xf3003ff7,0x07f9809f,0xffffffb8, 0x0fffffff,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x201ee980, 0x21999999,0x99999999,0x64c01999,0x44000002,0x261bcecb,0xc980acdb, 0x2a059302,0x3a20bcec,0x2605930e,0x9503972c,0xa88037bd,0x9802cddc, 0xca801bdb,0xca800bdd,0xb9800bce,0x65440bdd,0x82c981cd,0x03950cc9, 0x333200cc,0x0ccccccc,0x99304004,0x00399103,0x65472610,0x2f6e61bd, 0xeca8e4c0,0x3016542c,0x26072e59,0x0219703c,0x32272600,0x225970ad, 0x20032a2c,0x880b223b,0x2a028009,0x44017300,0x575100aa,0xc9815c01, 0x00554402,0xff980391,0xfffff302,0x2666e1ff,0xa9999999,0x4013ea00, 0xd92cecb8,0xffffff50,0xfffff77f,0x504fb85f,0xfffe98bf,0x1ff12fff, 0xafd413ee,0x7fff43fe,0xff503fff,0x40bfffff,0x0ffffffd,0xfffffd88, 0xfffd302f,0x7ec05fff,0xf32fffff,0xa89fffff,0x917fcc5f,0x203fc07f, 0xffffffff,0x4c3b20ff,0xfd83b61b,0x4005fd86,0xfb7f55ea,0xff31ffff, 0x5fd49fff,0x25fffffc,0x4bf606f9,0x0ffc83fc,0x17d93fc4,0x3fafea00, 0x6c9fd0ff,0xa80bf11f,0xc803fa3f,0x41fec06f,0x7fecc6fa,0x7ffdc0df, 0x7f7fcc6f,0xb04fd82f,0x7f7e40ff,0x805f104f,0x99102ff9,0x01499999, 0x27d40130,0x7ffffd40,0x7fc42fff,0xdfff930a,0x41ff7117,0x8bf504fb, 0xfda8befe,0x3ee7c89f,0x3fabf504,0x54477f22,0x5ffc41ff,0xb05ff731, 0xbf9317df,0xb317dfd0,0x7dfd03ff,0x903ffb51,0x3ff665df,0xfd51cffc, 0xff32fd49,0x3e03fc85,0x4ccccc07,0x7e44ff99,0xfeffffef,0xa8ffe20e, 0xfc8800ff,0x5fff55ff,0x5bfdfd51,0x3ea3ff71,0xffb89cff,0x3e207fa2, 0x3fa1bea7,0xf927d42f,0xfa8039ff,0x3b24bcff,0x3fb9be23,0x1fdcdf10, 0xf501bf20,0x217fd47f,0x25fb8afe,0xe8bf25f8,0x7d4bd10e,0xfff884ff, 0x3fa4e883,0x64d7c720,0x14000000,0x7d401300,0x977fcc04,0x7e40ffea, 0x703fff03,0xa827dcdf,0x5c1bee5f,0x27dcd34f,0xe87a5fa8,0x5c3ec81f, 0xa89fb05f,0x543fd06f,0x45fb80ff,0x8df706fb,0xffa80ffa,0x50ff884f, 0x20bfe6bf,0x01fe03fc,0xfd82fec0,0x0fffdbef,0xff88ffa8,0x7ffed402, 0x30bfea1c,0x27fb0dff,0x4fc82ffa,0x13ee13ee,0x7f7c41ff,0x32617ec4, 0xf502dfff,0x4fc8005f,0x47fa07fa,0x098806f9,0xfabffa80,0x3a27cc2f, 0x2fa8220f,0x367e9884,0xbfb84f8b,0x26f9806f,0xffefeff8,0x99999992, 0x39501999,0x004c0050,0x4fe809f5,0x4c44ffe8,0x220dfb00,0x209f70ff, 0x80bfa5fa,0x3ee2d8ff,0x07cbf504,0x22001bfb,0xc8bf7009,0x6c15303f, 0x41ff104f,0x87fe02fe,0x3ffa04fc,0x3ea9fb00,0xf902ff9d,0x4003fc07, 0x7fb00efc,0xf900ff88,0x2e209fbb,0xa80beffe,0x907ff07f,0x5c1fea9f, 0x3a1fe25f,0xf717ec1f,0x207f8df7,0x0bfffeb8,0x7c001fea,0xfb8df51f, 0x3320bfa5,0xcccccccc,0xffffa81c,0x7e42fa82,0xd98fd101,0xf887ffff, 0x03f97f84,0x6cc077e4,0x3ffe0aef,0x0fffffff,0x00283fc8,0x77774426, 0x1eeeeffe,0xafc81ff1,0x6dd4407f,0xaaaaadff,0x09f71fea,0x00ff97ea, 0x9f70bff6,0x0fa77ea0,0x017bfff5,0x7fee5440,0xd000ff45,0x5555559f, 0x007fc3ff,0x017ec5fb,0x55555df9,0x3beabf95,0x4ff206ff,0xcffcccca, 0x3ee03ccc,0x641fe00f,0x1bffa02f,0x00efffdc,0x0ffc1bea,0x06faa7dc, 0x22fe8bf5,0x24fa86f9,0xf30fe8fd,0x3ff6600b,0x000df53f,0x33fe9bea, 0x217f23ff,0xfffffff8,0xf902ffff,0x90fea0bf,0x43df501f,0x7d8acff8, 0xa7dc4f88,0x3ae605f9,0x1fe7cc0e,0x26666666,0x07f904ff,0xf884c005, 0xffffffff,0xb8df32ff,0xd881ff2f,0xfffffffe,0xffffffff,0x3ea09f73, 0xfc80ff15,0xf504fb83,0x3fa607df,0xb302efff,0xbfdfffff,0x3e000ff8, 0xffffffff,0x80ff12ff,0x807fe3fc,0xfffffffb,0xfff56fff,0x4ff209fd, 0xfffffffc,0xff505fff,0xa82fcc03,0x0ffea04f,0xa8017fe4,0x701ff05f, 0x5417ea9f,0xf92fd45f,0xb7cdf107,0x005f92fc,0xbf55ff98,0x453f2000, 0x4cbfa1ff,0xaaaa80ff,0x0aaaaaaa,0x83ffffa8,0x5c3f45f9,0x117d40df, 0xe89f10ff,0x5003fa0f,0xfcb7c47f,0x205fd802,0x200283fc,0x2e666609, 0x509999df,0xff1fccbf,0x567ffcc3,0x33339fb1,0x3ee13333,0x3e2bf705, 0x20bf600f,0x0bf705fb,0x3fffae60,0x5e77fcc3,0x1ff8bf51,0x266bfe00, 0x10999999,0x17ec01ff,0x77e405ff,0xaaaaaaaa,0xff33ff52,0x2a67f903, 0xaabffaaa,0x02ff982a,0x2fd80ff8,0x203fffa0,0x402efffa,0x01ff05fa, 0x417ea9f7,0x87fc45fa,0x33fb00fe,0x7f53ea9f,0xfffb5000,0x20017ea7, 0x313f26f9,0x013f21ff,0x3ea00262,0xd83ffaaf,0x643fdadf,0x55df104f, 0x4f881ffd,0x49f517ea,0x507f23fa,0x77e401c3,0x0a0ff200,0x3ea00980, 0x745bea04,0x9fd07fc5,0xb8013f60,0x7cbf905f,0x203fa01f,0x0bf905fb, 0xe8dfb100,0xe8bf904f,0x7457302f,0x0ffc003f,0x27ec1fd0,0x2001ffb0, 0x21bf25fa,0x01fe03fc,0x6c013fe2,0x903fcc4f,0x540bf9bf,0xa80cfffd, 0x701ff05f,0x5417ea9f,0xf9afc85f,0x3eefee05,0x0bf1df12,0x2effeb88, 0x74002fd4,0x2e0df31f,0x9003fa4f,0x3ffa80df,0xd710ffea,0xfffa85df, 0x3fae4fff,0x7c42faad,0x3fe0bf64,0x17ffff60,0x03fee000,0x00507f90, 0x09f5004c,0x07ec7fcc,0x07fc4ff1,0xf8837fc4,0x3a0df50f,0x4c13f65f, 0x20df507f,0x1fd105fd,0x7fc1ff10,0xfc8bfb01,0x7ec9fb04,0x6c1df306, 0xc8ff304f,0x5fff106f,0x2fd4bf60,0x07f913fa,0x3fa203fc,0x3fff6005, 0xa81fffec,0x02ff88ff,0x16fffe4c,0x03fe0bf5,0x82fd53ee,0xcdf985fa, 0x377e602f,0x0ff3fa0f,0x0efffecc,0x54005fa8,0xd803f64f,0xc80bf30f, 0x41fec06f,0x4c0205fa,0x81aaaaaa,0x3a235000,0xb885d705,0xfa80000a, 0x83fc801f,0xa8026002,0x7effc04f,0x3fa37dc1,0x84fffd83,0x0bfe64fd, 0x7fccbff7,0x9827f4c3,0x2ffdc1ff,0xbf709f90,0xffc83fd8,0x2617fc45, 0x2ffe21ff,0x3e61ff40,0x227f4c3f,0x7f4c3ff8,0x37d41eff,0x1ff98bf5, 0x07f80ff2,0xfb002fec,0xfbdfffbd,0x517fc41f,0xf71001ff,0x417eabff, 0x54fb80ff,0x417ea0bf,0xfe807ffe,0x07ffdc6f,0x0067ffe4,0x1aa817ea, 0x403fa9ba,0x807f25f8,0x20280098,0x00000001,0x00000000,0x017fcc00, 0x00283fc8,0x04fa8026,0x3ee27fe4,0x5effd41f,0xefe9bffd,0xfd86ffcc, 0x5fcfecdf,0x7f67ffe4,0x6ffec04f,0x205fcfec,0xfeccfff8,0x5effd41f, 0xb86fdfec,0x4ffdcfff,0xfdcfffb8,0x9fff906f,0x3ea0bffd,0x8dffecef, 0xffeceffd,0x3f217ea2,0x7f80ff26,0x3bbbfee0,0x2e3eeeee,0x2e41510e, 0x1bf617f6,0x3eabb500,0xf701ff05,0x7d417ea9,0x009ff705,0xff987ff9, 0x4005d906,0x93fa05fa,0x44006209,0x000004c1,0x00000000,0x00000000, 0x13fe2000,0x0283fc80,0x20000260,0xffcdfff9,0xfffb704f,0x7ffec43b, 0xfff900be,0xd50bf15d,0x2007dfff,0xf8aefffc,0x7fff4c05,0xffb701df, 0x207fe3df,0x01cfffe9,0x2fbfffa6,0x3fffaa00,0x7ff4c03e,0x7ff644ef, 0x42fd42cf,0x07f94fe8,0xfff700cc,0x9fffffff,0x0ffb8000,0x8003ff88, 0x3fe0bf50,0xbf54fb80,0x7c417ea0,0x1ff9801f,0x00103ff8,0x7f40bf50, 0x00000004,0x00000000,0x00000000,0x22000000,0x7e4005fe,0x42600283, 0xfffffff8,0x3ba2ffff,0x02efffdb,0x00880188,0x31000260,0x00260001, 0x20019880,0x03100018,0x88001300,0x00980009,0x000000c4,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x0bfb0000,0x0507f900,0xfff884c0,0xffffffff,0x00130322, 0x00000000,0x00000000,0x00000000,0x00000000,0x10000000,0x33333333, 0x26662133,0x09999999,0x81b88133,0x2a133099,0xa9804c1a,0x02a98201, 0xa8aa2555,0x3723550a,0x2aaaaaa3,0xbb300000,0xbbbbbbbb,0x00007bbb, 0x00000000,0x00000000,0x00000000,0x00000000,0x77777fdc,0xfc83eeee, 0xaaaaac83,0x00caaaaa,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x7e400000,0xffffffff,0xfffff95f,0x3abfffff,0x3bfbee3f, 0x97fcffa0,0x2a1fc3fe,0x21cfffff,0x307fe669,0xe9be63ff,0x3f69fb1f, 0xffffff14,0x3ffffea3,0xffffffff,0xdddddd35,0x9ddddddd,0x00000000, 0x00000000,0x00000000,0x00000000,0x7fdc0000,0xffffffff,0x0003fc84, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x80000000, 0xeeeeeeeb,0xddd74eee,0xbfdddddd,0x362f8ffa,0x97fcffa3,0x8fbe63fe, 0xffffffff,0x2fd47ffe,0x26f98ff6,0x2e9fb1fe,0xddddd12c,0x2eeee63d, 0xbbbbbbbb,0x0000002b,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x40000000,0x2a7fd5f9,0x27fd3546,0x360f62ff,0x75cc3d1f, 0xfb83ffff,0x00009f11,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x5f980000,0xb83e23fb,0x0fecbf65, 0x9bf6ea3f,0x0026a600,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x3f2bf300,0x87f2fb60, 0x361f90fb,0x0073bf24,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x80000000,0xfffffffc,0x26005fff, 0x9d50b55f,0x096a6983,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x3fff2000,0x5fffffff, 0x0017e600,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, }; static signed short stb__arial_27_latin_ext_x[560]={ 0,2,1,0,0,1,1,1,1,1,0,1,2,0, 2,0,1,2,0,1,0,1,0,1,0,1,2,2,1,1,1,1,1,-1,1,1,1,1,1,1,1,2,0,1, 1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,1,0,0,0,-1,1,0,1,0,0,0,0,0,1,1, -2,1,1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,2,0,1,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2,1,0,0,-1, 2,0,0,0,0,1,1,0,0,-1,1,0,0,0,2,1,0,2,1,1,0,1,1,1,0,1,-1,-1,-1,-1, -1,-1,0,1,1,1,1,1,0,1,-1,0,-1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,2,-1,0,0,1,0,0,0,0,0,0,1,1,1,1,1,0,1,0, -1,0,-1,0,-1,0,1,0,1,0,1,0,1,0,1,0,-1,0,1,0,1,0,1,0,1,0,1,0,1,0, 1,0,1,0,1,0,1,1,0,0,-1,-1,-1,-1,-1,-1,1,1,2,2,2,1,0,-2,1,1,1,1,0,1, -1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0, 1,0,1,0,1,0,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0, 0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,0,3,3,3, 3,3,3,3,3,3,3,3,3,3,1,0,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,-1,0,-1,-1,1, 0,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,-1,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3, }; static signed short stb__arial_27_latin_ext_y[560]={ 21,3,3,3,2,3,3,3,3,3,3,6,18,13, 18,3,3,3,3,3,3,3,3,3,3,3,8,8,6,8,6,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,24,3,8,3,8,3,8,3,8,3,3, 3,3,3,8,8,8,8,8,8,8,4,8,8,8,8,8,8,3,3,3,10,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,21,8,3,3,6,3, 3,3,3,3,3,9,8,13,3,0,3,6,3,3,3,8,3,11,20,3,3,9,3,3,3,8,-1,-1,-1,-1, 0,-1,3,3,-1,-1,-1,0,-1,-1,-1,0,3,-1,-1,-1,-1,-1,0,7,3,-1,-1,-1,0,-1,3,3,3,3, 3,3,3,3,8,8,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,7,7,3,3,3,3,3,3,3, 0,4,-1,3,3,8,-1,3,-1,3,-1,4,-1,3,-1,3,3,3,0,4,-1,3,-1,4,3,8,-1,3,-1,3, -1,3,0,4,3,2,-1,-1,3,3,-1,3,0,4,-1,3,3,3,-1,8,3,3,-1,3,3,3,8,-1,-1,3, 3,3,3,3,3,3,3,-1,3,3,8,-1,3,3,3,8,0,4,-1,3,-1,3,3,8,-1,3,3,8,-1,3, -1,3,-1,3,3,8,-1,3,3,4,-1,3,3,4,-1,3,0,4,-1,3,-1,3,-1,3,3,8,-1,3,-1,3, 0,-1,3,-1,4,-1,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,5,5,3,5,5,5, 5,5,5,5,5,5,5,5,5,5,3,8,5,5,5,5,5,5,5,5,5,5,5,5,5,3,8,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,-1,3,-1,3,-1, 3,-1,3,-1,0,-1,-1,-1,-1,-1,-1,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,-4,-2,-1,3,-1,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5, }; static unsigned short stb__arial_27_latin_ext_w[560]={ 0,3,7,14,13,20,15,3,7,7,9,12,3,8, 3,7,12,8,13,12,13,12,13,12,13,12,3,3,12,12,12,12,23,18,14,16,16,14,13,17,15,3,11,16, 12,18,15,17,15,17,17,14,15,15,16,23,16,16,15,6,7,6,11,15,5,13,12,12,12,13,8,12,11,3, 6,11,3,18,11,13,12,12,8,12,7,11,12,18,12,12,12,8,3,8,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,0,4,12,13,13,15, 3,13,8,18,9,11,12,8,18,15,8,13,8,8,5,12,14,3,6,5,9,11,19,19,20,13,18,18,18,18, 18,18,23,16,14,14,14,14,6,6,9,7,18,15,17,17,17,17,17,12,18,15,15,15,15,16,15,14,13,13, 13,13,13,13,21,12,13,13,13,13,5,5,9,7,13,11,13,13,13,13,13,13,13,11,11,11,11,12,12,12, 18,13,18,13,20,15,16,12,16,12,16,12,16,12,16,15,18,14,14,13,14,13,14,13,14,13,14,13,17,12, 17,12,17,12,17,12,15,11,18,12,9,9,9,9,8,8,7,6,3,3,15,9,14,9,16,11,11,12,6,12, 7,12,7,12,7,13,6,15,11,15,11,15,11,14,16,11,17,13,17,13,17,13,23,22,17,8,17,8,17,9, 14,12,14,12,14,12,14,12,15,7,15,10,15,7,15,11,15,11,15,11,15,11,15,11,15,14,23,18,16,12, 16,15,12,15,12,15,12,7,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,17,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,20,16,13,13,13,13,13,13,13,13,13,13,13,13,13,19,15,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,18,13,9,8,17, 13,15,11,15,11,15,11,15,11,15,11,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,18,13,23,21,18,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13, }; static unsigned short stb__arial_27_latin_ext_h[560]={ 0,18,7,19,22,19,19,7,24,24,8,13,7,3, 3,19,19,18,18,19,18,19,19,18,19,19,13,17,13,9,13,18,24,18,18,19,18,18,18,19,18,18,19,18, 18,18,18,19,18,20,18,19,18,19,18,18,18,18,18,23,19,23,10,2,4,14,19,14,19,14,18,19,18,18, 24,18,18,13,13,14,18,18,13,14,18,14,13,13,13,19,13,24,24,24,5,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,0,18,23,19,13,18, 24,24,4,19,10,12,8,3,19,3,7,15,10,10,4,18,23,3,6,10,10,12,19,19,19,19,22,22,22,22, 21,22,18,23,22,22,22,21,22,22,22,21,18,22,23,23,23,23,22,11,19,23,23,23,22,22,18,19,19,19, 19,19,19,19,14,18,19,19,19,19,18,18,18,18,19,18,19,19,19,19,19,11,15,19,19,19,19,24,23,24, 21,18,22,19,23,18,23,19,23,19,23,18,23,19,22,19,18,19,21,18,22,19,22,18,24,19,22,19,23,24, 23,24,22,23,23,25,22,22,18,18,22,18,21,17,22,18,24,24,22,13,19,24,23,24,23,23,13,22,22,23, 23,18,18,18,18,18,18,22,18,23,18,22,18,18,19,19,22,18,23,19,23,19,19,14,22,18,23,18,22,18, 23,19,23,19,23,18,23,19,25,24,22,19,18,18,23,19,22,18,23,19,23,19,23,19,24,19,22,18,22,24, 21,22,18,22,17,22,18,18,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,19,16,16,24,16,16,16, 16,16,16,16,16,16,16,16,16,16,19,14,16,16,16,16,16,16,16,16,16,16,16,16,16,19,14,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,22,19,22,18,23, 19,23,19,23,22,23,23,23,23,23,23,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,25,24,22,19,23,19,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16, }; static unsigned short stb__arial_27_latin_ext_s[560]={ 510,161,263,1,491,136,365,250,285,198,502, 240,271,325,317,453,336,165,126,349,112,461,86,140,303,453,391,506,293,224,369, 200,247,213,232,396,263,321,336,378,350,366,366,370,387,58,400,348,416,323,77, 333,296,317,95,432,456,473,490,195,503,503,481,350,296,146,238,160,225,173,312, 199,284,280,121,251,247,306,325,187,187,174,382,133,153,88,337,350,280,212,253, 228,194,206,282,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24, 24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,510,1,353, 251,266,457,117,157,308,1,465,407,237,325,265,334,254,38,456,493,302,273,467, 321,275,475,446,395,413,433,466,487,234,111,180,199,255,271,164,450,323,338,353, 274,500,505,141,237,61,192,219,144,336,271,35,433,284,58,1,400,439,306,384, 184,170,156,142,128,114,100,66,96,58,44,30,16,378,364,326,50,447,352,418, 404,390,376,362,419,52,324,312,300,288,76,29,144,289,312,16,181,90,80,127, 123,162,98,202,286,304,499,87,30,244,1,308,230,53,439,151,216,171,240,1, 72,19,49,416,89,123,434,447,20,176,208,188,132,166,154,245,14,104,145,109, 102,507,236,487,237,237,293,483,17,224,426,419,482,495,20,53,33,501,412,46, 290,486,369,6,218,400,35,482,157,130,109,37,381,1,16,341,201,253,123,465, 207,401,263,385,474,354,227,321,299,289,74,33,186,55,87,336,370,179,111,164, 426,111,169,74,215,42,254,128,432,87,438,384,215,220,368,473,148,1,71,498, 18,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,421,24,24,271, 24,24,24,24,24,24,24,24,24,24,24,24,24,461,100,24,24,24,24,24, 24,24,24,24,24,24,24,24,195,117,24,24,24,24,24,24,24,24,24,24, 24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,68,46, 113,26,319,395,337,409,303,479,366,382,394,410,422,438,24,24,24,24,24,24, 24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24, 24,24,24,1,62,455,266,252,60,24,24,24,24,24,24,24,24,24,24,24, 24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24, 24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24, 24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24, 24,24,24,24,24,24,24,24,24, }; static unsigned short stb__arial_27_latin_ext_t[560]={ 1,158,191,118,51,98,75,191,1,1,177, 177,191,191,191,75,98,158,158,98,158,98,118,158,118,118,177,158,177,191,177, 158,1,158,158,118,158,158,158,118,158,158,118,158,158,158,158,118,158,75,158, 118,158,118,158,158,158,158,158,27,98,1,177,191,191,177,118,177,118,177,158, 118,158,158,1,158,158,177,177,177,158,158,177,177,158,177,177,177,177,118,177, 1,1,1,191,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,1,158,1, 118,177,138,1,1,191,138,177,177,191,191,118,191,191,177,177,177,191,138,1, 191,191,177,177,177,118,118,118,118,51,51,51,51,75,51,138,1,51,51,51, 75,27,51,75,75,138,75,27,27,27,27,75,177,118,27,27,27,51,51,138, 118,118,118,118,118,118,118,177,138,118,118,118,118,138,138,138,158,98,138,98, 98,98,98,98,177,177,98,98,98,98,1,27,1,75,138,75,98,27,138,27, 98,27,98,27,138,27,75,75,98,138,98,75,138,75,75,75,138,1,98,75, 118,51,1,27,1,75,27,27,1,75,75,138,138,75,138,75,177,75,138,1, 1,27,177,98,1,27,1,27,27,177,51,51,1,1,138,138,138,118,138,138, 51,138,27,158,51,138,158,75,98,51,138,51,75,51,98,75,177,51,138,27, 138,51,138,27,98,27,98,27,138,27,98,1,1,51,98,138,138,27,98,51, 138,27,98,27,98,27,98,1,98,51,138,51,1,75,51,138,51,177,51,138, 158,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,75,177,177,1, 177,177,177,177,177,177,177,177,177,177,177,177,177,75,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,98,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,75,98, 75,158,1,75,1,75,1,51,1,1,1,1,1,1,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,1,1,51,98,27,98,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177, }; static unsigned short stb__arial_27_latin_ext_a[560]={ 107,107,137,215,215,344,258,74, 129,129,150,226,107,129,107,107,215,215,215,215,215,215,215,215, 215,215,107,107,226,226,226,215,393,258,258,279,279,258,236,301, 279,107,193,258,215,322,279,301,258,301,279,258,236,279,258,365, 258,258,236,107,107,107,181,215,129,215,215,193,215,215,107,215, 215,86,86,193,86,322,215,215,215,215,129,193,107,215,193,279, 193,193,193,129,100,129,226,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,107,129,215,215,215,215,100,215, 129,285,143,215,226,129,285,214,155,212,129,129,129,223,208,107, 129,129,141,215,322,322,322,236,258,258,258,258,258,258,387,279, 258,258,258,258,107,107,107,107,279,279,301,301,301,301,301,226, 301,279,279,279,279,258,258,236,215,215,215,215,215,215,344,193, 215,215,215,215,107,107,107,107,215,215,215,215,215,215,215,212, 236,215,215,215,215,193,215,193,258,215,258,215,258,215,279,193, 279,193,279,193,279,193,279,238,279,215,258,215,258,215,258,215, 258,215,258,215,301,215,301,215,301,215,301,215,279,215,279,215, 107,107,107,107,107,107,107,86,107,107,284,172,193,86,258,193, 193,215,86,215,86,215,113,215,129,215,86,279,215,279,215,279, 215,234,280,215,301,215,301,215,301,215,387,365,279,129,279,129, 279,129,258,193,258,193,258,193,258,193,236,107,236,145,236,107, 279,215,279,215,279,215,279,215,279,215,279,215,365,279,258,193, 258,236,193,236,193,236,193,86,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,291,290,290,215,290,290,290,290,290, 290,290,290,290,290,290,290,290,332,254,290,290,290,290,290,290, 290,290,290,290,290,290,290,330,259,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,258,215,107,86,301,215,279,215,279,215,279, 215,279,215,279,215,290,290,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290,290, 290,290,258,215,387,344,301,236,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290,290, 290,290,290,290,290,290,290,290, }; // Call this function with // font: NULL or array length // data: NULL or specified size // height: STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT or STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT_POW2 // return value: spacing between lines static void stb_font_arial_27_latin_ext(stb_fontchar font[STB_FONT_arial_27_latin_ext_NUM_CHARS], unsigned char data[STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT][STB_FONT_arial_27_latin_ext_BITMAP_WIDTH], int height) { int i,j; if (data != 0) { unsigned int *bits = stb__arial_27_latin_ext_pixels; unsigned int bitpack = *bits++, numbits = 32; for (i=0; i < STB_FONT_arial_27_latin_ext_BITMAP_WIDTH*height; ++i) data[0][i] = 0; // zero entire bitmap for (j=1; j < STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT-1; ++j) { for (i=1; i < STB_FONT_arial_27_latin_ext_BITMAP_WIDTH-1; ++i) { unsigned int value; if (numbits==0) bitpack = *bits++, numbits=32; value = bitpack & 1; bitpack >>= 1, --numbits; if (value) { if (numbits < 3) bitpack = *bits++, numbits = 32; data[j][i] = (bitpack & 7) * 0x20 + 0x1f; bitpack >>= 3, numbits -= 3; } else { data[j][i] = 0; } } } } // build font description if (font != 0) { float recip_width = 1.0f / STB_FONT_arial_27_latin_ext_BITMAP_WIDTH; float recip_height = 1.0f / height; for (i=0; i < STB_FONT_arial_27_latin_ext_NUM_CHARS; ++i) { // pad characters so they bilerp from empty space around each character font[i].s0 = (stb__arial_27_latin_ext_s[i]) * recip_width; font[i].t0 = (stb__arial_27_latin_ext_t[i]) * recip_height; font[i].s1 = (stb__arial_27_latin_ext_s[i] + stb__arial_27_latin_ext_w[i]) * recip_width; font[i].t1 = (stb__arial_27_latin_ext_t[i] + stb__arial_27_latin_ext_h[i]) * recip_height; font[i].x0 = stb__arial_27_latin_ext_x[i]; font[i].y0 = stb__arial_27_latin_ext_y[i]; font[i].x1 = stb__arial_27_latin_ext_x[i] + stb__arial_27_latin_ext_w[i]; font[i].y1 = stb__arial_27_latin_ext_y[i] + stb__arial_27_latin_ext_h[i]; font[i].advance_int = (stb__arial_27_latin_ext_a[i]+8)>>4; font[i].s0f = (stb__arial_27_latin_ext_s[i] - 0.5f) * recip_width; font[i].t0f = (stb__arial_27_latin_ext_t[i] - 0.5f) * recip_height; font[i].s1f = (stb__arial_27_latin_ext_s[i] + stb__arial_27_latin_ext_w[i] + 0.5f) * recip_width; font[i].t1f = (stb__arial_27_latin_ext_t[i] + stb__arial_27_latin_ext_h[i] + 0.5f) * recip_height; font[i].x0f = stb__arial_27_latin_ext_x[i] - 0.5f; font[i].y0f = stb__arial_27_latin_ext_y[i] - 0.5f; font[i].x1f = stb__arial_27_latin_ext_x[i] + stb__arial_27_latin_ext_w[i] + 0.5f; font[i].y1f = stb__arial_27_latin_ext_y[i] + stb__arial_27_latin_ext_h[i] + 0.5f; font[i].advance = stb__arial_27_latin_ext_a[i]/16.0f; } } } #ifndef STB_SOMEFONT_CREATE #define STB_SOMEFONT_CREATE stb_font_arial_27_latin_ext #define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_arial_27_latin_ext_BITMAP_WIDTH #define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT #define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_arial_27_latin_ext_BITMAP_HEIGHT_POW2 #define STB_SOMEFONT_FIRST_CHAR STB_FONT_arial_27_latin_ext_FIRST_CHAR #define STB_SOMEFONT_NUM_CHARS STB_FONT_arial_27_latin_ext_NUM_CHARS #define STB_SOMEFONT_LINE_SPACING STB_FONT_arial_27_latin_ext_LINE_SPACING #endif
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE134_Uncontrolled_Format_String__wchar_t_environment_fprintf_83_goodB2G.cpp Label Definition File: CWE134_Uncontrolled_Format_String.label.xml Template File: sources-sinks-83_goodB2G.tmpl.cpp */ /* * @description * CWE: 134 Uncontrolled Format String * BadSource: environment Read input from an environment variable * GoodSource: Copy a fixed string into data * Sinks: fprintf * GoodSink: fwprintf with "%s" as the second argument and data as the third * BadSink : fwprintf with data as the second argument * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE134_Uncontrolled_Format_String__wchar_t_environment_fprintf_83.h" #define ENV_VARIABLE L"ADD" #ifdef _WIN32 #define GETENV _wgetenv #else #define GETENV getenv #endif namespace CWE134_Uncontrolled_Format_String__wchar_t_environment_fprintf_83 { CWE134_Uncontrolled_Format_String__wchar_t_environment_fprintf_83_goodB2G::CWE134_Uncontrolled_Format_String__wchar_t_environment_fprintf_83_goodB2G(wchar_t * dataCopy) { data = dataCopy; { /* Append input from an environment variable to data */ size_t dataLen = wcslen(data); wchar_t * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ wcsncat(data+dataLen, environment, 100-dataLen-1); } } } CWE134_Uncontrolled_Format_String__wchar_t_environment_fprintf_83_goodB2G::~CWE134_Uncontrolled_Format_String__wchar_t_environment_fprintf_83_goodB2G() { /* FIX: Specify the format disallowing a format string vulnerability */ fwprintf(stdout, L"%s\n", data); } } #endif /* OMITGOOD */
// Copyright (c) 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 "media/midi/midi_manager_mac.h" #include <stddef.h> #include <algorithm> #include <iterator> #include <string> #include <CoreAudio/HostTime.h> #include "base/bind.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include "media/midi/midi_service.h" #include "media/midi/task_service.h" using base::IntToString; using base::SysCFStringRefToUTF8; using midi::mojom::PortState; using midi::mojom::Result; // NB: System MIDI types are pointer types in 32-bit and integer types in // 64-bit. Therefore, the initialization is the simplest one that satisfies both // (if possible). namespace midi { namespace { // Maximum buffer size that CoreMIDI can handle for MIDIPacketList. const size_t kCoreMIDIMaxPacketListSize = 65536; // Pessimistic estimation on available data size of MIDIPacketList. const size_t kEstimatedMaxPacketDataSize = kCoreMIDIMaxPacketListSize / 2; enum { kDefaultRunnerNotUsedOnMac = TaskService::kDefaultRunnerId, kClientTaskRunner, }; MidiPortInfo GetPortInfoFromEndpoint(MIDIEndpointRef endpoint) { std::string manufacturer; CFStringRef manufacturer_ref = NULL; OSStatus result = MIDIObjectGetStringProperty( endpoint, kMIDIPropertyManufacturer, &manufacturer_ref); if (result == noErr) { manufacturer = SysCFStringRefToUTF8(manufacturer_ref); } else { // kMIDIPropertyManufacturer is not supported in IAC driver providing // endpoints, and the result will be kMIDIUnknownProperty (-10835). DLOG(WARNING) << "Failed to get kMIDIPropertyManufacturer with status " << result; } std::string name; CFStringRef name_ref = NULL; result = MIDIObjectGetStringProperty(endpoint, kMIDIPropertyDisplayName, &name_ref); if (result == noErr) { name = SysCFStringRefToUTF8(name_ref); } else { DLOG(WARNING) << "Failed to get kMIDIPropertyDisplayName with status " << result; } std::string version; SInt32 version_number = 0; result = MIDIObjectGetIntegerProperty( endpoint, kMIDIPropertyDriverVersion, &version_number); if (result == noErr) { version = IntToString(version_number); } else { // kMIDIPropertyDriverVersion is not supported in IAC driver providing // endpoints, and the result will be kMIDIUnknownProperty (-10835). DLOG(WARNING) << "Failed to get kMIDIPropertyDriverVersion with status " << result; } std::string id; SInt32 id_number = 0; result = MIDIObjectGetIntegerProperty( endpoint, kMIDIPropertyUniqueID, &id_number); if (result == noErr) { id = IntToString(id_number); } else { // On connecting some devices, e.g., nano KONTROL2, unknown endpoints // appear and disappear quickly and they fail on queries. // Let's ignore such ghost devices. // Same problems will happen if the device is disconnected before finishing // all queries. DLOG(WARNING) << "Failed to get kMIDIPropertyUniqueID with status " << result; } const PortState state = PortState::OPENED; return MidiPortInfo(id, manufacturer, name, version, state); } base::TimeTicks MIDITimeStampToTimeTicks(MIDITimeStamp timestamp) { UInt64 nanoseconds = AudioConvertHostTimeToNanos(timestamp); return base::TimeTicks() + base::TimeDelta::FromNanoseconds(nanoseconds); } MIDITimeStamp TimeTicksToMIDITimeStamp(base::TimeTicks ticks) { return AudioConvertNanosToHostTime(ticks.since_origin().InNanoseconds()); } } // namespace MidiManager* MidiManager::Create(MidiService* service) { return new MidiManagerMac(service); } MidiManagerMac::MidiManagerMac(MidiService* service) : MidiManager(service) {} MidiManagerMac::~MidiManagerMac() = default; void MidiManagerMac::StartInitialization() { if (!service()->task_service()->BindInstance()) { NOTREACHED(); return CompleteInitialization(Result::INITIALIZATION_ERROR); } service()->task_service()->PostBoundTask( kClientTaskRunner, base::BindOnce(&MidiManagerMac::InitializeCoreMIDI, base::Unretained(this))); } void MidiManagerMac::Finalize() { if (!service()->task_service()->UnbindInstance()) { NOTREACHED(); } // Do not need to dispose |coremidi_input_| and |coremidi_output_| explicitly. // CoreMIDI automatically disposes them on the client disposal. base::AutoLock lock(midi_client_lock_); if (midi_client_) MIDIClientDispose(midi_client_); midi_client_ = 0u; } void MidiManagerMac::DispatchSendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8_t>& data, base::TimeTicks timestamp) { service()->task_service()->PostBoundTask( kClientTaskRunner, base::BindOnce(&MidiManagerMac::SendMidiData, base::Unretained(this), client, port_index, data, timestamp)); } void MidiManagerMac::InitializeCoreMIDI() { DCHECK(service()->task_service()->IsOnTaskRunner(kClientTaskRunner)); // CoreMIDI registration. MIDIClientRef client = 0u; OSStatus result = MIDIClientCreate(CFSTR("Chrome"), ReceiveMidiNotifyDispatch, this, &client); if (result != noErr || client == 0u) return CompleteInitialization(Result::INITIALIZATION_ERROR); { base::AutoLock lock(midi_client_lock_); midi_client_ = client; } // Create input and output port. These MIDIPortRef references are not needed // to be disposed explicitly. CoreMIDI automatically disposes them on the // client disposal. result = MIDIInputPortCreate(client, CFSTR("MIDI Input"), ReadMidiDispatch, this, &midi_input_); if (result != noErr || midi_input_ == 0u) return CompleteInitialization(Result::INITIALIZATION_ERROR); result = MIDIOutputPortCreate(client, CFSTR("MIDI Output"), &midi_output_); if (result != noErr || midi_output_ == 0u) return CompleteInitialization(Result::INITIALIZATION_ERROR); // Following loop may miss some newly attached devices, but such device will // be captured by ReceiveMidiNotifyDispatch callback. destinations_.resize(MIDIGetNumberOfDestinations()); for (size_t i = 0u; i < destinations_.size(); ++i) { MIDIEndpointRef destination = MIDIGetDestination(i); DCHECK_NE(0u, destination); // Keep track of all destinations (known as outputs by the Web MIDI API). destinations_[i] = destination; AddOutputPort(GetPortInfoFromEndpoint(destination)); } // Allocate maximum size of buffer that CoreMIDI can handle. midi_buffer_.resize(kCoreMIDIMaxPacketListSize); // Open connections from all sources. This loop also may miss new devices. sources_.resize(MIDIGetNumberOfSources()); for (size_t i = 0u; i < sources_.size(); ++i) { MIDIEndpointRef source = MIDIGetSource(i); DCHECK_NE(0u, source); // Keep track of all sources (known as inputs by the Web MIDI API). sources_[i] = source; AddInputPort(GetPortInfoFromEndpoint(source)); } // Start listening. for (size_t i = 0u; i < sources_.size(); ++i) MIDIPortConnectSource(midi_input_, sources_[i], reinterpret_cast<void*>(i)); CompleteInitialization(Result::OK); } // static void MidiManagerMac::ReceiveMidiNotifyDispatch(const MIDINotification* message, void* refcon) { // This callback function is invoked on |kClientTaskRunner|. // |manager| should be valid because we can ensure |midi_client_| is still // alive here. MidiManagerMac* manager = static_cast<MidiManagerMac*>(refcon); manager->ReceiveMidiNotify(message); } void MidiManagerMac::ReceiveMidiNotify(const MIDINotification* message) { DCHECK(service()->task_service()->IsOnTaskRunner(kClientTaskRunner)); if (kMIDIMsgObjectAdded == message->messageID) { // New device is going to be attached. const MIDIObjectAddRemoveNotification* notification = reinterpret_cast<const MIDIObjectAddRemoveNotification*>(message); MIDIEndpointRef endpoint = static_cast<MIDIEndpointRef>(notification->child); if (notification->childType == kMIDIObjectType_Source) { // Attaching device is an input device. auto it = std::find(sources_.begin(), sources_.end(), endpoint); if (it == sources_.end()) { MidiPortInfo info = GetPortInfoFromEndpoint(endpoint); // If the device disappears before finishing queries, MidiPortInfo // becomes incomplete. Skip and do not cache such information here. // On kMIDIMsgObjectRemoved, the entry will be ignored because it // will not be found in the pool. if (!info.id.empty()) { sources_.push_back(endpoint); AddInputPort(info); MIDIPortConnectSource(midi_input_, endpoint, reinterpret_cast<void*>(sources_.size() - 1)); } } else { SetInputPortState(it - sources_.begin(), PortState::OPENED); } } else if (notification->childType == kMIDIObjectType_Destination) { // Attaching device is an output device. auto it = std::find(destinations_.begin(), destinations_.end(), endpoint); if (it == destinations_.end()) { MidiPortInfo info = GetPortInfoFromEndpoint(endpoint); // Skip cases that queries are not finished correctly. if (!info.id.empty()) { destinations_.push_back(endpoint); AddOutputPort(info); } } else { SetOutputPortState(it - destinations_.begin(), PortState::OPENED); } } } else if (kMIDIMsgObjectRemoved == message->messageID) { // Existing device is going to be detached. const MIDIObjectAddRemoveNotification* notification = reinterpret_cast<const MIDIObjectAddRemoveNotification*>(message); MIDIEndpointRef endpoint = static_cast<MIDIEndpointRef>(notification->child); if (notification->childType == kMIDIObjectType_Source) { // Detaching device is an input device. auto it = std::find(sources_.begin(), sources_.end(), endpoint); if (it != sources_.end()) SetInputPortState(it - sources_.begin(), PortState::DISCONNECTED); } else if (notification->childType == kMIDIObjectType_Destination) { // Detaching device is an output device. auto it = std::find(destinations_.begin(), destinations_.end(), endpoint); if (it != destinations_.end()) SetOutputPortState(it - destinations_.begin(), PortState::DISCONNECTED); } } } // static void MidiManagerMac::ReadMidiDispatch(const MIDIPacketList* packet_list, void* read_proc_refcon, void* src_conn_refcon) { // This method is called on a separate high-priority thread owned by CoreMIDI. // |manager| should be valid because we can ensure |midi_client_| is still // alive here. MidiManagerMac* manager = static_cast<MidiManagerMac*>(read_proc_refcon); DCHECK(manager); uint32_t port_index = reinterpret_cast<uintptr_t>(src_conn_refcon); // Go through each packet and process separately. const MIDIPacket* packet = &packet_list->packet[0]; for (size_t i = 0u; i < packet_list->numPackets; i++) { // Each packet contains MIDI data for one or more messages (like note-on). base::TimeTicks timestamp = MIDITimeStampToTimeTicks(packet->timeStamp); manager->ReceiveMidiData(port_index, packet->data, packet->length, timestamp); packet = MIDIPacketNext(packet); } } void MidiManagerMac::SendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8_t>& data, base::TimeTicks timestamp) { DCHECK(service()->task_service()->IsOnTaskRunner(kClientTaskRunner)); // Lookup the destination based on the port index. if (static_cast<size_t>(port_index) >= destinations_.size()) return; MIDITimeStamp coremidi_timestamp = TimeTicksToMIDITimeStamp(timestamp); MIDIEndpointRef destination = destinations_[port_index]; size_t send_size; for (size_t sent_size = 0u; sent_size < data.size(); sent_size += send_size) { MIDIPacketList* packet_list = reinterpret_cast<MIDIPacketList*>(midi_buffer_.data()); MIDIPacket* midi_packet = MIDIPacketListInit(packet_list); // Limit the maximum payload size to kEstimatedMaxPacketDataSize that is // half of midi_buffer data size. MIDIPacketList and MIDIPacket consume // extra buffer areas for meta information, and available size is smaller // than buffer size. Here, we simply assume that at least half size is // available for data payload. send_size = std::min(data.size() - sent_size, kEstimatedMaxPacketDataSize); midi_packet = MIDIPacketListAdd( packet_list, kCoreMIDIMaxPacketListSize, midi_packet, coremidi_timestamp, send_size, &data[sent_size]); DCHECK(midi_packet); MIDISend(midi_output_, destination, packet_list); } AccumulateMidiBytesSent(client, data.size()); } } // namespace midi
// // server.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2010 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 HTTP_SERVER2_SERVER_HPP #define HTTP_SERVER2_SERVER_HPP #include <boost/asio.hpp> #include <string> #include <vector> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include "connection.hpp" #include "io_service_pool.hpp" #include "request_handler.hpp" namespace http { namespace server2 { /// The top-level class of the HTTP server. class server : private boost::noncopyable { public: /// Construct the server to listen on the specified TCP address and port, and /// serve up files from the given directory. explicit server(const std::string& address, const std::string& port, const std::string& doc_root, std::size_t io_service_pool_size); /// Run the server's io_service loop. void run(); /// Stop the server. void stop(); private: /// Handle completion of an asynchronous accept operation. void handle_accept(const boost::system::error_code& e); /// The pool of io_service objects used to perform asynchronous operations. io_service_pool io_service_pool_; /// Acceptor used to listen for incoming connections. boost::asio::ip::tcp::acceptor acceptor_; /// The next connection to be accepted. connection_ptr new_connection_; /// The handler for all incoming requests. request_handler request_handler_; }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_SERVER_HPP
/* * Copyright 2020-2021 Hewlett Packard Enterprise Development LP * Copyright 2004-2019 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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. */ /************************************* | ************************************** * * * pruneResolvedTree() -- prunes and cleans the AST * * after function calls and types have been resolved * * * ************************************** | *************************************/ #include "DecoratedClassType.h" #include "ForallStmt.h" #include "ForLoop.h" #include "iterator.h" #include "passes.h" #include "resolution.h" #include "wellknown.h" static void clearDefaultInitFns(FnSymbol* unusedFn) { AggregateType* at = toAggregateType(unusedFn->retType); if (at) { // Also remove unused fns from iterator infos. // Ditto for iterator fn in iterator info. if (at->iteratorInfo) { IteratorInfo* ii = at->iteratorInfo; INT_ASSERT(at->symbol->hasEitherFlag(FLAG_ITERATOR_RECORD, FLAG_ITERATOR_CLASS)); if (ii) { if (ii->iterator == unusedFn) ii->iterator = NULL; if (ii->getIterator == unusedFn) ii->getIterator = NULL; } } } } static void removeUnusedFunction(FnSymbol* unusedFn) { // remove the function unusedFn->defPoint->remove(); } static void removeUnusedFunctions() { std::set<FnSymbol*> concreteWellKnownFunctionsSet; clearGenericWellKnownFunctions(); std::vector<FnSymbol*> fns = getWellKnownFunctions(); for_vector(FnSymbol, fn, fns) { INT_ASSERT(! fn->isGeneric()); concreteWellKnownFunctionsSet.insert(fn); } for_alive_in_Vec(FnSymbol, fn, gFnSymbols) { if (concreteWellKnownFunctionsSet.count(fn) == 0) { if (fn->defPoint->parentSymbol != stringLiteralModule) { if (! fn->isResolved() || fn->retTag == RET_PARAM) { std::vector<DefExpr*> defExprs; collectDefExprs(fn, defExprs); forv_Vec(DefExpr, def, defExprs) { if (TypeSymbol* typeSym = toTypeSymbol(def->sym)) { Type* refType = typeSym->type->refType; removeCopyFns(typeSym->type); if (AggregateType* at = toAggregateType(refType)) { removeCopyFns(at); at->symbol->defPoint->remove(); } } } clearDefaultInitFns(fn); removeUnusedFunction(fn); } else if (fn->isResolved() && fn->retTag == RET_TYPE) { // BHARSH TODO: This is a way to work around the cleanup logic that // removes generic types from the tree. If the function was left // alive and returned a generic type the compiler would encounter // memory corruption issues. Ideally type functions could remain // in the AST and prevent the types they use from being removed. // // Skip if fatal errors were encountered because in such cases // postFold will leave type-returning function calls in the AST. Type* type = fn->retType; if (type->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE) == false && type->symbol->hasFlag(FLAG_EXTERN) == false && fatalErrorsEncountered() == false) { removeUnusedFunction(fn); } } } } } } static CallExpr* replaceRuntimeTypeGetField(CallExpr* call) { SymExpr* rt = toSymExpr(call->get(1)); INT_ASSERT(rt->typeInfo()->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)); Symbol* field = getPrimGetRuntimeTypeField_Field(call); INT_ASSERT(field); SET_LINENO(call); CallExpr* ret = new CallExpr(PRIM_GET_MEMBER_VALUE, rt->remove(), field); call->replace(ret); return ret; } static void removeRandomPrimitive(CallExpr* call) { if (call->isPrimitive(PRIM_GET_RUNTIME_TYPE_FIELD)) call = replaceRuntimeTypeGetField(call); switch (call->primitive->tag) { default: /* do nothing */ break; case PRIM_NOOP: call->remove(); break; case PRIM_TYPEOF: { // Remove move(x, PRIM_TYPEOF(y)) calls -- useless after this CallExpr* parentCall = toCallExpr(call->parentExpr); if (parentCall && parentCall->isPrimitive(PRIM_MOVE) && parentCall->get(2) == call) { parentCall->remove(); } else { // Replace PRIM_TYPEOF with argument call->replace(call->get(1)->remove()); } } break; case PRIM_CAST: // Remove trivial casts. if (call->get(1)->typeInfo() == call->get(2)->typeInfo()) call->replace(call->get(2)->remove()); break; case PRIM_SET_MEMBER: case PRIM_GET_MEMBER: case PRIM_GET_MEMBER_VALUE: { // Remove member accesses of types // Replace string literals with field symbols in member primitives Type* baseType = call->get(1)->typeInfo(); if (!call->parentSymbol->hasFlag(FLAG_REF) && baseType->symbol->hasFlag(FLAG_REF)) baseType = baseType->getValType(); baseType = canonicalDecoratedClassType(baseType); SymExpr* memberSE = toSymExpr(call->get(2)); const char* memberName = NULL; Symbol* sym = NULL; // the member symbol if (get_string(memberSE, &memberName)) { sym = baseType->getField(memberName); SET_LINENO(memberSE); memberSE->replace(new SymExpr(sym)); } else { // Confirm that this is already a correct field Symbol. sym = memberSE->symbol(); // This used to check for type equality, is this wrong? INT_ASSERT(isSubtypeOrInstantiation(baseType, sym->defPoint->parentSymbol->type, call)); } if (sym->hasFlag(FLAG_TYPE_VARIABLE) || sym->isParameter()) call->getStmtExpr()->remove(); } break; case PRIM_MOVE: { // Remove types to enable --baseline SymExpr* se = toSymExpr(call->get(2)); if (se && se->symbol()) { Symbol* sym = se->symbol(); if (isTypeSymbol(sym) || sym->hasFlag(FLAG_TYPE_VARIABLE)) call->remove(); } } break; case PRIM_WARNING: case PRIM_ERROR: { // Warnings have now been issued, no need to keep the function around. // Remove calls to compilerWarning and let dead code elimination handle // the rest. call->remove(); } break; } } static void removeRandomPrimitives() { for_alive_in_Vec(CallExpr, call, gCallExprs) if (call->isPrimitive()) removeRandomPrimitive(call); } static void removeInterfaceCode() { for_alive_in_Vec(InterfaceSymbol, isym, gInterfaceSymbols) isym->defPoint->remove(); for_alive_in_Vec(ImplementsStmt, istm, gImplementsStmts) { FnSymbol* wrapFn = wrapperFnForImplementsStmt(istm); INT_ASSERT(wrapFn->hasFlag(FLAG_IMPLEMENTS_WRAPPER)); Expr* wrapFnDef = wrapFn->defPoint; // We will remove istm and wrapFn. Preserve the implementation fns. for_alist(impl, istm->implBody->body) wrapFnDef->insertBefore(impl->remove()); wrapFnDef->remove(); } for_alive_in_Vec(ConstrainedType, ct, gConstrainedTypes) { ct->symbol->defPoint->remove(); if (Type* ctRef = ct->refType) ctRef->symbol->defPoint->remove(); } } static void replaceTypeArgsWithFormalTypeTemps() { compute_call_sites(); for_alive_in_Vec(FnSymbol, fn, gFnSymbols) { if (! fn->isResolved()) // Don't bother with unresolved functions. // They will be removed from the tree. continue; // We do not remove type args from extern functions so that e.g.: // extern proc sizeof(type t); // sizeof(int) // will function correctly. // However, in such a case, we'd like to pass the type symbol // to the call site rather than a type variable call_tmp if (fn->hasFlag(FLAG_EXTERN)) { // Replace the corresponding actual with a SymExpr TypeSymbol // for all the call sites. forv_Vec(CallExpr, call, *fn->calledBy) { for_formals_actuals(formal, actual, call) { if (! formal->hasFlag(FLAG_TYPE_VARIABLE)) continue; if (SymExpr* se = toSymExpr(actual)) { if (isTypeSymbol(se->symbol())) continue; if (se->symbol()->hasFlag(FLAG_EXTERN) && se->symbol()->hasFlag(FLAG_TYPE_VARIABLE)) continue; } SET_LINENO(actual); TypeSymbol* ts = formal->type->symbol; actual->replace(new SymExpr(ts)); } } continue; } for_formals(formal, fn) { // We are only interested in type formals if (! formal->hasFlag(FLAG_TYPE_VARIABLE)) continue; // Replace the formal with a _formal_type_tmp_. SET_LINENO(formal); VarSymbol* tmp = newTemp("_formal_type_tmp_", formal->type); fn->insertAtHead(new DefExpr(tmp)); subSymbol(fn, formal, tmp); // Remove the corresponding actual from all call sites. forv_Vec(CallExpr, call, *fn->calledBy) { for_formals_actuals(cf, ca, call) { if (cf == formal) { ca->remove(); break; } } } formal->defPoint->remove(); // // If we're removing the formal representing 'this' (if it's a // type, say), we need to nullify the 'this' pointer in the // function as well to avoid assumptions that it's legal later. // if (formal == fn->_this) { fn->_this = NULL; } } } } // Remove the method token, parameter and type arguments // from function signatures and corresponding calls. static void removeParamArgs() { compute_call_sites(); for_alive_in_Vec(FnSymbol, fn, gFnSymbols) { if (! fn->isResolved()) // Don't bother with unresolved functions. // They will be removed from the tree. continue; for_formals(formal, fn) { if (formal->hasFlag(FLAG_INSTANTIATED_PARAM) || formal->type == dtMethodToken) { // Remove the argument from the call site. for_alive_in_Vec(CallExpr, call, *fn->calledBy) { // Performance note: AList::get(int) also performs a linear search. for_formals_actuals(cf, ca, call) { if (cf == formal) { ca->remove(); break; } } } formal->defPoint->remove(); } } } } static void removeAggTypeFieldInfo() { for_alive_in_Vec(AggregateType, at, gAggregateTypes) { // Defined an initializer (so we left its init // and exprType information in the tree) for_fields(field, at) { if (field->defPoint->exprType) { field->defPoint->exprType->remove(); } if (field->defPoint->init) { field->defPoint->init->remove(); } } } } // Remove module level variables if they are not defined or used // With the exception of variables that are defined in the rootModule static void removeUnusedModuleVariables() { forv_Vec(DefExpr, def, gDefExprs) { if (VarSymbol* var = toVarSymbol(def->sym)) { if (ModuleSymbol* module = toModuleSymbol(def->parentSymbol)) { if (var->isDefined() == false && var->isUsed() == false) { if (module != rootModule) { def->remove(); } } } } } } static bool do_isUnusedClass(Type* t, const std::set<Type*>& wellknown) { bool retval = true; AggregateType* at = toAggregateType(t); // Special case for global types. if (t->symbol->hasFlag(FLAG_GLOBAL_TYPE_SYMBOL)) { retval = false; // Runtime types are assumed to be always used. } else if (t->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) { retval = false; // Uses of iterator records get inserted in lowerIterators } else if (t->symbol->hasFlag(FLAG_ITERATOR_RECORD)) { retval = false; // FALSE if iterator class's getIterator is used // (this case may not be necessary) } else if (t->symbol->hasFlag(FLAG_ITERATOR_CLASS) && at && at->iteratorInfo->getIterator->isResolved()) { retval = false; } else if (at && at->resolveStatus == RESOLVED) { retval = false; // FALSE if the type uses an initializer and that initializer was // resolved } else if (at && at->initializerResolved) { retval = false; } else if (wellknown.count(at) != 0) { retval = false; } else if (at) { forv_Vec(AggregateType, childClass, at->dispatchChildren) { if (childClass && isUnusedClass(childClass, wellknown) == false) { retval = false; break; } } } return retval; } std::set<Type*> getWellKnownTypesSet() { std::set<Type*> concreteWellKnownTypesSet; std::vector<Type*> wellKnownTypes= getWellKnownTypes(); for_vector(Type, type, wellKnownTypes) { AggregateType* at = toAggregateType(type); if (at == NULL || at->isGeneric() == false) concreteWellKnownTypesSet.insert(type); } return concreteWellKnownTypesSet; } bool isUnusedClass(Type* t, const std::set<Type*>& wellknown) { bool retval = true; retval = do_isUnusedClass(t, wellknown); // check other variant // borrow/class types can have unmanaged class type used // unmanaged class types can have borrow/canonical class type used if (AggregateType* at = toAggregateType(t)) { if (isClass(at)) { for (int i = 0; i < NUM_DECORATED_CLASS_TYPES; i++) { ClassTypeDecorator decorator = (ClassTypeDecorator)i; if (Type* dt = at->getDecoratedClass(decorator)) retval &= do_isUnusedClass(dt, wellknown); } } } else if (DecoratedClassType* dt = toDecoratedClassType(t)) { retval &= do_isUnusedClass(dt->getCanonicalClass(), wellknown); } return retval; } static void removeUnusedTypes() { clearGenericWellKnownTypes(); std::set<Type*> wellknown = getWellKnownTypesSet(); // Remove unused aggregate types. for_alive_in_Vec(TypeSymbol, type, gTypeSymbols) { if (! type->hasFlag(FLAG_REF) && ! type->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) { if (AggregateType* at = toAggregateType(type->type)) { if (isUnusedClass(at, wellknown)) { at->symbol->defPoint->remove(); } } else if(DecoratedClassType* dt = toDecoratedClassType(type->type)) { if (isUnusedClass(dt->getCanonicalClass(), wellknown)) { dt->symbol->defPoint->remove(); } } } } // Remove unused ref types. for_alive_in_Vec(TypeSymbol, type, gTypeSymbols) { if (type->hasFlag(FLAG_REF)) { // Get the value type of the ref type. if (AggregateType* at1 = toAggregateType(type->getValType())) { if (isUnusedClass(at1, wellknown)) { // If the value type is unused, its ref type can also be removed. type->defPoint->remove(); } } else if(DecoratedClassType* dt = toDecoratedClassType(type->getValType())) { if (isUnusedClass(dt->getCanonicalClass(), wellknown)) { type->defPoint->remove(); } } } } } static void removeActualNames() { for_alive_in_Vec(NamedExpr, named, gNamedExprs) { Expr* actual = named->actual; actual->remove(); named->replace(actual); } } static void removeFormalTypeAndInitBlocks() { for_alive_in_Vec(FnSymbol, fn, gFnSymbols) { for_formals(formal, fn) { // Remove formal default values if (formal->defaultExpr) formal->defaultExpr->remove(); // Remove formal type expressions if (formal->typeExpr) formal->typeExpr->remove(); } } } // // Remove the ref types and the autocopy/autodestroy functions // for the types that are about to be removed when removing 'block'. // // Todo: we probably want to do this for all types that have been // deleted, as a cleanup function at the end of resolve(). // static void removeRefAndAutoCopyForDeadTypes(BlockStmt* block) { for_alist(stmt, block->body) { if (DefExpr* def = toDefExpr(stmt)) { Symbol* sym = def->sym; // Check whether this is the definition of a type. if (sym->hasFlag(FLAG_TYPE_VARIABLE) && sym->type->symbol == sym) { if (Type* ref = sym->type->getRefType()) ref->symbol->defPoint->remove(); removeCopyFns(sym->type); } } } } static void removeTypeBlocks() { for_alive_in_Vec(BlockStmt, block, gBlockStmts) { // Remove type blocks--code that exists only to determine types if (block->blockTag & BLOCK_TYPE_ONLY) { removeRefAndAutoCopyForDeadTypes(block); block->remove(); } } } // Remove moot parts of AST for type a=b static void removeTypedefParts() { for_alive_in_Vec(DefExpr, def, gDefExprs) { if (def->init && (def->sym->hasFlag(FLAG_TYPE_VARIABLE) || def->sym->type->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE))) { def->init->remove(); def->init = NULL; } // Also remove DefExprs for generic type variables if (!isPrimitiveType(def->sym->type) && def->sym->hasFlag(FLAG_TYPE_VARIABLE) && def->sym->type->symbol->hasFlag(FLAG_GENERIC)) { bool removeIt = true; if (TypeSymbol* ts = toTypeSymbol(def->sym)) { if (DecoratedClassType* dt = toDecoratedClassType(ts->type)) { ClassTypeDecorator d = dt->getDecorator(); if ((isDecoratorUnknownNilability(d) || isDecoratorUnknownManagement(d)) && dt->getCanonicalClass()->inTree()) { // After resolution, can't consider it generic anymore... // The generic-ness will be moot though because later // it will all be replaced with the AggregateType. ts->removeFlag(FLAG_GENERIC); removeIt = false; } } } if (removeIt) def->remove(); } } } static void removeWhereClausesAndReturnTypeBlocks() { for_alive_in_Vec(FnSymbol, fn, gFnSymbols) { if (fn->where) fn->where->remove(); if (fn->retExprType) { // First, move any defs in the return type block out // (e.g. an array return type creates forall-expr fns) for_alist(expr, fn->retExprType->body) { if (DefExpr* def = toDefExpr(expr)) { if (isFnSymbol(def->sym)) { def->remove(); fn->defPoint->insertBefore(def); } } } // Now remove the type block fn->retExprType->remove(); } } } static void removeMootFields() { // Remove type fields and parameter fields for_alive_in_Vec(TypeSymbol, ts, gTypeSymbols) { if (AggregateType* at = toAggregateType(ts->type)) { for_fields(field, at) { if (field->hasFlag(FLAG_TYPE_VARIABLE) || field->isParameter()) field->defPoint->remove(); } } } } // // If a symbol's type is not live, we can't use it. // Remove it if VarSymbol; remove containing fn if ArgSymbol. // Hopefully they are not used. // static void removeSymbolsWithRemovedTypes() { std::vector<Symbol*> removedSyms; // for verification for_alive_in_Vec(ArgSymbol, arg, gArgSymbols) { if (! arg->type->inTree()) { if (FnSymbol* fn = toFnSymbol(arg->defPoint->parentSymbol)) { removedSyms.push_back(fn); fn->defPoint->remove(); } } } for_alive_in_Vec(VarSymbol, var, gVarSymbols) { if (! var->type->inTree()) { removedSyms.push_back(var); var->defPoint->remove(); } } // Running the asserts after the above guards against potential false alarms // when an earlier-removed Fn/VarSymbol refers to a later-removed one. for_vector(Symbol, sym, removedSyms) INT_ASSERT(sym->firstSymExpr() == NULL); // these better be unused } // // A few internal pointers may point to nodes not in tree. // Zero out such pointers whether or not their targets are live, // to ensure they are not looked at again. static void cleanupAfterRemoves() { // Note: some pointers are already zero'd in saveGenericSubstitutions forv_Vec(ModuleSymbol, mod, gModuleSymbols) { // Zero the initFn pointer if the function is now dead. Ditto deinitFn. if (mod->initFn && !isAlive(mod->initFn)) mod->initFn = NULL; if (mod->deinitFn && !isAlive(mod->deinitFn)) mod->deinitFn = NULL; } forv_Vec(ArgSymbol, arg, gArgSymbols) { if (arg->instantiatedFrom != NULL) arg->addFlag(FLAG_INSTANTIATED_GENERIC); arg->instantiatedFrom = NULL; } cleanupAfterTypeRemoval(); } static bool isNothingType(Type* type) { if (type == NULL) { return false; } if (type == dtNothing) { return true; } if (type->symbol->hasFlag(FLAG_REF)) { if (type->getField("_val", false)) { return isNothingType(type->getValType()); } else { // The _val field has already been removed because it is // void or tuple of void return true; } } if (type->symbol->hasFlag(FLAG_STAR_TUPLE)) { Symbol* field = type->getField("x0", false); if (field == NULL || field->type == dtNothing) { return true; } } return false; } static void cleanupNothingVarsAndFields() { // Remove most uses of nothing variables and fields for_alive_in_Vec(CallExpr, call, gCallExprs) { if (call->isPrimitive()) switch (call->primitive->tag) { case PRIM_MOVE: if (isNothingType(call->get(2)->typeInfo()) || call->get(2)->typeInfo() == dtNothing->refType) { INT_ASSERT(call->get(1)->typeInfo() == call->get(2)->typeInfo()); // Remove moves where the rhs has type nothing. If the rhs is a // call to something other than a few primitives, still make // that call, just don't move the result into anything. if (CallExpr* rhs = toCallExpr(call->get(2))) { if (rhs->isPrimitive(PRIM_DEREF) || rhs->isPrimitive(PRIM_GET_MEMBER) || rhs->isPrimitive(PRIM_GET_MEMBER_VALUE)) { call->remove(); } else { Expr* rmRhs = rhs->remove(); call->insertBefore(rmRhs); call->remove(); } } else if (isSymExpr(call->get(2))) { call->remove(); } } break; case PRIM_SET_MEMBER: if (isNothingType(call->get(3)->typeInfo())) { INT_ASSERT(call->get(2)->typeInfo() == call->get(3)->typeInfo()); // Remove set_member(a, nothing, nothing) calls if (CallExpr* rhs = toCallExpr(call->get(2))) { Expr* rmRhs = rhs->remove(); call->insertBefore(rmRhs); call->remove(); } else if (isSymExpr(call->get(2))) { call->remove(); } } break; case PRIM_YIELD: case PRIM_RETURN: if (isNothingType(call->get(1)->typeInfo()) || call->get(1)->typeInfo() == dtNothing->refType) { // Change functions/iterators that return/yield nothing to use the // global nothing value instead of a local nothing. if (SymExpr* ret = toSymExpr(call->get(1))) { if (ret->symbol() != gNone) { SET_LINENO(call); call->replace(new CallExpr(call->primitive->tag, gNone)); } } } break; case PRIM_CALL_DESTRUCTOR: // Remove calls to destructors for homogeneous tuples of nothing if (isNothingType(call->get(1)->typeInfo())) { call->remove(); } break; default: break; } // switch (call->primitive->tag) else if (FnSymbol* fn = call->resolvedFunction()) { bool seenNothing = false; // Remove actual arguments that are nothing from function calls for_actuals(actual, call) { if (isNothingType(actual->typeInfo())) { actual->remove(); seenNothing = true; } } if (seenNothing && fn->hasFlag(FLAG_AUTO_DESTROY_FN)) { INT_ASSERT(call->numActuals() == 0); // A 0-arg call to autoDestroy would upset later passes. call->remove(); } } } // Remove nothing formal arguments from functions. // Change functions that return ref(nothing) to just return nothing. for_alive_in_Vec(FnSymbol, fn, gFnSymbols) { for_formals(formal, fn) { if (isNothingType(formal->type)) { if (formal == fn->_this) { fn->_this = NULL; } formal->defPoint->remove(); } } if (fn->retType == dtNothing->refType || isNothingType(fn->retType)) { fn->retType = dtNothing; } if (fn->_this) { if (isNothingType(fn->_this->type)) { fn->_this = NULL; } } } // Set for loop index variables that are nothing to the global nothing value for_alive_in_Vec(BlockStmt, block, gBlockStmts) { if (ForLoop* loop = toForLoop(block)) { if (loop->indexGet() && loop->indexGet()->typeInfo() == dtNothing) { loop->indexGet()->setSymbol(gNone); } } } // Now that uses of nothing have been cleaned up, remove the // DefExprs for nothing variables. for_alive_in_Vec(DefExpr, def, gDefExprs) { if (isNothingType(def->sym->type) || def->sym->type == dtNothing->refType) { if (VarSymbol* var = toVarSymbol(def->sym)) { // Avoid removing the "_val" field from refs // and forall statements' induction/shadow variables. if (! def->parentSymbol->hasFlag(FLAG_REF) && ! isForallIterVarDef(def) && ! preserveShadowVar(var) ) { if (var != gNone) { def->remove(); } } } } else if (def->sym->type == dtUninstantiated && isVarSymbol(def->sym) && !def->parentSymbol->hasFlag(FLAG_REF)) { def->remove(); } } adjustNothingShadowVariables(); // Problem case introduced by postFoldNormal where a statement-level call // returning void can be replaced by a 'none' SymExpr. Such SymExprs will // be left in the tree if optimizations are disabled, and can cause codegen // failures later on (at least under LLVM). // // Solution: Remove SymExprs to none if the expr is at the // statement level. for_SymbolSymExprs(se, gNone) { if (se == se->getStmtExpr()) { se->remove(); } } } void saveGenericSubstitutions() { for_alive_in_Vec(FnSymbol, fn, gFnSymbols) { if (fn->substitutions.n > 0) { // Generate substitutionsPostResolve which should not be generated yet INT_ASSERT(fn->substitutionsPostResolve.size() == 0); if (FnSymbol* genericFn = fn->instantiatedFrom) { // Construct substitutionsPostResolve for_formals(genericFormal, genericFn) { if (genericFormal->type != dtMethodToken) { Symbol* value = fn->substitutions.get(genericFormal); NameAndSymbol ns; ns.name = genericFormal->name; ns.value = value; ns.isParam = genericFormal->isParameter(); ns.isType = (genericFormal->originalIntent == INTENT_TYPE); fn->substitutionsPostResolve.push_back(ns); } } } else { // This case is a workaround for patterns that // come up with compiler-generated tuple functions INT_ASSERT(fn->hasFlag(FLAG_INIT_TUPLE)); form_Map(SymbolMapElem, e, fn->substitutions) { NameAndSymbol ns; ns.name = e->key->name; ns.value = e->value; ns.isParam = false; ns.isType = false; fn->substitutionsPostResolve.push_back(ns); } } // Clear substitutions since keys might refer to deleted AST nodes fn->substitutions.clear(); } // Clear instantiatedFrom since it would refer to a deleted AST node if (fn->instantiatedFrom != NULL) { fn->addFlag(FLAG_INSTANTIATED_GENERIC); // Clear instantiatedFrom since it would refer to a deleted AST node fn->instantiatedFrom = NULL; } fn->setInstantiationPoint(NULL); } for_alive_in_Vec(TypeSymbol, ts, gTypeSymbols) { if (AggregateType* at = toAggregateType(ts->type)) { if (at->substitutions.n > 0) { // Generate substitutionsPostResolve which should not be generated yet INT_ASSERT(at->substitutionsPostResolve.size() == 0); for_fields(field, at) { if (Symbol* value = at->getSubstitutionWithName(field->name)) { NameAndSymbol ns; ns.name = field->name; ns.value = value; ns.isParam = field->isParameter(); ns.isType = field->hasFlag(FLAG_TYPE_VARIABLE); at->substitutionsPostResolve.push_back(ns); } } // Clear substitutions since keys might refer to deleted AST nodes at->substitutions.clear(); } if (at->instantiatedFrom != NULL) { // Clear instantiatedFrom since it would refer to a deleted AST node at->instantiatedFrom = NULL; ts->addFlag(FLAG_INSTANTIATED_GENERIC); } } } } void pruneResolvedTree() { removeInterfaceCode(); removeTiMarks(); removeUnusedFunctions(); if (fRemoveUnreachableBlocks) { deadBlockElimination(); } removeRandomPrimitives(); replaceTypeArgsWithFormalTypeTemps(); removeParamArgs(); removeAggTypeFieldInfo(); removeUnusedModuleVariables(); removeUnusedTypes(); removeActualNames(); removeFormalTypeAndInitBlocks(); removeTypeBlocks(); removeTypedefParts(); removeWhereClausesAndReturnTypeBlocks(); removeMootFields(); removeSymbolsWithRemovedTypes(); expandInitFieldPrims(); cleanupNothingVarsAndFields(); cleanupAfterRemoves(); }
#include <eosio/chain/block_header_state.hpp> #include <eosio/chain/exceptions.hpp> #include <limits> namespace eosio { namespace chain { producer_authority block_header_state::get_scheduled_producer( block_timestamp_type t )const { auto index = t.slot % (active_schedule.producers.size() * config::producer_repetitions); index /= config::producer_repetitions; return active_schedule.producers[index]; } uint32_t block_header_state::calc_dpos_last_irreversible( account_name producer_of_next_block )const { vector<uint32_t> blocknums; blocknums.reserve( producer_to_last_implied_irb.size() ); for( auto& i : producer_to_last_implied_irb ) { blocknums.push_back( (i.first == producer_of_next_block) ? dpos_proposed_irreversible_blocknum : i.second); } /// 2/3 must be greater, so if I go 1/3 into the list sorted from low to high, then 2/3 are greater if( blocknums.size() == 0 ) return 0; std::size_t index = (blocknums.size()-1) / 3; // dpos最后不可逆区块的判断条件是必须在池子里面保持有2/3个区块号是大于自己的 std::nth_element( blocknums.begin(), blocknums.begin() + index, blocknums.end() ); return blocknums[ index ]; } pending_block_header_state block_header_state::next( block_timestamp_type when, uint16_t num_prev_blocks_to_confirm )const { pending_block_header_state result; if( when != block_timestamp_type() ) { EOS_ASSERT( when > header.timestamp, block_validate_exception, "next block must be in the future" ); } else { (when = header.timestamp).slot++; } auto proauth = get_scheduled_producer(when); auto itr = producer_to_last_produced.find( proauth.producer_name ); if( itr != producer_to_last_produced.end() ) { EOS_ASSERT( itr->second < (block_num+1) - num_prev_blocks_to_confirm, producer_double_confirm, "producer ${prod} double-confirming known range", ("prod", proauth.producer_name)("num", block_num+1) ("confirmed", num_prev_blocks_to_confirm)("last_produced", itr->second) ); } result.block_num = block_num + 1; result.previous = id; result.timestamp = when; result.confirmed = num_prev_blocks_to_confirm; result.active_schedule_version = active_schedule.version; result.valid_block_signing_authority = proauth.authority; result.producer = proauth.producer_name; result.blockroot_merkle = blockroot_merkle; result.blockroot_merkle.append( id ); /// grow the confirmed count static_assert(std::numeric_limits<uint8_t>::max() >= (config::max_producers * 2 / 3) + 1, "8bit confirmations may not be able to hold all of the needed confirmations"); // This uses the previous block active_schedule because thats the "schedule" that signs and therefore confirms _this_ block auto num_active_producers = active_schedule.producers.size(); uint32_t required_confs = (uint32_t)(num_active_producers * 2 / 3) + 1; if( confirm_count.size() < config::maximum_tracked_dpos_confirmations ) { result.confirm_count.reserve( confirm_count.size() + 1 ); result.confirm_count = confirm_count; result.confirm_count.resize( confirm_count.size() + 1 ); result.confirm_count.back() = (uint8_t)required_confs; } else { result.confirm_count.resize( confirm_count.size() ); memcpy( &result.confirm_count[0], &confirm_count[1], confirm_count.size() - 1 ); result.confirm_count.back() = (uint8_t)required_confs; } auto new_dpos_proposed_irreversible_blocknum = dpos_proposed_irreversible_blocknum; int32_t i = (int32_t)(result.confirm_count.size() - 1); uint32_t blocks_to_confirm = num_prev_blocks_to_confirm + 1; /// confirm the head block too while( i >= 0 && blocks_to_confirm ) { --result.confirm_count[i]; // idump((result.confirm_count[i])); if( result.confirm_count[i] == 0 ) { uint32_t block_num_for_i = result.block_num - (uint32_t)(result.confirm_count.size() - 1 - i); new_dpos_proposed_irreversible_blocknum = block_num_for_i; // idump((block_num_for_i)(block_num)(dpos_irreversible_blocknum)); if (i == static_cast<int32_t>(result.confirm_count.size() - 1)) { result.confirm_count.resize(0); } else { memmove( &result.confirm_count[0], &result.confirm_count[i + 1], result.confirm_count.size() - i - 1); result.confirm_count.resize( result.confirm_count.size() - i - 1 ); } break; } --i; --blocks_to_confirm; } result.dpos_proposed_irreversible_blocknum = new_dpos_proposed_irreversible_blocknum; result.dpos_irreversible_blocknum = calc_dpos_last_irreversible( proauth.producer_name ); result.prev_pending_schedule = pending_schedule; result.enable_standby_schedule = enable_standby_schedule; result.standby_schedule_block_num = standby_schedule_block_num; if( pending_schedule.schedule.producers.size() && ((result.dpos_irreversible_blocknum >= pending_schedule.schedule_lib_num ) || (enable_standby_schedule && standby_schedule_block_num.valid() && *standby_schedule_block_num <= block_num) ) ) { result.active_schedule = pending_schedule.schedule; flat_map<account_name,uint32_t> new_producer_to_last_produced; for( const auto& pro : result.active_schedule.producers ) { if( pro.producer_name == proauth.producer_name ) { new_producer_to_last_produced[pro.producer_name] = result.block_num; } else { auto existing = producer_to_last_produced.find( pro.producer_name ); if( existing != producer_to_last_produced.end() ) { new_producer_to_last_produced[pro.producer_name] = existing->second; } else { new_producer_to_last_produced[pro.producer_name] = result.dpos_irreversible_blocknum; } } } new_producer_to_last_produced[proauth.producer_name] = result.block_num; result.producer_to_last_produced = std::move( new_producer_to_last_produced ); flat_map<account_name,uint32_t> new_producer_to_last_implied_irb; for( const auto& pro : result.active_schedule.producers ) { if( pro.producer_name == proauth.producer_name ) { new_producer_to_last_implied_irb[pro.producer_name] = dpos_proposed_irreversible_blocknum; } else { auto existing = producer_to_last_implied_irb.find( pro.producer_name ); if( existing != producer_to_last_implied_irb.end() ) { new_producer_to_last_implied_irb[pro.producer_name] = existing->second; } else { new_producer_to_last_implied_irb[pro.producer_name] = result.dpos_irreversible_blocknum; } } } result.producer_to_last_implied_irb = std::move( new_producer_to_last_implied_irb ); result.was_pending_promoted = !enable_standby_schedule; } else { result.active_schedule = active_schedule; result.producer_to_last_produced = producer_to_last_produced; result.producer_to_last_produced[proauth.producer_name] = result.block_num; result.producer_to_last_implied_irb = producer_to_last_implied_irb; result.producer_to_last_implied_irb[proauth.producer_name] = dpos_proposed_irreversible_blocknum; } return result; } signed_block_header pending_block_header_state::make_block_header( const checksum256_type& transaction_mroot, const checksum256_type& action_mroot, const optional<producer_authority_schedule>& new_producers, bool enable_standby_schedule, optional<block_num_type> standby_schedule_block_num )const { signed_block_header h; h.timestamp = timestamp; h.producer = producer; h.confirmed = confirmed; h.previous = previous; h.transaction_mroot = transaction_mroot; h.action_mroot = action_mroot; h.schedule_version = active_schedule_version; h.enable_standby_schedule = enable_standby_schedule; h.standby_schedule_block_num = standby_schedule_block_num; if (new_producers) { // add the header extension to update the block schedule emplace_extension( h.header_extensions, producer_schedule_change_extension::extension_id(), fc::raw::pack( producer_schedule_change_extension( *new_producers ) ) ); } return h; } block_header_state pending_block_header_state::_finish_next( const signed_block_header& h )&& { EOS_ASSERT( h.timestamp == timestamp, block_validate_exception, "timestamp mismatch" ); EOS_ASSERT( h.previous == previous, unlinkable_block_exception, "previous mismatch" ); EOS_ASSERT( h.confirmed == confirmed, block_validate_exception, "confirmed mismatch" ); EOS_ASSERT( h.producer == producer, wrong_producer, "wrong producer specified" ); EOS_ASSERT( h.schedule_version == active_schedule_version, producer_schedule_exception, "schedule_version in signed block is corrupted" ); auto exts = h.validate_and_extract_header_extensions(); std::optional<producer_authority_schedule> maybe_new_producer_schedule; std::optional<digest_type> maybe_new_producer_schedule_hash; if ( exts.count(producer_schedule_change_extension::extension_id()) > 0 ) { EOS_ASSERT( !was_pending_promoted, producer_schedule_exception, "cannot set pending producer schedule in the same block in which pending was promoted to active" ); const auto& new_producer_schedule = exts.lower_bound(producer_schedule_change_extension::extension_id())->second.get<producer_schedule_change_extension>(); EOS_ASSERT( h.enable_standby_schedule || new_producer_schedule.version == active_schedule.version + 1, producer_schedule_exception, "wrong producer schedule version specified" ); EOS_ASSERT( h.enable_standby_schedule || prev_pending_schedule.schedule.producers.empty(), producer_schedule_exception, "cannot set new pending producers until last pending is confirmed" ); maybe_new_producer_schedule_hash.emplace(digest_type::hash(new_producer_schedule)); maybe_new_producer_schedule.emplace(new_producer_schedule); } auto block_number = block_num; block_header_state result( std::move( *static_cast<detail::block_header_state_common*>(this) ) ); result.id = h.id(); result.header = h; result.enable_standby_schedule = h.enable_standby_schedule; result.standby_schedule_block_num = h.standby_schedule_block_num; result.header_exts = std::move(exts); if( maybe_new_producer_schedule ) { result.pending_schedule.schedule = std::move(*maybe_new_producer_schedule); result.pending_schedule.schedule_hash = std::move(*maybe_new_producer_schedule_hash); result.pending_schedule.schedule_lib_num = block_number; } else { if( was_pending_promoted ) { result.pending_schedule.schedule.version = prev_pending_schedule.schedule.version; } else { result.pending_schedule.schedule = std::move( prev_pending_schedule.schedule ); } result.pending_schedule.schedule_hash = std::move( prev_pending_schedule.schedule_hash ); result.pending_schedule.schedule_lib_num = prev_pending_schedule.schedule_lib_num; } return result; } //验证调用 block_header_state pending_block_header_state::finish_next( const signed_block_header& h, vector<signature_type>&& additional_signatures, bool skip_validate_signee )&& { auto result = std::move(*this)._finish_next( h ); if( !additional_signatures.empty() ) { result.additional_signatures = std::move(additional_signatures); } // ASSUMPTION FROM controller_impl::apply_block = all untrusted blocks will have their signatures pre-validated here if( !skip_validate_signee ) { result.verify_signee( ); } return result; } //生产BP调用 block_header_state pending_block_header_state::finish_next( signed_block_header& h, const signer_callback_type& signer )&& { auto result = std::move(*this)._finish_next( h ); result.sign( signer ); h.producer_signature = result.header.producer_signature; return result; } //验证调用 /** * Transitions the current header state into the next header state given the supplied signed block header. * * Given a signed block header, generate the expected template based upon the header time, * then validate that the provided header matches the template. * * If the header specifies new_producers then apply them accordingly. */ block_header_state block_header_state::next( const signed_block_header& h, vector<signature_type>&& _additional_signatures, bool skip_validate_signee )const { return next( h.timestamp, h.confirmed ) .finish_next( h, std::move(_additional_signatures), skip_validate_signee ); } digest_type block_header_state::sig_digest()const { auto header_bmroot = digest_type::hash( std::make_pair( header.digest(), blockroot_merkle.get_root() ) ); return digest_type::hash( std::make_pair(header_bmroot, pending_schedule.schedule_hash) ); } void block_header_state::sign( const signer_callback_type& signer ) { auto d = sig_digest(); auto sigs = signer( d ); EOS_ASSERT(!sigs.empty(), no_block_signatures, "Signer returned no signatures"); header.producer_signature = sigs.back(); sigs.pop_back(); additional_signatures = std::move(sigs); verify_signee(); } void block_header_state::verify_signee( )const { size_t num_keys_in_authority = valid_block_signing_authority.visit([](const auto &a){ return a.keys.size(); }); EOS_ASSERT(1 + additional_signatures.size() <= num_keys_in_authority, wrong_signing_key, "number of block signatures (${num_block_signatures}) exceeds number of keys in block signing authority (${num_keys})", ("num_block_signatures", 1 + additional_signatures.size()) ("num_keys", num_keys_in_authority) ("authority", valid_block_signing_authority) ); std::set<public_key_type> keys; auto digest = sig_digest(); keys.emplace(fc::crypto::public_key( header.producer_signature, digest, true )); for (const auto& s: additional_signatures) { auto res = keys.emplace(s, digest, true); EOS_ASSERT(res.second, wrong_signing_key, "block signed by same key twice", ("key", *res.first)); } bool is_satisfied = false; size_t relevant_sig_count = 0; std::tie(is_satisfied, relevant_sig_count) = producer_authority::keys_satisfy_and_relevant(keys, valid_block_signing_authority); EOS_ASSERT(relevant_sig_count == keys.size(), wrong_signing_key, "block signed by unexpected key", ("signing_keys", keys)("authority", valid_block_signing_authority)); EOS_ASSERT(is_satisfied, wrong_signing_key, "block signatures do not satisfy the block signing authority", ("signing_keys", keys)("authority", valid_block_signing_authority)); } } } /// namespace eosio::chain
#include <okiidoku/db/serdes.hpp> #include <okiidoku/house_mask.hpp> #include <iostream> #include <algorithm> #include <array> #include <limits> // numeric_limits #include <cassert> namespace okiidoku::mono::db::serdes { namespace detail { template<Order O> requires(is_order_compiled(O)) class SerdesHelper; } template<Order O> requires(is_order_compiled(O)) class detail::SerdesHelper final { using T = traits<O>; using cands_t = HouseMask<O>; using val_t = typename T::o2x_t; using o4i_t = typename T::o4i_t; static constexpr unsigned num_buf_bytes {1}; using buf_t = uint_smolN_t<2*8*num_buf_bytes>; // x2 to prevent overflow static_assert((1<<(2*8*num_buf_bytes)) > (2*T::O2)); // requirement to handle overflow public: SerdesHelper() noexcept: row_cands{house_mask_ones<O>} { h_chute_boxes_cands.fill(house_mask_ones<O>); cols_cands.fill(house_mask_ones<O>); cell_cands = house_mask_ones<O>; cell_rmi = 0; buf = 0; buf_pos = 1; } [[nodiscard, gnu::pure]] o4i_t get_cell_rmi() const noexcept { return cell_rmi; } void advance() noexcept; // automatically removes val as a candidate of future cells. void print_val(std::ostream&, val_t val) noexcept; void print_remaining_buf(std::ostream&) noexcept; // automatically removes val as a candidate of future cells. [[nodiscard]] val_t parse_val(std::istream&) noexcept; private: void remove_cand_at_current_rmi_(val_t cand) noexcept; // hypothetical candidates remaining for future cells // based on already encountered (printed/parsed) cells. cands_t row_cands; std::array<cands_t, T::O1> h_chute_boxes_cands; std::array<cands_t, T::O2> cols_cands; // hypothetical candidates of cell to print/parse. cands_t cell_cands; o4i_t cell_rmi; // current small buffer of data to print/parse. static constexpr buf_t buf_end {buf_t{8*num_buf_bytes}}; buf_t buf; buf_t buf_pos; }; template<Order O> requires(is_order_compiled(O)) void detail::SerdesHelper<O>::advance() noexcept { ++cell_rmi; if (cell_rmi % T::O2 == 0) [[unlikely]] { row_cands = house_mask_ones<O>; } if (cell_rmi % T::O3 == 0) [[unlikely]] { h_chute_boxes_cands.fill(house_mask_ones<O>); } auto& box_cands {h_chute_boxes_cands[cell_rmi / T::O3]}; auto& col_cands {cols_cands[cell_rmi / T::O2]}; cell_cands = row_cands & col_cands & box_cands; } template<Order O> requires(is_order_compiled(O)) void detail::SerdesHelper<O>::print_val(std::ostream& os, const typename detail::SerdesHelper<O>::val_t val) noexcept { // The number of possible different values that this cell could be // based on the values that have already been encountered. auto smol_val_buf_remaining {cell_cands.count()}; assert(smol_val_buf_remaining > 0); // implied by contract (grid_follows_rule) // Some slightly-weird-looking logic stems from the fact that it is // a "null" action to try to print something that can only take on one // value (as in- the buffer will be unchanged). Just keep that in mind. auto smol_val_buf {static_cast<val_t>(cell_cands.count_bits_below(val))}; assert(smol_val_buf < smol_val_buf_remaining); while (smol_val_buf_remaining > 1) { buf += static_cast<buf_t>(buf_pos * smol_val_buf); // should never overflow // const auto buf_remaining {(buf_pos == 1) ? buf_end : static_cast<buf_t>(buf_end - buf_pos)}; { const auto use_factor {static_cast<buf_t>(smol_val_buf_remaining)}; assert(buf_pos != 0 && buf_pos < buf_end); buf_pos *= use_factor; smol_val_buf /= static_cast<val_t>(use_factor); smol_val_buf_remaining /= static_cast<typename T::o2i_t>(use_factor); } if (buf_pos >= buf_end) { // TODO.asap should this be a while loop? static_assert(num_buf_bytes == 1); // otherwise the below needs to change. os.put(static_cast<char>(buf)); buf >>= 8 * num_buf_bytes; buf_pos = static_cast<buf_t>((buf_pos % buf_end) + 1); } } remove_cand_at_current_rmi_(val); } template<Order O> requires(is_order_compiled(O)) void detail::SerdesHelper<O>::print_remaining_buf(std::ostream& os) noexcept { if (buf_pos > 1) { os.put(static_cast<char>(buf)); } // TODO should there be some mechanism to disable further printing? or just write a contract? } template<Order O> requires(is_order_compiled(O)) typename detail::SerdesHelper<O>::val_t detail::SerdesHelper<O>::parse_val(std::istream& is) noexcept { // The number of possible different values that this cell could be // based on the values that have already been encountered. auto smol_val_buf_remaining {cell_cands.count()}; assert(smol_val_buf_remaining > 0); // implied by contract (grid_follows_rule) (void)smol_val_buf_remaining; (void)is; val_t smol_val_buf {0}; // TODO.asap assert(smol_val_buf < smol_val_buf_remaining); const auto val {cell_cands.get_index_of_nth_set_bit(smol_val_buf)}; remove_cand_at_current_rmi_(val); return val; } template<Order O> requires(is_order_compiled(O)) void detail::SerdesHelper<O>::remove_cand_at_current_rmi_(const typename SerdesHelper<O>::val_t cand) noexcept { auto& box_cands {h_chute_boxes_cands[cell_rmi / T::O3]}; auto& col_cands {cols_cands[cell_rmi / T::O2]}; cands_t::unset3(cand, row_cands, box_cands, col_cands); } template<Order O> void print_filled(std::ostream& os, const Grid<O>& grid) { assert(grid_is_filled<O>(grid)); assert(grid_follows_rule(grid)); using T = traits<O>; detail::SerdesHelper<O> helper {}; for (; helper.get_cell_rmi() < T::O4; helper.advance()) { const auto row {helper.get_cell_rmi() / T::O2}; const auto col {helper.get_cell_rmi() % T::O2}; if ((T::O1-1-row)/T::O1 == col/T::O1) { continue; // skip cells in the anti-diagonal boxes } using val_t = typename traits<O>::o2x_t; const auto val {static_cast<val_t>(grid.at_row_major(helper.get_cell_rmi()))}; helper.print_val(os, val); } helper.print_remaining_buf(os); } template<Order O> void parse_filled(std::istream& is, Grid<O>& grid) { using T = traits<O>; detail::SerdesHelper<O> helper {}; for (; helper.get_cell_rmi() < T::O4; helper.advance()) { const auto row {helper.get_cell_rmi() / T::O2}; const auto col {helper.get_cell_rmi() % T::O2}; if ((T::O1-1-row)/T::O1 == col/T::O1) { continue; // skip cells in the anti-diagonal boxes } const auto val {helper.parse_val(is)}; grid.at_row_major(helper.get_cell_rmi()) = static_cast<grid_val_t<O>>(val); } // TODO.asap infer cells in anti-diagonal boxes. assert(grid_is_filled(grid)); assert(grid_follows_rule(grid)); } template<Order O> void print_puzzle(std::ostream& os, const Grid<O>& grid) { assert(grid_follows_rule(grid)); // using T = traits<O>; (void)os; (void)grid; } template<Order O> void parse_puzzle(std::istream& is, Grid<O>& grid) { // using T = traits<O>; (void)is; (void)grid; assert(grid_follows_rule(grid)); assert(grid_follows_rule(grid)); } #define OKIIDOKU_FOR_COMPILED_O(O_) \ template void print_filled<O_>(std::ostream&, const Grid<O_>&); \ template void parse_filled<O_>(std::istream&, Grid<O_>&); \ template void print_puzzle<O_>(std::ostream&, const Grid<O_>&); \ template void parse_puzzle<O_>(std::istream&, Grid<O_>&); OKIIDOKU_INSTANTIATE_ORDER_TEMPLATES #undef OKIIDOKU_FOR_COMPILED_O } namespace okiidoku::visitor::db::serdes { void print_filled(std::ostream& os, const Grid& vis_src) { return std::visit([&](auto& mono_src) { return mono::db::serdes::print_filled(os, mono_src); }, vis_src.get_mono_variant()); } void parse_filled(std::istream& is, Grid& vis_sink) { return std::visit([&](auto& mono_sink) { return mono::db::serdes::parse_filled(is, mono_sink); }, vis_sink.get_mono_variant()); } void print_puzzle(std::ostream& os, const Grid& vis_src) { return std::visit([&](auto& mono_src) { return mono::db::serdes::print_puzzle(os, mono_src); }, vis_src.get_mono_variant()); } void parse_puzzle(std::istream& is, Grid& vis_sink) { return std::visit([&](auto& mono_sink) { return mono::db::serdes::parse_puzzle(is, mono_sink); }, vis_sink.get_mono_variant()); } }
/* Copyright 2017 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/compiler/xla/shape_util.h" #include <algorithm> #include <functional> #include <numeric> #include <optional> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/inlined_vector.h" #include "absl/hash/hash.h" #include "absl/strings/ascii.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "tensorflow/compiler/xla/index_util.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/overflow_util.h" #include "tensorflow/compiler/xla/permutation_util.h" #include "tensorflow/compiler/xla/primitive_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/platform/logging.h" namespace xla { using absl::StrAppend; using absl::StrCat; namespace { // An array that is indexed by PrimitiveType, and returns // the size of each element of that primitive type, or 0 // if the PrimitiveType is not a primitive type constexpr uint8_t primitive_byte_size[PrimitiveType_ARRAYSIZE] = { 0, // PRIMITIVE_TYPE_INVALID = 0, sizeof(int8_t), // PRED = 1 sizeof(int8_t), // S8 = 2 sizeof(int16_t), // S16 = 3 sizeof(int32_t), // S32 = 4 sizeof(int64_t), // S64 = 5 sizeof(uint8_t), // U8 = 6 sizeof(uint16_t), // U16 = 7 sizeof(uint32_t), // U32 = 8 sizeof(uint64_t), // U64 = 9 sizeof(float) / 2, // F16 = 10 sizeof(float), // F32 = 11 sizeof(double), // F64 = 12 0, // TUPLE = 13 0, // OPAQUE_TYPE = 14 sizeof(complex64), // C64 = 15 sizeof(float) / 2, // BF16 = 16 0, // TOKEN = 17 sizeof(complex128) // C128 = 18 }; constexpr int64_t kAnnotationPrintInterval = 5; } // namespace std::string ShapeIndex::ToString() const { return StrCat("{", absl::StrJoin(*this, ","), "}"); } std::ostream& operator<<(std::ostream& out, const ShapeIndex& shape_index) { out << shape_index.ToString(); return out; } /* static */ bool ShapeUtil::IsArrayPrimitiveType( PrimitiveType primitive_type) { return primitive_util::IsArrayType(primitive_type); } namespace { // Constructs and returns the new shape with the given minor_to_major order in // its Layout. StatusOr<Shape> MakeShapeWithLayoutInternal( PrimitiveType element_type, absl::Span<const int64_t> dimensions, absl::Span<const int64_t> minor_to_major, absl::Span<const Tile> tiles, int64_t element_size_in_bits, int64_t memory_space) { if (dimensions.size() != minor_to_major.size()) { return InvalidArgument("Dimensions size is %ld, but layout size is %ld.", dimensions.size(), minor_to_major.size()); } if (element_type == OPAQUE_TYPE || element_type == TUPLE) { return InvalidArgument("Unsupported element type: %s", PrimitiveType_Name(element_type)); } TF_ASSIGN_OR_RETURN(Shape shape, ShapeUtil::MakeValidatedShape(element_type, dimensions)); if (element_size_in_bits == ShapeUtil::ByteSizeOfPrimitiveType(element_type) * 8) { // Only set element_size_in_bits if it's different from the default value. element_size_in_bits = 0; } *shape.mutable_layout() = LayoutUtil::MakeLayout( minor_to_major, tiles, element_size_in_bits, memory_space); if (!shape.has_layout()) { return InvalidArgument("Shape has no layout."); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShape(shape)); return shape; } template <typename T> const T& Deref(const T* ptr) { DCHECK(ptr != nullptr); return *ptr; } template <typename T> const T& Deref(const T& ref) { return ref; } template <typename ShapePtrOrRef> Shape MakeTupleShapeImpl(absl::Span<ShapePtrOrRef> shapes) { Shape result; result.set_element_type(TUPLE); result.mutable_tuple_shapes()->reserve(shapes.size()); for (const auto& shape : shapes) { ShapeUtil::AppendShapeToTuple(Deref(shape), &result); } TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(result)); return result; } } // namespace /* static */ bool ShapeUtil::Equal(const Shape& lhs, const Shape& rhs) { bool equal = Shape::Equal()(lhs, rhs); if (!equal && VLOG_IS_ON(3)) { VLOG(3) << "ShapeUtil::Equal differ: lhs = " << lhs.ShortDebugString() << ", rhs = " << rhs.ShortDebugString(); } return equal; } /* static */ bool ShapeUtil::EqualIgnoringElementType(const Shape& lhs, const Shape& rhs) { bool equal = Shape::Equal().IgnoreElementType()(lhs, rhs); if (!equal && VLOG_IS_ON(3)) { VLOG(3) << "ShapeUtil::EqualIgnoringElementType differ: lhs = " << lhs.ShortDebugString() << ", rhs = " << rhs.ShortDebugString(); } return equal; } /* static */ bool ShapeUtil::EqualIgnoringFpPrecision(const Shape& lhs, const Shape& rhs) { bool equal = Shape::Equal().IgnoreFpPrecision()(lhs, rhs); if (!equal && VLOG_IS_ON(3)) { VLOG(3) << "ShapeUtil::EqualIgnoringFpPrecision differ: lhs = " << lhs.ShortDebugString() << ", rhs = " << rhs.ShortDebugString(); } return equal; } /* static */ bool ShapeUtil::EqualStructure(const Shape& lhs, const Shape& rhs) { bool equal = true; ForEachSubshape(lhs, [&](const Shape& /*subshape*/, const ShapeIndex& index) { equal &= IndexIsValid(rhs, index); }); ForEachSubshape(rhs, [&](const Shape& /*subshape*/, const ShapeIndex& index) { equal &= IndexIsValid(lhs, index); }); return equal; } /* static */ int64_t ShapeUtil::TrueRank(const Shape& shape) { int64_t accum = 0; for (int64_t dimension : shape.dimensions()) { // We do not count zero dimensions. if (dimension != 1) { accum += 1; } } return accum; } /* static */ bool ShapeUtil::FillNewShape(PrimitiveType element_type, absl::Span<const int64_t> dimensions, Shape* shape) { const int eint = static_cast<int>(element_type); int64_t dense_shape_size = ((eint >= 0 && eint < PrimitiveType_ARRAYSIZE) ? primitive_byte_size[eint] : 0); // Out of range: force a failure if (dense_shape_size <= 0) { return false; } // Verify that array-based lookup is consistent with public API. DCHECK_EQ(dense_shape_size, ByteSizeOfPrimitiveType(element_type)) << element_type; shape->set_element_type(element_type); const int ndims = dimensions.size(); auto layout = shape->mutable_layout(); layout->set_format(DENSE); auto* minor_to_major = layout->mutable_minor_to_major(); for (int i = 0; i < ndims; i++) { const int64_t d = dimensions[i]; if (d < 0) { return false; } dense_shape_size = MultiplyWithoutOverflow(dense_shape_size, d); if (dense_shape_size < 0) { return false; } shape->add_dimensions(d); minor_to_major->push_back(ndims - 1 - i); } return true; } /* static */ ProgramShape ShapeUtil::MakeProgramShape( std::initializer_list<Shape> parameters, Shape result) { ProgramShape program_shape; for (const Shape& shape : parameters) { *program_shape.add_parameters() = shape; } *program_shape.mutable_result() = std::move(result); return program_shape; } /* static */ Shape ShapeUtil::MakeShape(PrimitiveType element_type, absl::Span<const int64_t> dimensions) { Shape shape; CHECK(FillNewShape(element_type, dimensions, &shape)); return shape; } /* static */ Shape ShapeUtil::MakeScalarShape(PrimitiveType element_type) { return MakeShape(element_type, {}); } /* static */ Shape ShapeUtil::MakeShape( PrimitiveType element_type, absl::Span<const int64_t> dimensions, const std::vector<bool>& dynamic_dimensions) { return MakeValidatedShape(element_type, dimensions, dynamic_dimensions) .ValueOrDie(); } /* static */ Shape ShapeUtil::MakeShapeWithStaticDimensions( const Shape& shape) { Shape output = shape; output.clear_dynamic_dimensions(); return output; } /* static */ StatusOr<Shape> ShapeUtil::MakeValidatedShape( PrimitiveType element_type, absl::Span<const int64_t> dimensions) { Shape shape; if (!FillNewShape(element_type, dimensions, &shape)) { return InvalidArgument("invalid shape type=%d, dims=[%s]", static_cast<int>(element_type), absl::StrJoin(dimensions, ",")); } return shape; } /* static */ StatusOr<Shape> ShapeUtil::MakeValidatedShape( PrimitiveType element_type, absl::Span<const int64_t> dimensions, const std::vector<bool>& dynamic_dimensions) { if (dynamic_dimensions.size() != dimensions.size()) { return InvalidArgument( "dynamic dimensions size %d did not match number of dimensions %d", dynamic_dimensions.size(), dimensions.size()); } Shape shape; if (!FillNewShape(element_type, dimensions, &shape)) { return InvalidArgument("invalid shape type=%d, dims=[%s]", static_cast<int>(element_type), absl::StrJoin(dimensions, ",")); } for (int i = 0, n = dimensions.size(); i < n; i++) { shape.set_dynamic_dimension(i, dynamic_dimensions[i]); } return shape; } /* static */ Shape ShapeUtil::MakeShapeWithLayout( PrimitiveType element_type, absl::Span<const int64_t> dimensions, absl::Span<const int64_t> minor_to_major, absl::Span<const Tile> tiles, int64_t element_size_in_bits, int64_t memory_space) { auto ret = MakeShapeWithLayoutInternal(element_type, dimensions, minor_to_major, tiles, element_size_in_bits, memory_space); if (!ret.ok()) LOG(ERROR) << ret.status(); return ret.ValueOrDie(); } /* static */ Shape ShapeUtil::MoveDimToMajor(const Shape& shape, int64_t dim) { if (shape.IsTuple()) { std::vector<Shape> result_shapes; result_shapes.reserve(shape.tuple_shapes_size()); for (const Shape& s : shape.tuple_shapes()) { result_shapes.push_back(MoveDimToMajor(s, dim)); } return ShapeUtil::MakeTupleShape(result_shapes); } Shape ret = shape; if (!ret.has_layout()) { LayoutUtil::SetToDefaultLayout(&ret); } *ret.mutable_layout() = LayoutUtil::MoveDimToMajor(ret.layout(), dim); DimensionVector minor_to_major; for (int64_t d : LayoutUtil::MinorToMajor(ret)) { if (d != dim) { minor_to_major.push_back(d); } } minor_to_major.push_back(dim); *ret.mutable_layout() = LayoutUtil::MakeLayout(minor_to_major); return ret; } /* static */ Shape ShapeUtil::MakeShapeWithDescendingLayout( PrimitiveType element_type, absl::Span<const int64_t> dimensions) { std::vector<int64_t> layout(dimensions.size()); std::iota(layout.rbegin(), layout.rend(), static_cast<int64_t>(0)); return MakeShapeWithLayout(element_type, dimensions, layout); } /* static */ Shape ShapeUtil::MakeShapeWithDescendingLayoutAndSamePhysicalLayout( const Shape& shape) { std::vector<int64_t> dims(shape.dimensions_size()); for (int i = 0; i < shape.dimensions_size(); ++i) { dims[i] = shape.dimensions(LayoutUtil::Major(shape.layout(), i)); } Shape new_shape = MakeShapeWithDescendingLayout(shape.element_type(), dims); // Since the physical layout is kept the same, the tiles and element size are // the same also. new_shape.mutable_layout()->mutable_tiles()->assign( shape.layout().tiles().begin(), shape.layout().tiles().end()); new_shape.mutable_layout()->set_element_size_in_bits( shape.layout().element_size_in_bits()); for (int i = 0; i < shape.dimensions_size(); ++i) { new_shape.set_dynamic_dimension(i, shape.is_dynamic_dimension(i)); } return new_shape; } /* static */ Status ShapeUtil::PopulateShape( PrimitiveType element_type, absl::Span<const int64_t> dimensions, Shape* shape) { shape->Clear(); shape->set_element_type(element_type); for (int64_t dimension : dimensions) { shape->add_dimensions(dimension); } LayoutUtil::SetToDefaultLayout(shape); return ValidateShape(*shape); } /* static */ Shape ShapeUtil::MakeStaticShape(const Shape& original) { Shape result = original; result.clear_dynamic_dimensions(); return result; } /* static */ Shape ShapeUtil::MakeTupleShape(absl::Span<const Shape> shapes) { return MakeTupleShapeImpl(shapes); } /* static */ Shape ShapeUtil::MakeTupleShapeWithPtrs( absl::Span<const Shape* const> shapes) { return MakeTupleShapeImpl(shapes); } /* static */ Shape ShapeUtil::MakeMaybeTupleShape( absl::Span<const Shape> shapes) { if (shapes.size() == 1) { return shapes[0]; } return MakeTupleShape(shapes); } /* static */ Shape ShapeUtil::MakeOpaqueShape() { Shape result; result.set_element_type(OPAQUE_TYPE); TF_DCHECK_OK(ValidateShapeWithOptionalLayout(result)); return result; } /* static */ Shape ShapeUtil::MakeTokenShape() { Shape result; result.set_element_type(TOKEN); TF_DCHECK_OK(ValidateShapeWithOptionalLayout(result)); return result; } /* static */ void ShapeUtil::AppendShapeToTuple(const Shape& shape, Shape* tuple_shape) { TF_DCHECK_OK(ValidateShapeWithOptionalLayout(shape)); *tuple_shape->add_tuple_shapes() = shape; } /* static */ void ShapeUtil::UpdateTupleShape(const Shape& shape, int64_t index, Shape* tuple_shape) { CHECK(index < tuple_shape->tuple_shapes_size()); *tuple_shape->mutable_tuple_shapes(index) = shape; } /* static */ void ShapeUtil::UpdateDynamicDimension(Shape* shape, ShapeIndexView index, int64_t dim, bool is_dynamic) { if (index.empty()) { CHECK(!shape->IsTuple()); shape->set_dynamic_dimension(dim, is_dynamic); return; } UpdateDynamicDimension(shape->mutable_tuple_shapes(index.front()), index.subspan(1), dim, is_dynamic); } /* static */ void ShapeUtil::AppendMajorDimension(int bound, Shape* shape) { CHECK(LayoutUtil::IsDenseArray(*shape)); shape->mutable_layout()->add_minor_to_major(shape->rank()); shape->add_dimensions(bound); TF_DCHECK_OK(ValidateShape(*shape)); } /* static */ void ShapeUtil::AppendMinorDimension(int bound, Shape* shape) { CHECK(LayoutUtil::IsDenseArray(*shape)); // Bump up all values in the layout by one. for (int dim_idx = 0; dim_idx < shape->layout().minor_to_major_size(); dim_idx++) { int layout_idx = shape->layout().minor_to_major(dim_idx); shape->mutable_layout()->set_minor_to_major(dim_idx, layout_idx + 1); } // Then we can safely add zero. shape->mutable_layout()->add_minor_to_major(0); shape->add_dimensions(bound); TF_DCHECK_OK(ValidateShape(*shape)); } /* static */ void ShapeUtil::CopyDynamicDimensions(Shape* to, const Shape& from) { CHECK_EQ(to->rank(), from.rank()); for (int64_t i = 0; i < from.rank(); ++i) { to->set_dynamic_dimension(i, from.is_dynamic_dimension(i)); } TF_DCHECK_OK(ValidateShape(*to)); } /* static */ bool ShapeUtil::ElementIsIntegral(const Shape& shape) { return primitive_util::IsIntegralType(shape.element_type()); } /* static */ bool ShapeUtil::ElementIsIntegralWithBits(const Shape& shape, int32_t bits) { return ElementIsIntegral(shape) && ElementHasBitWidth(shape, bits); } /* static */ bool ShapeUtil::ElementHasBitWidth(const Shape& shape, int bits) { if (!shape.IsArray()) { return false; } return primitive_util::BitWidth(shape.element_type()) == bits; } /* static */ bool ShapeUtil::ElementIsSigned(const Shape& shape) { switch (shape.element_type()) { case S8: case S16: case S32: case S64: case F16: case BF16: case F32: case F64: return true; case PRED: case U8: case U16: case U32: case U64: case C64: case C128: case TUPLE: case OPAQUE_TYPE: case TOKEN: return false; default: LOG(FATAL) << "Unhandled element type " << shape.element_type(); } } /* static */ bool ShapeUtil::ElementIsComplex(const Shape& shape) { return primitive_util::IsComplexType(shape.element_type()); } /* static */ bool ShapeUtil::ElementIsFloating(const Shape& shape) { return primitive_util::IsFloatingPointType(shape.element_type()); } /* static */ bool ShapeUtil::IsNestedTuple(const Shape& shape) { return shape.IsTuple() && absl::c_any_of(shape.tuple_shapes(), [](const Shape& s) { return s.IsTuple(); }); } /* static */ bool ShapeUtil::IsEmptyTuple(const Shape& shape) { return shape.IsTuple() && TupleElementCount(shape) == 0; } /* static */ int64_t ShapeUtil::TupleElementCount(const Shape& shape) { CHECK(shape.IsTuple()) << HumanString(shape); return shape.tuple_shapes_size(); } /* static */ const Shape& ShapeUtil::GetTupleElementShape(const Shape& shape, int64_t index) { CHECK(shape.IsTuple()); CHECK_GT(TupleElementCount(shape), index); TF_DCHECK_OK(ValidateShapeWithOptionalLayout(shape.tuple_shapes(index))); return shape.tuple_shapes(index); } /* static */ int64_t ShapeUtil::SubshapeCount(const Shape& shape) { int64_t n = 0; ForEachSubshape(shape, [&](const Shape& literal_subshape, const ShapeIndex& index) { ++n; }); return n; } /* static */ Shape ShapeUtil::SliceTuple(const Shape& tuple, int64_t start, int64_t limit) { TF_DCHECK_OK(ValidateShapeWithOptionalLayout(tuple)); CHECK(tuple.IsTuple()); CHECK_LE(start, TupleElementCount(tuple)); CHECK_LE(limit, TupleElementCount(tuple)); std::vector<Shape> new_elements(tuple.tuple_shapes().begin() + start, tuple.tuple_shapes().begin() + limit); return MakeTupleShape(new_elements); } // Returns the shape of a real or imaginary component. /* static */ Shape ShapeUtil::ComplexComponentShape( const Shape& complex_shape) { CHECK(ElementIsComplex(complex_shape)) << HumanString(complex_shape); return ChangeElementType(complex_shape, primitive_util::ComplexComponentType( complex_shape.element_type())); } /* static */ int64_t ShapeUtil::ElementsIn(const Shape& shape) { DCHECK(shape.IsArray()) << ShapeUtil::HumanString(shape); DCHECK_EQ(shape.dimensions_size(), shape.rank()); if (shape.dimensions().size() == 1) { return shape.dimensions()[0]; } return std::accumulate<decltype(shape.dimensions().begin()), int64_t>( shape.dimensions().begin(), shape.dimensions().end(), 1LL, std::multiplies<int64_t>()); } /* static */ int64_t ShapeUtil::ElementsInRecursive(const Shape& shape) { CHECK(shape.IsArray() || shape.IsTuple()); if (shape.IsArray()) { return ElementsIn(shape); } int64_t count = 0; for (const Shape& element_shape : shape.tuple_shapes()) { count += ElementsInRecursive(element_shape); } return count; } /* static */ bool ShapeUtil::HasPrimitiveType(const Shape& shape, PrimitiveType primitive_type) { if (shape.element_type() == primitive_type) { return true; } for (const Shape& element_shape : shape.tuple_shapes()) { if (HasPrimitiveType(element_shape, primitive_type)) { return true; } } return false; } /* static */ bool ShapeUtil::IsZeroElementArray(const Shape& shape) { return shape.IsArray() && ElementsIn(shape) == 0; } /* static */ bool ShapeUtil::IsScalarWithElementType( const Shape& shape, PrimitiveType element_type) { return IsScalar(shape) && shape.element_type() == element_type; } /* static */ std::string ShapeUtil::HumanString(const Shape& shape) { if (shape.IsTuple()) { std::string text = "("; const auto& tuple_shapes = shape.tuple_shapes(); for (int64_t i = 0; i < tuple_shapes.size(); ++i) { const Shape& elem_shape = tuple_shapes[i]; if (i != 0) { StrAppend(&text, ", "); if (i % kAnnotationPrintInterval == 0) { StrAppend(&text, absl::StrFormat("/*index=%lld*/", i)); } } StrAppend(&text, HumanString(elem_shape)); } text += ")"; return text; } std::vector<std::string> dim_elements; const auto dimensions_size = shape.dimensions_size(); dim_elements.reserve(dimensions_size); for (int i = 0; i < dimensions_size; ++i) { if (shape.is_dynamic_dimension(i)) { dim_elements.push_back(StrCat("<=", shape.dimensions(i))); } else { dim_elements.push_back(StrCat(shape.dimensions(i))); } } return StrCat( primitive_util::LowercasePrimitiveTypeName(shape.element_type()), "[", absl::StrJoin(dim_elements, ","), "]"); } /* static */ std::string ShapeUtil::HumanStringWithLayout(const Shape& shape) { if (shape.IsTuple()) { std::string text = "("; const auto& tuple_shapes = shape.tuple_shapes(); for (int64_t i = 0; i < tuple_shapes.size(); ++i) { const Shape& elem_shape = tuple_shapes[i]; if (i != 0) { StrAppend(&text, ", "); if (i % kAnnotationPrintInterval == 0) { StrAppend(&text, absl::StrFormat("/*index=%lld*/", i)); } } StrAppend(&text, HumanStringWithLayout(elem_shape)); } text += ")"; return text; } std::string result = HumanString(shape); if (IsScalar(shape)) { std::string layout_str = LayoutUtil::HumanString(shape.layout()); // Don't print "{}" as layout for scalars. if (layout_str != "{}") { StrAppend(&result, layout_str); } } else if (shape.IsArray() && LayoutUtil::HasLayout(shape)) { StrAppend(&result, LayoutUtil::HumanString(shape.layout())); } return result; } /* static */ std::string ShapeUtil::HumanString( const ProgramShape& program_shape) { std::vector<std::string> parameters; const auto& shape_parameters = program_shape.parameters(); parameters.reserve(shape_parameters.size()); for (const auto& shape : shape_parameters) { const int i = parameters.size(); parameters.push_back(StrCat(i < program_shape.parameter_names_size() ? program_shape.parameter_names(i) : "(unknown)", ": ", HumanString(shape))); } return StrCat("(", absl::StrJoin(parameters, ", "), ") -> ", HumanString(program_shape.result())); } /* static */ bool ShapeUtil::SameDimensions(const Shape& lhs, const Shape& rhs) { CHECK(lhs.IsArray()); CHECK(rhs.IsArray()); return absl::c_equal(lhs.dimensions(), rhs.dimensions()); } /* static */ bool ShapeUtil::SameRank(const Shape& lhs, const Shape& rhs) { CHECK(lhs.IsArray()); CHECK(rhs.IsArray()); return lhs.rank() == rhs.rank(); } /* static */ bool ShapeUtil::Compatible(const Shape& lhs, const Shape& rhs) { return Shape::Equal().IgnoreDynamicDimension().IgnoreLayout()(lhs, rhs); } /* static */ bool ShapeUtil::CompatibleIgnoringElementType(const Shape& lhs, const Shape& rhs) { return Shape::Equal() .IgnoreDynamicDimension() .IgnoreElementType() .IgnoreLayout()(lhs, rhs); } /* static */ bool ShapeUtil::CompatibleKind(const Shape& lhs, const Shape& rhs) { return Shape::Equal() .IgnoreElementType() .IgnoreLayout() .IgnoreDimensions() .IgnoreDynamicDimension()(lhs, rhs); } /* static */ bool ShapeUtil::CompatibleIgnoringFpPrecision(const Shape& lhs, const Shape& rhs) { return Shape::Equal() .IgnoreDynamicDimension() .IgnoreFpPrecision() .IgnoreLayout()(lhs, rhs); } /* static */ int64_t ShapeUtil::GetDimension(const Shape& shape, int64_t dimension_number) { return shape.dimensions(GetDimensionNumber(shape, dimension_number)); } /* static */ int64_t ShapeUtil::GetDimensionNumber(const Shape& shape, int64_t dimension_number) { if (dimension_number < 0) { dimension_number += shape.rank(); } CHECK_GE(dimension_number, 0); return dimension_number; } /* static */ int64_t ShapeUtil::ByteSizeOfPrimitiveType( PrimitiveType primitive_type) { switch (primitive_type) { case PRED: return sizeof(int8_t); case S8: return sizeof(int8_t); case S16: return sizeof(int16_t); case S32: return sizeof(int32_t); case S64: return sizeof(int64_t); case U8: return sizeof(uint8_t); case U16: return sizeof(uint16_t); case U32: return sizeof(uint32_t); case U64: return sizeof(uint64_t); case BF16: return sizeof(float) / 2; case F16: return sizeof(float) / 2; case F32: return sizeof(float); case F64: return sizeof(double); case C64: return sizeof(complex64); case C128: return sizeof(complex128); case TOKEN: // Tokens require no space. return 0; case TUPLE: case OPAQUE_TYPE: LOG(FATAL) << PrimitiveType_Name(primitive_type) << " primitive type has no definitive size"; default: LOG(FATAL) << "Unhandled primitive type " << primitive_type; } } /* static */ int64_t ShapeUtil::ByteSizeOf(const Shape& shape, int64_t pointer_size) { TF_DCHECK_OK(ValidateShape(shape)); if (shape.element_type() == TUPLE) { return ByteSizeOfTupleIndexTable(shape, pointer_size); } else if (shape.IsArray()) { return ByteSizeOfElements(shape); } else if (shape.element_type() == TOKEN) { return 0; } else if (shape.element_type() == OPAQUE_TYPE) { CHECK_GT(pointer_size, 0); return pointer_size; } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " primitive type has no definitive size"; } /* static */ int64_t ShapeUtil::ByteSizeOfTupleIndexTable( const Shape& shape, int64_t pointer_size) { TF_DCHECK_OK(ValidateShape(shape)); CHECK_EQ(TUPLE, shape.element_type()); CHECK_GT(pointer_size, 0); return pointer_size * shape.tuple_shapes_size(); } /* static */ int64_t ShapeUtil::ByteSizeOfElements(const Shape& shape) { TF_DCHECK_OK(ValidateShape(shape)); CHECK(shape.IsArray()); int64_t allocated_element_count; CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ShortDebugString(); allocated_element_count = ElementsIn(shape); return allocated_element_count * ByteSizeOfPrimitiveType(shape.element_type()); } /* static */ Status ShapeUtil::ValidateShapeWithOptionalLayoutInternal( const Shape& shape) { if (shape.element_type() == PRIMITIVE_TYPE_INVALID || !PrimitiveType_IsValid(shape.element_type())) { return InvalidArgument("shape has invalid element type: %s", shape.ShortDebugString()); } if (shape.element_type() == TUPLE) { if (shape.dimensions_size() != 0) { return InvalidArgument("tuples must not have dimensions specified"); } for (auto& element_shape : shape.tuple_shapes()) { TF_RETURN_IF_ERROR( ValidateShapeWithOptionalLayoutInternal(element_shape)); } return OkStatus(); } // Non-tuple shape. if (shape.tuple_shapes_size() > 0) { return InvalidArgument("non-tuple shape has tuple_shapes field"); } // Tokens and opaques can should not have layout or dimensions. if (shape.element_type() == TOKEN || shape.element_type() == OPAQUE_TYPE) { if (shape.dimensions_size() != 0) { return InvalidArgument( "shape has %s element type, but has dimensions field: %s", primitive_util::LowercasePrimitiveTypeName(shape.element_type()), shape.ShortDebugString()); } if (shape.has_layout()) { return InvalidArgument( "shape has %s element type, but has layout field: %s", primitive_util::LowercasePrimitiveTypeName(shape.element_type()), shape.ShortDebugString()); } return OkStatus(); } for (int64_t i = 0; i < shape.rank(); ++i) { int64_t dimension = shape.dimensions(i); if (dimension < 0) { return InvalidArgument( "shape's dimensions must not be < 0; dimension at index %d was %d", i, dimension); } } TF_RETURN_IF_ERROR(ValidateShapeSize(shape)); return OkStatus(); } /* static */ Status ShapeUtil::ValidateShapeSize(const Shape& shape) { VLOG(3) << "Validating shape size: " << ShapeUtil::HumanString(shape); if (!shape.IsArray()) { return OkStatus(); } int64_t shape_size = [&]() { int64_t dense_shape_size = 1; if (shape.dimensions().empty()) { return dense_shape_size; } absl::Span<const int64_t> shape_max_dimensions = shape.dimensions(); for (int64_t dim : shape_max_dimensions) { dense_shape_size = MultiplyWithoutOverflow(dense_shape_size, dim); if (dense_shape_size < 0) { return dense_shape_size; } } dense_shape_size = MultiplyWithoutOverflow( dense_shape_size, ByteSizeOfPrimitiveType(shape.element_type())); return dense_shape_size; }(); if (shape_size < 0) { return InvalidArgument("Shape %s size may overflow int64_t.", ShapeUtil::HumanString(shape)); } VLOG(3) << "Shape size is valid: " << shape_size; return OkStatus(); } /* static */ Status ShapeUtil::ValidateShapeWithOptionalLayout( const Shape& shape) { TF_RETURN_IF_ERROR(ValidateShapeWithOptionalLayoutInternal(shape)); return LayoutUtil::ValidateLayoutInShape(shape, /*allow_missing_layouts=*/true); } /* static */ Status ShapeUtil::ValidateShape(const Shape& shape) { TF_RETURN_IF_ERROR(ValidateShapeWithOptionalLayoutInternal(shape)); return LayoutUtil::ValidateLayoutInShape(shape); } /* static */ Shape ShapeUtil::ChangeElementType(const Shape& original, PrimitiveType type) { if (original.IsTuple()) { std::vector<Shape> new_operands; new_operands.reserve(original.tuple_shapes_size()); for (const Shape& operand : original.tuple_shapes()) { new_operands.push_back(ChangeElementType(operand, type)); } return MakeTupleShape(new_operands); } else { Shape new_shape = original; new_shape.set_element_type(type); return new_shape; } } /* static */ bool ShapeUtil::IndexIsValid(const Shape& shape, ShapeIndexView index) { const Shape* subshape = &shape; for (auto i : index) { if (!subshape->IsTuple() || i >= subshape->tuple_shapes_size() || i < 0) { return false; } subshape = &subshape->tuple_shapes(i); } return true; } /* static */ const Shape& ShapeUtil::GetSubshape(const Shape& shape, ShapeIndexView index) { const Shape* return_shape = &shape; for (auto i : index) { CHECK(return_shape->IsTuple()) << "Invalid index " << ShapeIndex(index) << " for shape " << shape; return_shape = &return_shape->tuple_shapes(i); } return *return_shape; } /* static */ StatusOr<const Shape*> ShapeUtil::TryGetSubshape( const Shape& shape, ShapeIndexView index) { const Shape* return_shape = &shape; for (auto i : index) { if (!return_shape->IsTuple() || i < 0 || i >= return_shape->tuple_shapes_size()) { return InvalidArgument( "Shape index %s not a valid subshape index for tuple with shape %s", ShapeIndex(index).ToString(), shape.DebugString()); } return_shape = &return_shape->tuple_shapes(i); } return return_shape; } /* static */ Shape* ShapeUtil::GetMutableSubshape(Shape* shape, ShapeIndexView index) { Shape* return_shape = shape; for (auto i : index) { CHECK(return_shape->IsTuple()); return_shape = return_shape->mutable_tuple_shapes(i); } return return_shape; } /* static */ bool ShapeUtil::IsLeafIndex(const Shape& shape, const ShapeIndex& index) { return !GetSubshape(shape, index).IsTuple(); } /* static */ int64_t ShapeUtil::GetLeafCount(const Shape& shape) { if (!shape.IsTuple()) { return 1; } int64_t count = 0; for (const Shape& subshape : shape.tuple_shapes()) { count += GetLeafCount(subshape); } return count; } /* static */ std::vector<ShapeUtil::IndexedShape> ShapeUtil::GetLeafShapes( const Shape& shape) { std::vector<IndexedShape> leaves; ForEachSubshape(shape, [&](const Shape& sub_shape, const ShapeIndex& index) { if (IsLeafIndex(shape, index)) { leaves.emplace_back(index, sub_shape); } }); return leaves; } /* static */ bool ShapeUtil::HasDegenerateDimensions(const Shape& shape) { CHECK(shape.IsArray()); return absl::c_linear_search(shape.dimensions(), 1); } /* static */ Shape ShapeUtil::DropDegenerateDimensions(const Shape& shape) { return FilterDimensions( [&](int64_t dim) -> bool { return shape.dimensions()[dim] != 1; }, shape); } namespace { // Helper for ForEachSubshape which visits the subshapes of the given shape in // DFS pre-order starting with the index. Status ForEachSubshapeHelper(const Shape& shape, const ShapeUtil::StatusVisitorFunction& func, ShapeIndex* index) { TF_RETURN_IF_ERROR(func(shape, *index)); if (shape.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { index->push_back(i); TF_RETURN_IF_ERROR(ForEachSubshapeHelper( ShapeUtil::GetTupleElementShape(shape, i), func, index)); index->pop_back(); } } return OkStatus(); } // Helper for ForEachMutableSubshape which visits the subshapes of the given // shape in DFS pre-order starting with the index. Status ForEachMutableSubshapeHelper( Shape* shape, const ShapeUtil::MutatingStatusVisitorFunction& func, ShapeIndex* index) { TF_RETURN_IF_ERROR(func(shape, *index)); if (shape->IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(*shape); ++i) { index->push_back(i); TF_RETURN_IF_ERROR(ForEachMutableSubshapeHelper( shape->mutable_tuple_shapes(i), func, index)); index->pop_back(); } } return OkStatus(); } } // namespace /* static */ void ShapeUtil::ForEachSubshape(const Shape& shape, const VisitorFunction& func) { ShapeIndex index; ForEachSubshapeHelper( shape, [&func](const Shape& subshape, const ShapeIndex& index) { func(subshape, index); return OkStatus(); }, &index) .IgnoreError(); } /* static */ void ShapeUtil::ForEachMutableSubshape( Shape* shape, const MutatingVisitorFunction& func) { ShapeIndex index; ForEachMutableSubshapeHelper( shape, [&func](Shape* subshape, const ShapeIndex& index) { func(subshape, index); return OkStatus(); }, &index) .IgnoreError(); } /* static */ Status ShapeUtil::ForEachSubshapeWithStatus( const Shape& shape, const StatusVisitorFunction& func) { ShapeIndex index; return ForEachSubshapeHelper(shape, func, &index); } /* static */ Status ShapeUtil::ForEachMutableSubshapeWithStatus( Shape* shape, const MutatingStatusVisitorFunction& func) { ShapeIndex index; return ForEachMutableSubshapeHelper(shape, func, &index); } /* static */ Shape ShapeUtil::PermuteDimensions( absl::Span<const int64_t> permutation, const Shape& shape) { Shape new_shape = shape; new_shape.clear_dimensions(); for (auto dim : Permute(shape.dimensions(), permutation)) { new_shape.add_dimensions(dim); } auto inv_permutation = InversePermutation(permutation); for (int64_t i = 0; i < shape.rank(); i++) { new_shape.set_dynamic_dimension(inv_permutation[i], shape.is_dynamic_dimension(i)); } // If `shape` has a layout, by contract we choose a new layout such that the // transpose defined by this permutation is a bitcast. // // Some formalism helps to understand the correct way to do this. We're going // to do algebra in the group of permutations of the dimensions of `shape`. // // Since the order of `shape`'s dimensions is not permuted relative to itself, // `shape`'s list of dimensions is isomorphic to the identity I. // // Let `shape`'s layout be L. A layout is a permutation which maps a // minor-to-major physical dimension ordering to a shape's logical dimension // ordering. Therefore the inverse of a layout maps from logical to physical // dims, and so the physical ordering of I is simply L'.I = L', where L' is // the inverse of L. // // Let the argument `permutation` be P. This is a permutation over `shape`'s // dimensions, so our return value will be a shape with dims P.I = P. Our // goal is to construct a layout permutation L* for this shape. The physical // dimension ordering of this returned shape must be the same as that of the // original shape, namely L'. // // Our returned shape has dims P and layout L*, so its in-memory ordering is // L*'.P. Setting this equal to L' and solving for L*, we get: // // L*'.P = L' => // L*' = L'P' => // L* = P.L // if (shape.has_layout()) { CHECK(LayoutUtil::IsDenseArray(shape)); Layout* new_layout = new_shape.mutable_layout(); new_layout->set_format(DENSE); new_layout->clear_minor_to_major(); for (auto index : ComposePermutations(inv_permutation, shape.layout().minor_to_major())) { new_layout->add_minor_to_major(index); } // The permutation accepted by TransposeIsBitcast is the inverse of the // permutation here. CHECK(TransposeIsBitcast(shape, new_shape, permutation)) << "shape=" << HumanStringWithLayout(shape) << ", new_shape=" << HumanStringWithLayout(new_shape) << ", permutation={" << absl::StrJoin(permutation, ",") << "}"; } return new_shape; } /* static */ std::tuple<bool, std::vector<int64_t>, std::vector<int64_t>> ShapeUtil::InsertedOrDeleted1SizedDimensions(const Shape& shape_pre, const Shape& shape_post) { CHECK(shape_pre.IsArray()); CHECK(shape_post.IsArray()); auto nil = std::make_tuple(false, std::vector<int64_t>(), std::vector<int64_t>()); std::vector<int64_t> deleted_indices; std::vector<int64_t> inserted_indices; // Returns false if any input/output index between prior_unmodified_dim_pair // and unmodified_dim_pair have size >1. Otherwise, returns true and appends // the degerenate input/output dimensions in the gap to // deleted_indices/inserted_indices respectively. auto check_modified_dims = [&shape_pre, &shape_post, &deleted_indices, &inserted_indices]( std::pair<int64_t, int64_t> prior_unmodified_dim_pair, std::pair<int64_t, int64_t> unmodified_dim_pair) { for (int64_t modified_input_dim = prior_unmodified_dim_pair.first + 1; modified_input_dim < unmodified_dim_pair.first; ++modified_input_dim) { if (shape_pre.dimensions(modified_input_dim) > 1) { return false; } deleted_indices.push_back(modified_input_dim); } for (int64_t modified_output_dim = prior_unmodified_dim_pair.second + 1; modified_output_dim < unmodified_dim_pair.second; ++modified_output_dim) { if (shape_post.dimensions(modified_output_dim) > 1) { return false; } inserted_indices.push_back(modified_output_dim); } return true; }; std::vector<std::pair<int64_t, int64_t>> unmodified_dims = DimensionsUnmodifiedByReshape(shape_pre, shape_post); // Returns nil if the reshape modifies any non-degenerate input/output // dimension. DimensionsUnmodifiedByReshape gives us all unmodified // dimensions, so we only need to check whether dimensions in the gaps (thus // modified) have size >1. for (size_t i = 0; i <= unmodified_dims.size(); ++i) { // Check (modified) dimensions between unmodified_dims[i-1] and // unmodified_dims[i]. auto prior_unmodified_dim_pair = i > 0 ? unmodified_dims[i - 1] : std::pair<int64_t, int64_t>(-1, -1); auto unmodified_dim_pair = i < unmodified_dims.size() ? unmodified_dims[i] : std::make_pair(shape_pre.rank(), shape_post.rank()); if (!check_modified_dims(prior_unmodified_dim_pair, unmodified_dim_pair)) { return nil; } } return std::make_tuple(true, deleted_indices, inserted_indices); } /* static */ std::vector<std::pair<int64_t, int64_t>> ShapeUtil::DimensionsUnmodifiedByReshape(const Shape& input_shape, const Shape& output_shape) { CHECK(input_shape.IsArray()); CHECK(output_shape.IsArray()); // Unmodified dimensions are merely common factors of rank 1. auto common_factors = CommonFactors(input_shape.dimensions(), output_shape.dimensions()); for (size_t i = 0; i < common_factors.size() - 1;) { if (1 != common_factors[i + 1].first - common_factors[i].first || 1 != common_factors[i + 1].second - common_factors[i].second) { common_factors.erase(common_factors.begin() + i); } else { ++i; } } // `CommonFactors(a, b).back() == (a.rank, b.rank)` so we must pop it. common_factors.pop_back(); return std::vector<std::pair<int64_t, int64_t>>(common_factors.begin(), common_factors.end()); } /* static */ std::optional<std::vector<int64_t>> ShapeUtil::ReshapeLeavesDimensionsUnmodified( const Shape& from_shape, const Shape& to_shape, absl::Span<const int64_t> input_dim_indices) { if (!std::is_sorted(input_dim_indices.begin(), input_dim_indices.end())) { return std::nullopt; } std::vector<int64_t> output_dim_indices; std::vector<std::pair<int64_t, int64_t>> unmodified_dims = ShapeUtil::DimensionsUnmodifiedByReshape(from_shape, to_shape); size_t i = 0; // index to unmodified_dims for (int64_t input_dim_index : input_dim_indices) { // Search unmodified_dims for input_dim_index. We can search from the last // matching position because input_dim_indices is guaranteed to be sorted. while (i < unmodified_dims.size() && unmodified_dims[i].first < input_dim_index) { ++i; } if (i >= unmodified_dims.size() || unmodified_dims[i].first != input_dim_index) { return std::nullopt; } output_dim_indices.push_back(unmodified_dims[i].second); } return output_dim_indices; } /* static */ bool ShapeUtil::TransposeIsBitcast( const Shape& input_shape, const Shape& output_shape, absl::Span<const int64_t> dimension_mapping) { CHECK(LayoutUtil::HasLayout(input_shape) && LayoutUtil::HasLayout(output_shape)); if (!SameElementType(input_shape, output_shape)) { return false; } // Check the reshape permutes the positions of each dimension in the // minor-to-major order. positions[i]=k means dimension `i` is k-th minor. // input_positions = apply(dimension_mapping, output_positions) // // Because the positions of each dimension are the inverse permutation of the // minor-to-major order, the above check is equivalent to // inverse(input_dimensions) = // apply(dimension_mapping, inverse(output_dimensions)) // # `I` indicates identity permutation. // apply(input_dimensions, I) = // apply(dimension_mapping, apply(output_dimensions, I)) // apply(input_dimensions, I) = // apply((dimension_mapping * output_dimensions), I) // input_dimensions = dimension_mapping * output_dimensions return absl::c_equal( ComposePermutations(dimension_mapping, output_shape.layout().minor_to_major()), input_shape.layout().minor_to_major()); } /* static */ bool ShapeUtil::ReshapeIsBitcast(const Shape& input_shape, const Shape& output_shape) { CHECK(input_shape.IsArray()); CHECK(output_shape.IsArray()); CHECK(LayoutUtil::HasLayout(input_shape)); CHECK(LayoutUtil::HasLayout(output_shape)); if (!SameElementType(input_shape, output_shape)) { return false; } CHECK_EQ(ElementsIn(input_shape), ElementsIn(output_shape)) << "input_shape=" << input_shape.ShortDebugString() << ", output_shape=" << output_shape.ShortDebugString(); if (ElementsIn(input_shape) == 0) { return true; } // TL;DR: The rest of the method checks that the reshape does not change the // physical location of any unit input or output index. Unit indices have // exactly one dimension that equals 1 and other dimensions 0. This condition // is necessary for the reshape to be a bitcast, because a bitcast-equivalent // reshape shouldn't change the physical location of any element. It is also a // sufficient condition as is proved below (note: many details are omitted for // space). // // Definitions: // // * Denote the input shape by IS and output shape by OS. IS[i] or OS[i] means // the size of i-th least significant dimension of IS or OS (this is opposite // to how we define the index of Shape::dimensions()). // // * Given an input or output index I, denote by p(I) I's physical linear // index (or physical index for short) and l(I) I's logical linear index (or // logical index for short). // // * Given a logical index k, denote by II(k) the input index whose linear // index is k, and OI(k) the corresponding output index. // // * Denote by IT[i] the increment of physical index if i-th dimension of the // input index is increased by 1. Similarly, OT[i] means the increment if i-th // dimension of the output index is increased by 1. Note that IT[i] or OT[i] // is a function of IS or OS and the layout, and not dependent on the specific // input or output index. // // To prove the reshape from IS to OS is a bitcast, it is sufficient to prove // that, for any linear index k, p(II(k))=p(OI(k)). We prove this by // induction. We know p(II(0))=p(OI(0)) is trivially true, so what's left is // to prove, with every increment on k, the above formula still holds. // // First, suppose reshaping from IS to OS is non-factorizable (we discuss // refactorizable reshapes later). A reshape from IS to OS is factorizable, if // there exists (i,j) such that // // 0<=i<=|IS| // 0<=j<=|OS| // |IS|-i+|OS|-j > 0 (i.e., i,j mustn't both point to the end) // product(IS[i], IS[i+1], ..., IS[|IS|-1]) // = product(OS[j], OS[j+1], ..., OS[|OS|-1]) // // p(II(k))=p(OI(k)) is trivially true for k=0 because p(II(0)) and p(OI(0)) // are both 0. It's also trivially true for k=1, because II(1) and OI(1) are // unit indices which are already tested. This also means IT[0]=OT[0] // because p(II(1))=IT[0] and p(OI(1))=OT[0]. // // Furthermore, p(II(k))=p(OI(k)) for k<min(IS[0],OS[0]), because each // increment of k adds IT[0] to the input physical and OT[0] (same as IT[0]) // to the output physical. // // When k=min(IS[0],OS[0]), the first wrap happens. Without losing generality, // suppose IS[0]<OS[0] and thus k=IS[0]. Similar proof applies to IS[0]>OS[0]. // Note that IS[0]!=OS[0] because the reshape is non-factorizable. From // logical index k-1 to logical index k, dimension 1 of the input index // is increased by 1 and dimension 0 is reset to 0 thus decreased by // IS[0]-1. Therefore, the physical input index is increased by // // p(II(k)) - p(II(k-1)) = IT[1] - (IS[0]-1) * IT[0] // // Because IS[0]<OS[0], the only change to the output index is that its // dimension 0 is increased by one. Therefore, // // p(OI(k)) - p(OI(k-1)) = OT[0] = IT[0] // // Because II(k) is an unit index -- (0,..,0,1,0), we already tested that // p(II(k))=p(OI(k)). Therefore, // IT[1] - (IS[0]-1) * IT[0] = IT[0] // IT[1] = IS[0] * IT[0] // In other words, input dimension 1 is immediately more major than input // dimension 0. We can now conceptually collapse these two dimensions because // an increment in the logical index affecting only these two dimensions maps // to IT[0] in the physical index. // // By induction (omitted here), we can prove IT[i]=IS[i-1]*IT[i-1] and // OT[i]=OS[i-1]*OT[i-1]. Therefore, both IS and OS are row-major and bitwise // identical. // // A factorizable reshape can be factorized into a list of non-factorizable // sub-reshapes, each of which can be handled similarly to the proof above. // For example, // // [7x9x2x15] -> [63x6x5] // // can be factorized into // // [7x9] -> [63] and [2x15] -> [6x5]. // // Suppose input index I=(x3,x2,x1,x0) and output index O=(y2,y1,y0) have the // same logical linear index. According to the factorization, we know // l(x3,x2,0,0)=l(y2,0,0) and l(0,0,x1,x0)=l(0,y1,y0). Using the proof for // non-factorizable reshapes, we can prove p(0,0,x1,x0)=p(0,y1,y0). Using a // similar proof, with the increment of the logical index set to // IS[1]*IS[0]=OS[1]*OS[0]=30 instead of 1, we can prove // p(x3,x2,0,0)=p(y2,0,0) too. Therefore, // // p(x3,x2,x1,x0) = p(x3,x2,0,0) + p(0,0,x1,x0) // = p(y2,0,0) + p(0,0,y1,y0) // = p(y2,y1,y0) // // check_input_unit_indices checks one way of the condition: each input unit // index is mapped to an output index with the same physical location. This // lambda will be called again with input_shape and output_shape reversed to // check the other way. auto check_input_unit_indices = [](const Shape& input_shape, const Shape& output_shape) { // input_shape_dim0_major/output_shape_dim0_major has the same "dimensions" // as input_shape/output_shape and the dimension-0-major layout. These two // shapes are used for conversion between logical linear indices and // multi-dimensional indices. Shape input_shape_dim0_major = MakeShapeWithDescendingLayout( input_shape.element_type(), input_shape.dimensions()); Shape output_shape_dim0_major = MakeShapeWithDescendingLayout( output_shape.element_type(), output_shape.dimensions()); for (int64_t input_dim = 0; input_dim < input_shape.rank(); ++input_dim) { if (input_shape.dimensions(input_dim) <= 1) { continue; } std::vector<int64_t> input_unit_index(input_shape.rank(), 0); input_unit_index[input_dim] = 1; int64_t logical_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(input_shape_dim0_major, input_unit_index); // output_index has the same logical linear index as input_unit_index. std::vector<int64_t> output_index = IndexUtil::LinearIndexToMultidimensionalIndex(output_shape_dim0_major, logical_linear_index); // Check input_unit_index and output_index have the same physical linear // index. if (IndexUtil::MultidimensionalIndexToLinearIndex(input_shape, input_unit_index) != IndexUtil::MultidimensionalIndexToLinearIndex(output_shape, output_index)) { return false; } } return true; }; return check_input_unit_indices(input_shape, output_shape) && check_input_unit_indices(output_shape, input_shape); } /* static */ std::optional<Shape> ShapeUtil::AlignLayouts( const Shape& input_shape, const Shape& output_shape) { CHECK(input_shape.IsArray()); CHECK(output_shape.IsArray()); // Removing trivial dimensions from the shape simplifies the alignment // algorithm since ones can go in any position. if (HasDegenerateDimensions(input_shape) || HasDegenerateDimensions(output_shape)) { auto simple_output_shape = AlignLayouts(DropDegenerateDimensions(input_shape), DropDegenerateDimensions(output_shape)); if (!simple_output_shape) { return std::nullopt; } std::vector<int64_t> layout = SpanToVector(simple_output_shape->layout().minor_to_major()); // For each one sized dimension in the output, increment the dimension // numbers in layout that are more minor than the one. absl::InlinedVector<int64_t, 8> dim_map; dim_map.reserve(simple_output_shape->rank()); for (int64_t i = 0; i < output_shape.rank(); ++i) { if (output_shape.dimensions(i) != 1) { dim_map.push_back(i); } } for (int64_t& d : layout) { d = dim_map[d]; } // Add the ones in descending order to the layout. Descending layouts tend // to reduce the number of copies inserted in layout assignment. for (int64_t i = output_shape.rank() - 1; i >= 0; --i) { if (output_shape.dimensions(i) == 1) { layout.push_back(i); } } Shape output_shape_with_layout = output_shape; *output_shape_with_layout.mutable_layout() = Layout{layout}; return output_shape_with_layout; } auto common_factors = CommonFactors(input_shape.dimensions(), output_shape.dimensions()); const int64_t input_rank = input_shape.rank(); DimensionVector input_to_factor(input_rank); for (int64_t pos = 0; pos < common_factors.size() - 1; ++pos) { const int64_t input_start = common_factors[pos].first; const int64_t input_end = common_factors[pos + 1].first; int64_t input_physical = PositionInContainer(input_shape.layout().minor_to_major(), input_start); input_to_factor[input_start] = pos; for (int64_t i = input_start + 1; i < input_end; ++i) { --input_physical; if (input_physical < 0 || input_shape.layout().minor_to_major(input_physical) != i) { return std::nullopt; } input_to_factor[i] = pos; } } int64_t output_rank = output_shape.rank(); DimensionVector output_layout; output_layout.reserve(output_rank); int64_t input_minor = 0; while (output_layout.size() < output_rank) { const int64_t input_dim = input_shape.layout().minor_to_major(input_minor); const int64_t common_factor = input_to_factor[input_dim]; const auto start_factor = common_factors[common_factor]; const auto end_factor = common_factors[common_factor + 1]; for (int64_t dim = end_factor.second - 1; dim >= start_factor.second; --dim) { output_layout.push_back(dim); } input_minor += end_factor.first - start_factor.first; } Shape output_shape_with_layout = MakeShapeWithLayout( output_shape.element_type(), output_shape.dimensions(), output_layout); CHECK(ReshapeIsBitcast(input_shape, output_shape_with_layout)) << "reshape is not a bitcast for input_shape: " << ShapeUtil::HumanStringWithLayout(input_shape) << " and output_shape_with_layout: " << ShapeUtil::HumanStringWithLayout(output_shape_with_layout); return output_shape_with_layout; } /* static */ Shape ShapeUtil::DeleteDimension(int64_t dim_to_delete, Shape shape) { CHECK(shape.IsArray()); shape.DeleteDimension(dim_to_delete); return shape; } /* static */ bool ShapeUtil::DynamicArrayShapeIsCompatible( const xla::Shape& dynamic_shape, const xla::Shape& bounded_shape) { if (dynamic_shape.rank() != bounded_shape.rank()) { return false; } for (int64_t i = 0; i < dynamic_shape.rank(); ++i) { if (dynamic_shape.dimensions(i) > bounded_shape.dimensions(i)) { return false; } } return true; } /* static */ bool ShapeUtil::DynamicShapeIsCompatible( const xla::Shape& dynamic_shape, const xla::Shape& bounded_shape) { bool compatible = true; xla::ShapeUtil::ForEachSubshape(dynamic_shape, [&](const Shape& sub_shape, const ShapeIndex& index) { if (compatible) { auto subshape_result = TryGetSubshape(bounded_shape, index); if (subshape_result.ok()) { const Shape* bounded_sub_shape = std::move(subshape_result).value(); if (sub_shape.IsTuple()) { if (!bounded_sub_shape->IsTuple()) { compatible = false; } } else { if (bounded_sub_shape->IsTuple()) { compatible = false; } else if (!sub_shape.is_static() && !DynamicArrayShapeIsCompatible(sub_shape, *bounded_sub_shape)) { compatible = false; } } } else { compatible = false; } } }); return compatible; } /* static */ Shape ShapeUtil::DeleteDimensions( absl::Span<int64_t const> dims_to_delete, Shape shape) { std::vector<int64_t> dims_to_delete_v(dims_to_delete.begin(), dims_to_delete.end()); absl::c_sort(dims_to_delete_v, std::greater<int64_t>()); for (int64_t dim : dims_to_delete_v) { shape = DeleteDimension(dim, shape); } return shape; } /* static */ Shape ShapeUtil::FilterDimensions( const std::function<bool(int64_t)>& p, Shape shape) { CHECK(shape.IsArray()); std::vector<int64_t> dims_to_delete; for (int64_t i = shape.dimensions().size() - 1; i >= 0; --i) { if (!p(i)) { dims_to_delete.push_back(i); } } return DeleteDimensions(dims_to_delete, shape); } // Returns the indices of the first elements of all consecutive subarrays of the // given array. For example: // ConsecutiveSegments({m, m+1, m+2, n, k, k+1}) = {0, 3, 4} static std::vector<size_t> ConsecutiveSegments(absl::Span<const int64_t> xs) { std::vector<size_t> is = {0}; for (size_t i = 1; i < xs.size(); ++i) { if (1 != xs[i] - xs[i - 1]) { is.push_back(i); } } return is; } // Merges the sequences of dimensions of the given shape which start at the // given indices `segs`. static Shape MergeDimensions(absl::Span<const size_t> segs, const Shape& shape) { std::vector<int64_t> dimensions; const auto size = segs.size(); dimensions.reserve(size); for (size_t i = 1; i <= size; ++i) { dimensions.push_back(std::accumulate( shape.dimensions().begin() + segs[i - 1], shape.dimensions().begin() + (segs.size() == i ? shape.dimensions().size() : segs[i]), 1, std::multiplies<int64_t>())); } return ShapeUtil::MakeShapeWithDescendingLayout(shape.element_type(), dimensions); } /*static*/ std::optional<std::vector<int64_t>> ShapeUtil::FindTranspose021( const Shape& a, const Shape& b) { if (!CompatibleIgnoringElementType(a, b)) { return std::nullopt; } std::vector<int64_t> permutation(a.dimensions().size()); absl::Span<const int64_t> minor_to_major_a = LayoutUtil::MinorToMajor(a); std::vector<int64_t> major_to_minor_a(minor_to_major_a.rbegin(), minor_to_major_a.rend()); absl::Span<const int64_t> minor_to_major_b = LayoutUtil::MinorToMajor(b); std::vector<int64_t> major_to_minor_b(minor_to_major_b.rbegin(), minor_to_major_b.rend()); for (size_t i = 0; i < permutation.size(); ++i) { permutation[i] = PositionInContainer(major_to_minor_b, major_to_minor_a[i]); } std::vector<size_t> segments = ConsecutiveSegments(permutation); if ((3 == segments.size() && 0 == permutation[0]) || 2 == segments.size()) { Shape descending_layout_shape = ShapeUtil::MakeShapeWithDescendingLayoutAndSamePhysicalLayout(a); Shape normalized_shape = MergeDimensions(segments, descending_layout_shape); absl::Span<const int64_t> normalized_dims = normalized_shape.dimensions(); std::vector<int64_t> dims_021; if (2 == segments.size()) { // The logical component-0 is of size one. dims_021 = {1, normalized_dims[1], normalized_dims[0]}; } else { dims_021 = {normalized_dims[0], normalized_dims[2], normalized_dims[1]}; } return dims_021; } return std::nullopt; } Shape ShapeUtil::DeviceShapeToHostShape(Shape s) { ForEachMutableSubshape(&s, [](Shape* subshape, const ShapeIndex& index) { if (subshape->IsArray()) { subshape->mutable_layout()->clear_tiles(); subshape->mutable_layout()->set_memory_space(Layout::kDefaultMemorySpace); } }); return s; } /*static*/ bool ShapeUtil::ElementCanUpcast(const Shape& from, const Shape& to) { return HigherPrecisionElementType(from, to) == to.element_type(); } /*static*/ Status ShapeUtil::ByteStrides(const Shape& shape, absl::Span<int64_t> strides) { TF_RET_CHECK(shape.IsArray()); TF_RET_CHECK(shape.has_layout()); TF_RET_CHECK(shape.dimensions_size() == strides.size()); int64_t stride = ByteSizeOfPrimitiveType(shape.element_type()); for (int i : shape.layout().minor_to_major()) { strides.at(i) = stride; stride *= shape.dimensions(i); } return OkStatus(); } /*static*/ int64_t ShapeUtil::ArraySize(const Shape& shape) { CHECK(shape.IsArray()); CHECK(!shape.layout().tiles().empty()); auto tile_dimensions = shape.layout().tiles(0).dimensions(); auto shape_dimensions = shape.dimensions(); auto minor_to_major = shape.layout().minor_to_major(); int64_t shape_dim_size = shape_dimensions.size(); int64_t tile_dim_size = tile_dimensions.size(); // Use the top-level tile for shape size calculation. We assume the // sub-tiles won't cause additional padding. int64_t num_of_elements = 1; int64_t dim = 0; for (dim = 0; dim < tile_dim_size; dim++) { int64_t dim_size = dim < shape_dim_size ? shape_dimensions[minor_to_major[dim]] : 1; num_of_elements *= RoundUpTo(dim_size, tile_dimensions[tile_dim_size - dim - 1]); } for (; dim < shape_dim_size; dim++) { int64_t dim_size = shape_dimensions[minor_to_major[dim]]; num_of_elements *= dim_size; } if (shape.layout().element_size_in_bits() != 0) { const int64_t kBitsPerByte = 8; return CeilOfRatio(num_of_elements * shape.layout().element_size_in_bits(), static_cast<int64_t>(kBitsPerByte)); } return num_of_elements * ByteSizeOfPrimitiveType(shape.element_type()); } /*static*/ int64_t ShapeUtil::ArrayDataSize(const Shape& shape) { CHECK(shape.IsArray()); absl::InlinedVector<int64_t, 4> indices; for (int64_t dim : shape.dimensions()) { indices.push_back(dim - 1); } int64_t size = LayoutUtil::LinearIndex(shape, indices) + 1; if (shape.layout().element_size_in_bits() != 0) { const int64_t kBitsPerByte = 8; return CeilOfRatio(size * shape.layout().element_size_in_bits(), static_cast<int64_t>(kBitsPerByte)); } return (size * ShapeUtil::ByteSizeOfPrimitiveType(shape.element_type())); } } // namespace xla
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/FORMAT/VALIDATORS/MzDataValidator.h> #include <OpenMS/DATASTRUCTURES/CVMappingTerm.h> #include <OpenMS/DATASTRUCTURES/CVMappingRule.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> using namespace xercesc; using namespace std; namespace OpenMS::Internal { MzDataValidator::MzDataValidator(const CVMappings& mapping, const ControlledVocabulary& cv) : SemanticValidator(mapping, cv) { setCheckUnits(true); } MzDataValidator::~MzDataValidator() { } void MzDataValidator::handleTerm_(const String& path, const CVTerm& parsed_term) { //check if the term is allowed in this element //and if there is a mapping rule for this element //Also store fulfilled rule term counts - this count is used to check of the MUST/MAY and AND/OR/XOR is fulfilled bool allowed = false; bool rule_found = false; vector<CVMappingRule>& rules = rules_[path]; for (Size r = 0; r < rules.size(); ++r) //go thru all rules { rule_found = true; for (Size t = 0; t < rules[r].getCVTerms().size(); ++t) //go thru all terms { const CVMappingTerm& term = rules[r].getCVTerms()[t]; if (term.getUseTerm() && term.getAccession() == parsed_term.accession) //check if the term itself is allowed { allowed = true; ++fulfilled_[path][rules[r].getIdentifier()][term.getAccession()]; break; } if (term.getAllowChildren()) //check if the term's children are allowed { auto searcher = [&parsed_term] (const String& child) { return child == parsed_term.accession; }; if (cv_.iterateAllChildren(term.getAccession(), searcher)) { allowed = true; ++fulfilled_[path][rules[r].getIdentifier()][term.getAccession()]; break; } } } } // check units if (check_units_ && cv_.exists(parsed_term.accession)) { ControlledVocabulary::CVTerm term = cv_.getTerm(parsed_term.accession); // check if the cv term has units if (!term.units.empty()) { if (!parsed_term.has_unit_accession) { errors_.push_back(String("CV term must have a unit: " + parsed_term.accession + " - " + parsed_term.name)); } else { // check if the accession is ok if (cv_.exists(parsed_term.unit_accession)) { // check whether this unit is allowed within the cv term if (term.units.find(parsed_term.unit_accession) == term.units.end()) { // last chance, a child term of the units was used auto lambda = [&parsed_term] (const String& child) { return child == parsed_term.unit_accession; }; bool found_unit(false); for (set<String>::const_iterator it = term.units.begin(); it != term.units.end(); ++it) { if (cv_.iterateAllChildren(*it, lambda)) { found_unit = true; break; } } if (!found_unit) { errors_.push_back(String("Unit CV term not allowed: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name)); } } } else { errors_.push_back(String("Unit CV term not found: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name)); } } } else { // check whether unit was used if (parsed_term.has_unit_accession || parsed_term.has_unit_name) { warnings_.push_back(String("Unit CV term used, but not allowed: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name)); } } } if (!rule_found) //No rule found { warnings_.push_back(String("No mapping rule found for element '") + getPath_(1) + "'"); } else if (!allowed) //if rule found and not allowed { errors_.push_back(String("CV term used in invalid element: '") + parsed_term.accession + " - " + parsed_term.name + "' at element '" + getPath_(1) + "'"); } //check if term accession and term name match if (cv_.exists(parsed_term.accession)) { String parsed_name = parsed_term.name; parsed_name.trim(); String correct_name = cv_.getTerm(parsed_term.accession).name; correct_name.trim(); //be a bit more soft: ignore upper-lower case parsed_name.toLower(); correct_name.toLower(); //be a bit more soft: ignore spaces parsed_name.removeWhitespaces(); correct_name.removeWhitespaces(); if (parsed_name != correct_name) { errors_.push_back(String("Name of CV term not correct: '") + parsed_term.accession + " - " + parsed_name + "' should be '" + correct_name + "'"); } } } } // namespace OpenMS // namespace Internal
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "Grippables/GrippableStaticMeshComponent.h" #include "Net/UnrealNetwork.h" //============================================================================= UGrippableStaticMeshComponent::UGrippableStaticMeshComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { VRGripInterfaceSettings.bDenyGripping = false; VRGripInterfaceSettings.OnTeleportBehavior = EGripInterfaceTeleportBehavior::DropOnTeleport; VRGripInterfaceSettings.bSimulateOnDrop = true; VRGripInterfaceSettings.SlotDefaultGripType = EGripCollisionType::ManipulationGrip; VRGripInterfaceSettings.FreeDefaultGripType = EGripCollisionType::ManipulationGrip; VRGripInterfaceSettings.SecondaryGripType = ESecondaryGripType::SG_None; VRGripInterfaceSettings.MovementReplicationType = EGripMovementReplicationSettings::ForceClientSideMovement; VRGripInterfaceSettings.LateUpdateSetting = EGripLateUpdateSettings::LateUpdatesAlwaysOff; VRGripInterfaceSettings.ConstraintStiffness = 1500.0f; VRGripInterfaceSettings.ConstraintDamping = 200.0f; VRGripInterfaceSettings.ConstraintBreakDistance = 100.0f; VRGripInterfaceSettings.SecondarySlotRange = 20.0f; VRGripInterfaceSettings.PrimarySlotRange = 20.0f; VRGripInterfaceSettings.bIsHeld = false; bReplicateMovement = false; //this->bReplicates = true; bRepGripSettingsAndGameplayTags = true; } void UGrippableStaticMeshComponent::GetLifetimeReplicatedProps(TArray< class FLifetimeProperty > & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME/*_CONDITION*/(UGrippableStaticMeshComponent, GripLogicScripts);// , COND_Custom); DOREPLIFETIME(UGrippableStaticMeshComponent, bRepGripSettingsAndGameplayTags); DOREPLIFETIME(UGrippableStaticMeshComponent, bReplicateMovement); DOREPLIFETIME_CONDITION(UGrippableStaticMeshComponent, VRGripInterfaceSettings, COND_Custom); DOREPLIFETIME_CONDITION(UGrippableStaticMeshComponent, GameplayTags, COND_Custom); } void UGrippableStaticMeshComponent::PreReplication(IRepChangedPropertyTracker & ChangedPropertyTracker) { Super::PreReplication(ChangedPropertyTracker); // Don't replicate if set to not do it DOREPLIFETIME_ACTIVE_OVERRIDE(UGrippableStaticMeshComponent, VRGripInterfaceSettings, bRepGripSettingsAndGameplayTags); DOREPLIFETIME_ACTIVE_OVERRIDE(UGrippableStaticMeshComponent, GameplayTags, bRepGripSettingsAndGameplayTags); DOREPLIFETIME_ACTIVE_OVERRIDE_PRIVATE_PROPERTY(USceneComponent, RelativeLocation, bReplicateMovement); DOREPLIFETIME_ACTIVE_OVERRIDE_PRIVATE_PROPERTY(USceneComponent, RelativeRotation, bReplicateMovement); DOREPLIFETIME_ACTIVE_OVERRIDE_PRIVATE_PROPERTY(USceneComponent, RelativeScale3D, bReplicateMovement); } bool UGrippableStaticMeshComponent::ReplicateSubobjects(UActorChannel* Channel, class FOutBunch *Bunch, FReplicationFlags *RepFlags) { bool WroteSomething = Super::ReplicateSubobjects(Channel, Bunch, RepFlags); for (UVRGripScriptBase* Script : GripLogicScripts) { if (Script && !Script->IsPendingKill()) { WroteSomething |= Channel->ReplicateSubobject(Script, *Bunch, *RepFlags); } } return WroteSomething; } //============================================================================= UGrippableStaticMeshComponent::~UGrippableStaticMeshComponent() { } void UGrippableStaticMeshComponent::BeginPlay() { // Call the base class Super::BeginPlay(); // Call all grip scripts begin play events so they can perform any needed logic for (UVRGripScriptBase* Script : GripLogicScripts) { if (Script) { Script->BeginPlay(this); } } bOriginalReplicatesMovement = bReplicateMovement; } void UGrippableStaticMeshComponent::EndPlay(const EEndPlayReason::Type EndPlayReason) { // Call the base class Super::EndPlay(EndPlayReason); // Call all grip scripts begin play events so they can perform any needed logic for (UVRGripScriptBase* Script : GripLogicScripts) { if (Script) { Script->EndPlay(EndPlayReason); } } } void UGrippableStaticMeshComponent::SetDenyGripping(bool bDenyGripping) { VRGripInterfaceSettings.bDenyGripping = bDenyGripping; } void UGrippableStaticMeshComponent::SetGripPriority(int NewGripPriority) { VRGripInterfaceSettings.AdvancedGripSettings.GripPriority = NewGripPriority; } void UGrippableStaticMeshComponent::TickGrip_Implementation(UGripMotionControllerComponent * GrippingController, const FBPActorGripInformation & GripInformation, float DeltaTime) {} void UGrippableStaticMeshComponent::OnGrip_Implementation(UGripMotionControllerComponent* GrippingController, const FBPActorGripInformation& GripInformation) { } void UGrippableStaticMeshComponent::OnGripRelease_Implementation(UGripMotionControllerComponent* ReleasingController, const FBPActorGripInformation& GripInformation, bool bWasSocketed) { } void UGrippableStaticMeshComponent::OnChildGrip_Implementation(UGripMotionControllerComponent* GrippingController, const FBPActorGripInformation& GripInformation) {} void UGrippableStaticMeshComponent::OnChildGripRelease_Implementation(UGripMotionControllerComponent* ReleasingController, const FBPActorGripInformation& GripInformation, bool bWasSocketed) {} void UGrippableStaticMeshComponent::OnSecondaryGrip_Implementation(UGripMotionControllerComponent* GripOwningController, USceneComponent* SecondaryGripComponent, const FBPActorGripInformation& GripInformation) { OnSecondaryGripAdded.Broadcast(GripOwningController, GripInformation); } void UGrippableStaticMeshComponent::OnSecondaryGripRelease_Implementation(UGripMotionControllerComponent* GripOwningController, USceneComponent* ReleasingSecondaryGripComponent, const FBPActorGripInformation& GripInformation) { OnSecondaryGripRemoved.Broadcast(GripOwningController, GripInformation); } void UGrippableStaticMeshComponent::OnUsed_Implementation() {} void UGrippableStaticMeshComponent::OnEndUsed_Implementation() {} void UGrippableStaticMeshComponent::OnSecondaryUsed_Implementation() {} void UGrippableStaticMeshComponent::OnEndSecondaryUsed_Implementation() {} void UGrippableStaticMeshComponent::OnInput_Implementation(FKey Key, EInputEvent KeyEvent) {} bool UGrippableStaticMeshComponent::RequestsSocketing_Implementation(USceneComponent *& ParentToSocketTo, FName & OptionalSocketName, FTransform_NetQuantize & RelativeTransform) { return false; } bool UGrippableStaticMeshComponent::DenyGripping_Implementation(UGripMotionControllerComponent * GripInitiator) { return VRGripInterfaceSettings.bDenyGripping; } EGripInterfaceTeleportBehavior UGrippableStaticMeshComponent::TeleportBehavior_Implementation() { return VRGripInterfaceSettings.OnTeleportBehavior; } bool UGrippableStaticMeshComponent::SimulateOnDrop_Implementation() { return VRGripInterfaceSettings.bSimulateOnDrop; } EGripCollisionType UGrippableStaticMeshComponent::GetPrimaryGripType_Implementation(bool bIsSlot) { return bIsSlot ? VRGripInterfaceSettings.SlotDefaultGripType : VRGripInterfaceSettings.FreeDefaultGripType; } ESecondaryGripType UGrippableStaticMeshComponent::SecondaryGripType_Implementation() { return VRGripInterfaceSettings.SecondaryGripType; } EGripMovementReplicationSettings UGrippableStaticMeshComponent::GripMovementReplicationType_Implementation() { return VRGripInterfaceSettings.MovementReplicationType; } EGripLateUpdateSettings UGrippableStaticMeshComponent::GripLateUpdateSetting_Implementation() { return VRGripInterfaceSettings.LateUpdateSetting; } void UGrippableStaticMeshComponent::GetGripStiffnessAndDamping_Implementation(float &GripStiffnessOut, float &GripDampingOut) { GripStiffnessOut = VRGripInterfaceSettings.ConstraintStiffness; GripDampingOut = VRGripInterfaceSettings.ConstraintDamping; } FBPAdvGripSettings UGrippableStaticMeshComponent::AdvancedGripSettings_Implementation() { return VRGripInterfaceSettings.AdvancedGripSettings; } float UGrippableStaticMeshComponent::GripBreakDistance_Implementation() { return VRGripInterfaceSettings.ConstraintBreakDistance; } void UGrippableStaticMeshComponent::ClosestGripSlotInRange_Implementation(FVector WorldLocation, bool bSecondarySlot, bool & bHadSlotInRange, FTransform & SlotWorldTransform, FName & SlotName, UGripMotionControllerComponent * CallingController, FName OverridePrefix) { if (OverridePrefix.IsNone()) bSecondarySlot ? OverridePrefix = "VRGripS" : OverridePrefix = "VRGripP"; UVRExpansionFunctionLibrary::GetGripSlotInRangeByTypeName_Component(OverridePrefix, this, WorldLocation, bSecondarySlot ? VRGripInterfaceSettings.SecondarySlotRange : VRGripInterfaceSettings.PrimarySlotRange, bHadSlotInRange, SlotWorldTransform, SlotName, CallingController); } bool UGrippableStaticMeshComponent::AllowsMultipleGrips_Implementation() { return VRGripInterfaceSettings.bAllowMultipleGrips; } void UGrippableStaticMeshComponent::IsHeld_Implementation(TArray<FBPGripPair> & HoldingControllers, bool & bIsHeld) { HoldingControllers = VRGripInterfaceSettings.HoldingControllers; bIsHeld = VRGripInterfaceSettings.bIsHeld; } void UGrippableStaticMeshComponent::Native_NotifyThrowGripDelegates(UGripMotionControllerComponent* Controller, bool bGripped, const FBPActorGripInformation& GripInformation, bool bWasSocketed) { if (bGripped) { OnGripped.Broadcast(Controller, GripInformation); } else { OnDropped.Broadcast(Controller, GripInformation, bWasSocketed); } } void UGrippableStaticMeshComponent::SetHeld_Implementation(UGripMotionControllerComponent * HoldingController, uint8 GripID, bool bIsHeld) { if (bIsHeld) { if (VRGripInterfaceSettings.MovementReplicationType != EGripMovementReplicationSettings::ForceServerSideMovement) { if (!VRGripInterfaceSettings.bIsHeld) bOriginalReplicatesMovement = bReplicateMovement; bReplicateMovement = false; } VRGripInterfaceSettings.bWasHeld = true; VRGripInterfaceSettings.HoldingControllers.AddUnique(FBPGripPair(HoldingController, GripID)); } else { if (VRGripInterfaceSettings.MovementReplicationType != EGripMovementReplicationSettings::ForceServerSideMovement) { bReplicateMovement = bOriginalReplicatesMovement; } VRGripInterfaceSettings.HoldingControllers.Remove(FBPGripPair(HoldingController, GripID)); } VRGripInterfaceSettings.bIsHeld = VRGripInterfaceSettings.HoldingControllers.Num() > 0; } bool UGrippableStaticMeshComponent::GetGripScripts_Implementation(TArray<UVRGripScriptBase*> & ArrayReference) { ArrayReference = GripLogicScripts; return GripLogicScripts.Num() > 0; } void UGrippableStaticMeshComponent::PreDestroyFromReplication() { Super::PreDestroyFromReplication(); // Destroy any sub-objects we created for (int32 i = 0; i < GripLogicScripts.Num(); ++i) { if (UObject *SubObject = GripLogicScripts[i]) { SubObject->PreDestroyFromReplication(); SubObject->MarkPendingKill(); } } GripLogicScripts.Empty(); } void UGrippableStaticMeshComponent::GetSubobjectsWithStableNamesForNetworking(TArray<UObject*> &ObjList) { for (int32 i = 0; i < GripLogicScripts.Num(); ++i) { if (UObject *SubObject = GripLogicScripts[i]) { ObjList.Add(SubObject); } } } void UGrippableStaticMeshComponent::OnComponentDestroyed(bool bDestroyingHierarchy) { // Call the super at the end, after we've done what we needed to do Super::OnComponentDestroyed(bDestroyingHierarchy); // Don't set these in editor preview window and the like, it causes saving issues if (UWorld * World = GetWorld()) { EWorldType::Type WorldType = World->WorldType; if (WorldType == EWorldType::Editor || WorldType == EWorldType::EditorPreview) { return; } } for (int32 i = 0; i < GripLogicScripts.Num(); i++) { if (UObject *SubObject = GripLogicScripts[i]) { SubObject->MarkPendingKill(); } } GripLogicScripts.Empty(); }
//============================================================================= /** * @file Talker.cpp * * $Id$ * * * This test application tests a wide range of events that can be * demultiplexed using various ACE utilities. Events used include * ^C events, reading from STDIN, vanilla Win32 events, thread * exits, Reactor notifications, proactive reads, and proactive * writes. * * The proactive I/O events are demultiplexed by the ACE_Proactor. * The thread exits, notications, and vanilla Win32 events are * demultiplexed by the ACE_Reactor. To enable a single thread * to run all these events, the Proactor is integrated with the * Reactor. * * The test application prototypes a simple talk program. Two * instances of the application connect. Input from either console * is displayed on the others console also. Because of the evils * of Win32 STDIN, a separate thread is used to read from STDIN. * To test the Proactor and Reactor, I/O between the remote * processes is performed proactively and interactions between the * STDIN thread and the main thread are performed reactively. * * The following description of the test application is in two * parts. The participants section explains the main components * involved in the application. The collaboration section * describes how the partipants interact in response to the * multiple event types which occur. * * The Reactor test application has the following participants: * * . Reactor -- The Reactor demultiplexes Win32 "waitable" * events using WaitForMultipleObjects. * * . Proactor -- The proactor initiates and demultiplexes * overlapped I/O operations. The Proactor registers with the * Reactor so that a single-thread can demultiplex all * application events. * * . STDIN_Handler -- STDIN_Handler is an Active Object which reads * from STDIN and forwards the input to the Peer_Handler. This * runs in a separate thread to make the test more interesting. * However, STDIN is "waitable", so in general it can be waited on * by the ACE Reactor, thanks MicroSlush! * * . Peer_Handler -- The Peer_Handler connects to another instance * of test_reactor. It Proactively reads and writes data to the * peer. When the STDIN_Handler gives it messages, it fowards them * to the remote peer. When it receives messages from the remote * peer, it prints the output to the console. * * The collaborations of the participants are as follows: * * . Initialization * * Peer_Handler -- connects to the remote peer. It then begins * proactively reading from the remote connection. Note that it * will be notified by the Proactor when a read completes. It * also registers a notification strategy with message queue so * that it is notified when the STDIN_Handler posts a message * onto the queue. * * STDIN_Handler -- STDIN_Handler registers a signal handler for * SIGINT. This just captures the exception so that the kernel * doesn't kill our process; We want to exit gracefully. It also * creates an Exit_Hook object which registers the * STDIN_Handler's thread handle with the Reactor. The * Exit_Hook will get called back when the STDIN_Handler thread * exits. After registering these, it blocks reading from STDIN. * * Proactor -- is registered with the Reactor. * * The main thread of control waits in the Reactor. * * . STDIN events -- When the STDIN_Handler thread reads from * STDIN, it puts the message on Peer_Handler's message queue. It * then returns to reading from STDIN. * * . Message enqueue -- The Reactor thread wakes up and calls * Peer_Handler::handle_output. The Peer_Handler then tries to * dequeue a message from its message queue. If it can, the * message is Proactively sent to the remote peer. Note that the * Peer_Handler will be notified with this operation is complete. * The Peer_Handler then falls back into the Reactor event loop. * * . Send complete event -- When a proactive send is complete, the * Proactor is notified by the Reactor. The Proactor, in turn, * notifies the Peer_Handler. The Peer_Handler then checks for * more messages from the message queue. If there are any, it * tries to send them. If there are not, it returns to the * Reactor event loop. * * . Read complete event -- When a proactive read is complete (the * Peer_Handler initiated a proactive read when it connected to the * remote peer), the Proactor is notified by the Reactor. The * Proactor, in turn notifies the Peer_Handler. If the read was * successful the Peer_Handler just displays the received msg to * the console and reinvokes a proactive read from the network * connection. If the read failed (i.e. the remote peer exited), * the Peer_Handler sets a flag to end the event loop and returns. * This will cause the application to exit. * * . ^C events -- When the user types ^C at the console, the * STDIN_Handler's signal handler will be called. It does nothing, * but as a result of the signal, the STDIN_Handler thread will * exit. * * . STDIN_Handler thread exits -- The Exit_Hook will get called * back from the Reactor. Exit_Hook::handle_signal sets a flag * to end the event loop and returns. This will cause the * application to exit. * * * To run example, start an instance of the test with an optional * local port argument (as the acceptor). Start the other instance * with -h <hostname> and -p <server port>. Type in either the * client or server windows and your message should show up in the * other window. Control C to exit. * * * @author Tim Harrison Irfan Pyarali */ //============================================================================= #include "ace/OS_main.h" #if defined (ACE_HAS_WIN32_OVERLAPPED_IO) #include "ace/Reactor.h" #include "ace/Reactor_Notification_Strategy.h" #include "ace/WIN32_Proactor.h" #include "ace/Proactor.h" #include "ace/SOCK_Connector.h" #include "ace/SOCK_Acceptor.h" #include "ace/Get_Opt.h" #include "ace/Service_Config.h" #include "ace/Task.h" #include "ace/OS_NS_unistd.h" typedef ACE_Task<ACE_MT_SYNCH> MT_TASK; /** * @class Peer_Handler * * @brief Connect to a server. Receive messages from STDIN_Handler * and forward them to the server using proactive I/O. */ class Peer_Handler : public MT_TASK, public ACE_Handler { public: // = Initialization methods. Peer_Handler (int argc, ACE_TCHAR *argv[]); ~Peer_Handler (void); //FUZZ: disable check_for_lack_ACE_OS /** * This method creates the network connection to the remote peer. * It does blocking connects and accepts depending on whether a * hostname was specified from the command line. *FUZZ: enable check_for_lack_ACE_OS */ int open (void * =0); /** * This method will be called when an asynchronous read completes on a stream. * The remote peer has sent us something. If it succeeded, print * out the message and reinitiate a read. Otherwise, fail. In both * cases, delete the message sent. */ virtual void handle_read_stream (const ACE_Asynch_Read_Stream::Result &result); /** * This method will be called when an asynchronous write completes on a strea_m. * One of our asynchronous writes to the remote peer has completed. * Make sure it succeeded and then delete the message. */ virtual void handle_write_stream (const ACE_Asynch_Write_Stream::Result &result); /** * Get the I/O handle used by this <handler>. This method will be * called by the ACE_Asynch_* classes when an ACE_INVALID_HANDLE is * passed to <open>. */ virtual ACE_HANDLE handle (void) const; /// Set the ACE_HANDLE value for this Handler. void handle (ACE_HANDLE); /// We've been removed from the Reactor. virtual int handle_close (ACE_HANDLE, ACE_Reactor_Mask); /** * Called when output events should start. Note that this is * automatically invoked by the * <ACE_Reactor_Notificiation_Strategy>. */ virtual int handle_output (ACE_HANDLE fd); private: /// Socket that we have connected to the server. ACE_SOCK_Stream stream_; /// The strategy object that the reactor uses to notify us when /// something is added to the queue. ACE_Reactor_Notification_Strategy strategy_; // = Remote peer info. /// Name of remote host. ACE_TCHAR *host_; /// Port number for remote host. u_short port_; /// Read stream ACE_Asynch_Read_Stream rd_stream_; /// Write stream ACE_Asynch_Write_Stream wr_stream_; /// Message Block for reading from the network ACE_Message_Block mb_; }; /** * @class STDIN_Handler * * @brief Active Object. Reads from STDIN and passes message blocks to * the peer handler. */ class STDIN_Handler : public ACE_Task<ACE_NULL_SYNCH> { public: /// Initialization. STDIN_Handler (MT_TASK &ph); //FUZZ: disable check_for_lack_ACE_OS /// Activate object. virtual int open (void * = 0); /// Shut down. ///FUZZ: enable check_for_lack_ACE_OS virtual int close (u_long = 0); /// Thread runs here as an active object. int svc (void); int handle_close (ACE_HANDLE, ACE_Reactor_Mask); private: /// Handle a ^C. (Do nothing, this just illustrates how we can catch /// signals along with the other things). static void handler (int signum); /// Helper function to register with the Reactor for thread exit. void register_thread_exit_hook (void); /// The STDIN thread has exited. This means the user hit ^C. We can /// end the event loop. virtual int handle_signal (int index, siginfo_t *, ucontext_t *); /// Send all input to ph_. MT_TASK &ph_; /// Handle of our thread. ACE_HANDLE thr_handle_; }; Peer_Handler::Peer_Handler (int argc, ACE_TCHAR *argv[]) : strategy_ (ACE_Reactor::instance (), this, ACE_Event_Handler::WRITE_MASK), host_ (0), port_ (ACE_DEFAULT_SERVER_PORT), mb_ (BUFSIZ) { // This code sets up the message to notify us when a new message is // added to the queue. Actually, the queue notifies Reactor which // then notifies us. this->msg_queue ()->notification_strategy (&this->strategy_); ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("h:p:")); int c; while ((c = get_opt ()) != EOF) { switch (c) { case 'h': host_ = get_opt.opt_arg (); break; case 'p': port_ = ACE_OS::atoi (get_opt.opt_arg ()); break; } } } Peer_Handler::~Peer_Handler (void) { } // This method creates the network connection to the remote peer. It // does blocking connects and accepts depending on whether a hostname // was specified from the command line. int Peer_Handler::open (void *) { if (host_ != 0) // Connector { ACE_INET_Addr addr (port_, host_); ACE_SOCK_Connector connector; // Establish connection with server. if (connector.connect (stream_, addr) == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "connect"), -1); ACE_DEBUG ((LM_DEBUG, "(%t) connected.\n")); } else // Acceptor { ACE_SOCK_Acceptor acceptor; ACE_INET_Addr local_addr (port_); if ((acceptor.open (local_addr) == -1) || (acceptor.accept (this->stream_) == -1)) ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "accept failed"), -1); ACE_DEBUG ((LM_DEBUG, "(%t) accepted.\n")); } int result = this->rd_stream_.open (*this); if (result != 0) return result; result = this->wr_stream_.open (*this); if (result != 0) return result; result = this->rd_stream_.read (this->mb_, this->mb_.size ()); return result; } // One of our asynchronous writes to the remote peer has completed. // Make sure it succeeded and then delete the message. void Peer_Handler::handle_write_stream (const ACE_Asynch_Write_Stream::Result &result) { if (result.bytes_transferred () <= 0) ACE_DEBUG ((LM_DEBUG, "(%t) %p bytes = %d\n", "Message failed", result.bytes_transferred ())); // This was allocated by the STDIN_Handler, queued, dequeued, passed // to the proactor, and now passed back to us. result.message_block ().release (); } // The remote peer has sent us something. If it succeeded, print // out the message and reinitiate a read. Otherwise, fail. In both // cases, delete the message sent. void Peer_Handler::handle_read_stream (const ACE_Asynch_Read_Stream::Result &result) { if (result.bytes_transferred () > 0 && this->mb_.length () > 0) { this->mb_.rd_ptr ()[result.bytes_transferred ()] = '\0'; // Print out the message received from the server. ACE_DEBUG ((LM_DEBUG, "%s", this->mb_.rd_ptr ())); } else { // If a read failed, we will assume it's because the remote peer // went away. We will end the event loop. Since we're in the // main thread, we don't need to do a notify. ACE_Reactor::end_event_loop(); return; } // Reset pointers this->mb_.wr_ptr (this->mb_.wr_ptr () - result.bytes_transferred ()); // Start off another read if (this->rd_stream_.read (this->mb_, this->mb_.size ()) == -1) ACE_ERROR ((LM_ERROR, "%p Read initiate.\n", "Peer_Handler")); } // This is so the Proactor can get our handle. ACE_HANDLE Peer_Handler::handle (void) const { return this->stream_.get_handle (); } void Peer_Handler::handle (ACE_HANDLE handle) { this->stream_.set_handle (handle); } // We've been removed from the Reactor. int Peer_Handler::handle_close (ACE_HANDLE, ACE_Reactor_Mask) { ACE_DEBUG ((LM_DEBUG, "(%t) Peer_Handler closing down\n")); return 0; } // New stuff added to the message queue. Try to dequeue a message. int Peer_Handler::handle_output (ACE_HANDLE) { ACE_Message_Block *mb = 0; ACE_Time_Value tv (ACE_Time_Value::zero); // Forward the message to the remote peer receiver. if (this->getq (mb, &tv) != -1) { if (this->wr_stream_.write (*mb, mb->length ()) == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p Write initiate.\n", "Peer_Handler"), -1); } return 0; } void STDIN_Handler::handler (int signum) { ACE_DEBUG ((LM_DEBUG, "(%t) signal = %S\n", signum)); } STDIN_Handler::STDIN_Handler (MT_TASK &ph) : ph_ (ph) { // Register for ^C from the console. We just need to catch the // exception so that the kernel doesn't kill our process. // Registering this signal handler just tells the kernel that we // know what we're doing; to leave us alone. ACE_OS::signal (SIGINT, (ACE_SignalHandler) STDIN_Handler::handler); }; // Activate object. int STDIN_Handler::open (void *) { if (this->activate (THR_NEW_LWP | THR_DETACHED) == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "spawn"), -1); return 0; } // Shut down. int STDIN_Handler::close (u_long) { ACE_DEBUG ((LM_DEBUG, "(%t) thread is exiting.\n")); return 0; } // Thread runs here. int STDIN_Handler::svc (void) { this->register_thread_exit_hook (); for (;;) { ACE_Message_Block *mb = new ACE_Message_Block (BUFSIZ); // Read from stdin into mb. int read_result = ACE_OS::read (ACE_STDIN, mb->rd_ptr (), mb->size ()); // If read succeeds, put mb to peer handler, else end the loop. if (read_result > 0) { mb->wr_ptr (read_result); // Note that this call will first enqueue mb onto the peer // handler's message queue, which will then turn around and // notify the Reactor via the Notification_Strategy. This // will subsequently signal the Peer_Handler, which will // react by calling back to its handle_output() method, // which dequeues the message and sends it to the peer // across the network. this->ph_.putq (mb); } else { mb->release (); break; } } // handle_signal will get called on the main proactor thread since // we just exited and the main thread is waiting on our thread exit. return 0; } // Register an exit hook with the reactor. void STDIN_Handler::register_thread_exit_hook (void) { // Get a real handle to our thread. ACE_Thread_Manager::instance ()->thr_self (this->thr_handle_); // Register ourselves to get called back when our thread exits. if (ACE_Reactor::instance ()-> register_handler (this, this->thr_handle_) == -1) ACE_ERROR ((LM_ERROR, "Exit_Hook Register failed.\n")); } // The STDIN thread has exited. This means the user hit ^C. We can // end the event loop and delete ourself. int STDIN_Handler::handle_signal (int, siginfo_t *si, ucontext_t *) { if (si != 0) { ACE_TEST_ASSERT (this->thr_handle_ == si->si_handle_); ACE_Reactor::end_event_loop (); } return 0; } int STDIN_Handler::handle_close (ACE_HANDLE, ACE_Reactor_Mask) { delete this; return 0; } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { // Let the proactor know that it will be used with Reactor // Create specific proactor ACE_WIN32_Proactor win32_proactor (0, 1); // Get the interface proactor ACE_Proactor proactor (&win32_proactor); // Put it as the instance. ACE_Proactor::instance (&proactor); // Open handler for remote peer communications this will run from // the main thread. Peer_Handler peer_handler (argc, argv); if (peer_handler.open () == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p open failed, errno = %d.\n", "peer_handler", errno), 0); // Open active object for reading from stdin. STDIN_Handler *stdin_handler = new STDIN_Handler (peer_handler); // Spawn thread. if (stdin_handler->open () == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p open failed, errno = %d.\n", "stdin_handler", errno), 0); // Register proactor with Reactor so that we can demultiplex // "waitable" events and I/O operations from a single thread. if (ACE_Reactor::instance ()->register_handler (ACE_Proactor::instance ()->implementation ()) != 0) ACE_ERROR_RETURN ((LM_ERROR, "%p failed to register Proactor.\n", argv[0]), -1); // Run main event demultiplexor. ACE_Reactor::run_event_loop (); // Remove proactor with Reactor. if (ACE_Reactor::instance ()->remove_handler (ACE_Proactor::instance ()->implementation (), ACE_Event_Handler::DONT_CALL) != 0) ACE_ERROR_RETURN ((LM_ERROR, "%p failed to register Proactor.\n", argv[0]), -1); return 0; } #else /* !ACE_HAS_WIN32_OVERLAPPED_IO */ int ACE_TMAIN (int , ACE_TCHAR *[]) { return 0; } #endif /* ACE_HAS_WIN32_OVERLAPPED_IO */
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Atom/RHI/BufferFrameAttachment.h> #include <Atom/RHI/BufferPoolBase.h> #include <Atom/RHI/BufferScopeAttachment.h> #include <Atom/RHI/CpuProfiler.h> #include <Atom/RHI/FrameGraph.h> #include <Atom/RHI/ImageFrameAttachment.h> #include <Atom/RHI/ImagePoolBase.h> #include <Atom/RHI/ImageScopeAttachment.h> #include <Atom/RHI/QueryPool.h> #include <Atom/RHI/ResolveScopeAttachment.h> #include <Atom/RHI/Scope.h> #include <Atom/RHI/SwapChain.h> #include <Atom/RHI/SwapChainFrameAttachment.h> #include <AzCore/Debug/EventTrace.h> #include <AzCore/std/sort.h> namespace AZ { namespace RHI { FrameGraph::~FrameGraph() { Clear(); } bool FrameGraph::IsCompiled() const { return m_isCompiled; } void FrameGraph::SetCompiled() { m_isCompiled = true; } bool FrameGraph::IsBuilding() const { return m_isBuilding; } size_t FrameGraph::GetFrameCount() const { return m_frameCount; } const FrameGraphAttachmentDatabase& FrameGraph::GetAttachmentDatabase() const { return m_attachmentDatabase; } FrameGraphAttachmentDatabase& FrameGraph::GetAttachmentDatabase() { return m_attachmentDatabase; } void FrameGraph::Begin() { AZ_TRACE_METHOD(); AZ_Assert(m_isBuilding == false, "FrameGraph::Begin called, but End was never called on the previous build cycle!"); AZ_Assert(m_isCompiled == false, "FrameGraph::Clear must be called before reuse."); Clear(); m_isBuilding = true; m_frameCount++; } void FrameGraph::Clear() { AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraph: Clear"); for (Scope* scope : m_scopes) { scope->Deactivate(); } m_scopes.clear(); m_graphNodes.clear(); m_graphEdges.clear(); m_scopeLookup.clear(); m_attachmentDatabase.Clear(); m_isCompiled = false; } ResultCode FrameGraph::ValidateEnd() { if (Validation::IsEnabled()) { if (m_isBuilding == false) { AZ_Error("FrameGraph", false, "FrameGraph::End called, but Begin was never called"); Clear(); return ResultCode::InvalidOperation; } if (m_currentScope) { AZ_Error("FrameGraph", false, "We are still building a scope %s!", m_currentScope->GetId().GetCStr()); Clear(); return ResultCode::InvalidOperation; } /// Validate that every attachment was used. for (FrameAttachment* attachment : m_attachmentDatabase.GetAttachments()) { if (attachment->GetFirstScopeAttachment() == nullptr) { AZ_Error( "FrameGraph", false, "Invalid State: attachment '%s' was added but never used!", attachment->GetId().GetCStr()); Clear(); return ResultCode::InvalidOperation; } } } return ResultCode::Success; } ResultCode FrameGraph::End() { AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameGraph: End"); ResultCode resultCode = ValidateEnd(); if (resultCode != ResultCode::Success) { return resultCode; } /** * Swap chains are processed at the end of the last scope they are used on. This requires * waiting until all scopes have been added in order to have access to the full lifetime. */ for (SwapChainFrameAttachment* attachment : m_attachmentDatabase.GetSwapChainAttachments()) { if (auto* lastScope = attachment->GetLastScope()) { lastScope->m_swapChainsToPresent.push_back(attachment->GetSwapChain()); } } m_isBuilding = false; /// Finally, topologically sort the graph in preparation for compilation. resultCode = TopologicalSort(); if (resultCode != ResultCode::Success) { Clear(); } return resultCode; } void FrameGraph::BeginScope(Scope& scope) { AZ_Assert( m_currentScope == nullptr, "Cannot begin scope: %s, because scope %s is still recording! Only one scope can be recorded at a time.", scope.GetId().GetCStr(), m_currentScope->GetId().GetCStr()); m_currentScope = &scope; m_scopeLookup.emplace(scope.GetId(), &scope); scope.m_graphNodeIndex = decltype(scope.m_graphNodeIndex)(m_graphNodes.size()); m_graphNodes.emplace_back(scope); } void FrameGraph::EndScope() { m_currentScope = nullptr; } void FrameGraph::SetEstimatedItemCount(uint32_t itemCount) { m_currentScope->m_estimatedItemCount = itemCount; } void FrameGraph::SetHardwareQueueClass(HardwareQueueClass hardwareQueueClass) { m_currentScope->m_hardwareQueueClass = hardwareQueueClass; } void FrameGraph::UseAttachmentInternal( ImageFrameAttachment& frameAttachment, ScopeAttachmentUsage usage, ScopeAttachmentAccess access, const ImageScopeAttachmentDescriptor& descriptor) { AZ_Assert(usage != ScopeAttachmentUsage::Uninitialized, "ScopeAttachmentUsage is Uninitialized"); //A scopeattachment can be used in multiple ways within the same scope. Hence, instead of adding duplicate scopeattachments //for a scope we add multiple usage/access related data within the same scopeattahcment. for (ImageScopeAttachment* imageScopeInnerAttachment : m_currentScope->m_imageAttachments) { if(imageScopeInnerAttachment->GetFrameAttachment().GetId() == frameAttachment.GetId()) { //Check if it is the same sub resource as for an imagescopeattachments we may want to read and write into different mips //and in that case we would want multiple scopeattachments. if(imageScopeInnerAttachment->GetDescriptor().m_imageViewDescriptor.IsSameSubResource(descriptor.m_imageViewDescriptor)) { AZ_Assert(imageScopeInnerAttachment->GetDescriptor().m_loadStoreAction == descriptor.m_loadStoreAction, "LoadStore actions for multiple usages need to match"); imageScopeInnerAttachment->AddUsageAndAccess(usage, access); return; } } } // TODO:[ATOM-1267] Replace with writer / reader dependencies. GraphEdgeType edgeType = usage == ScopeAttachmentUsage::SubpassInput ? GraphEdgeType::SameGroup : GraphEdgeType::DifferentGroup; if (Scope* producer = frameAttachment.GetLastScope()) { InsertEdge(*producer, *m_currentScope, edgeType); } ImageScopeAttachment* scopeAttachment = m_attachmentDatabase.EmplaceScopeAttachment<ImageScopeAttachment>( *m_currentScope, frameAttachment, usage, access, descriptor); m_currentScope->m_attachments.push_back(scopeAttachment); m_currentScope->m_imageAttachments.push_back(scopeAttachment); if (frameAttachment.GetLifetimeType() == AttachmentLifetimeType::Transient) { m_currentScope->m_transientAttachments.push_back(scopeAttachment); } } void FrameGraph::UseAttachmentInternal( ImageFrameAttachment& frameAttachment, const ResolveScopeAttachmentDescriptor& descriptor) { #if defined(AZ_ENABLE_TRACING) if (Validation::IsEnabled()) { auto found = AZStd::find_if(m_currentScope->m_imageAttachments.begin(), m_currentScope->m_imageAttachments.end(), [&descriptor](const auto& scopeAttachment) { return scopeAttachment->GetFrameAttachment().GetId() == descriptor.m_resolveAttachmentId; }); AZ_Assert( found != m_currentScope->m_imageAttachments.end(), "Could not find resolve attachment id '%s' when adding a ResolveScopeAttachment '%s'", descriptor.m_resolveAttachmentId.GetCStr(), descriptor.m_attachmentId.GetCStr()); } #endif // TODO:[ATOM-1267] Replace with writer / reader dependencies. if (Scope* producer = frameAttachment.GetLastScope()) { InsertEdge(*producer, *m_currentScope); } ResolveScopeAttachment* scopeAttachment = m_attachmentDatabase.EmplaceScopeAttachment<ResolveScopeAttachment>( *m_currentScope, frameAttachment, descriptor); m_currentScope->m_attachments.push_back(scopeAttachment); m_currentScope->m_imageAttachments.push_back(scopeAttachment); m_currentScope->m_resolveAttachments.push_back(scopeAttachment); if (frameAttachment.GetLifetimeType() == AttachmentLifetimeType::Transient) { m_currentScope->m_transientAttachments.push_back(scopeAttachment); } } void FrameGraph::UseAttachmentInternal( BufferFrameAttachment& frameAttachment, ScopeAttachmentUsage usage, ScopeAttachmentAccess access, const BufferScopeAttachmentDescriptor& descriptor) { AZ_Assert(usage != ScopeAttachmentUsage::Uninitialized, "ScopeAttachmentUsage is Uninitialized"); //A scopeattachment can be used in multiple ways within the same scope. Hence, instead of adding duplicate scopeattachments //for a scope we add multiple usage/access related data within the same scopeattahcment. for (BufferScopeAttachment* scopeInnerAttachment : m_currentScope->m_bufferAttachments) { if (scopeInnerAttachment->GetFrameAttachment().GetId() == frameAttachment.GetId()) { scopeInnerAttachment->AddUsageAndAccess(usage, access); return; } } // TODO:[ATOM-1267] Replace with writer / reader dependencies. if (Scope* producer = frameAttachment.GetLastScope()) { InsertEdge(*producer, *m_currentScope); } BufferScopeAttachment* scopeAttachment = m_attachmentDatabase.EmplaceScopeAttachment<BufferScopeAttachment>( *m_currentScope, frameAttachment, usage, access, descriptor); m_currentScope->m_attachments.push_back(scopeAttachment); m_currentScope->m_bufferAttachments.push_back(scopeAttachment); if (frameAttachment.GetLifetimeType() == AttachmentLifetimeType::Transient) { m_currentScope->m_transientAttachments.push_back(scopeAttachment); } } ResultCode FrameGraph::UseAttachment(const BufferScopeAttachmentDescriptor& descriptor, ScopeAttachmentAccess access, ScopeAttachmentUsage usage) { BufferFrameAttachment* attachment = m_attachmentDatabase.FindAttachment<BufferFrameAttachment>(descriptor.m_attachmentId); if (attachment) { UseAttachmentInternal(*attachment, usage, access, descriptor); return ResultCode::Success; } AZ_Error("FrameGraph", false, "No compatible buffer attachment found for id: '%s'", descriptor.m_attachmentId.GetCStr()); return ResultCode::InvalidArgument; } ResultCode FrameGraph::UseAttachment(const ImageScopeAttachmentDescriptor& descriptor, ScopeAttachmentAccess access, ScopeAttachmentUsage usage) { ImageFrameAttachment* attachment = m_attachmentDatabase.FindAttachment<ImageFrameAttachment>(descriptor.m_attachmentId); if (attachment) { UseAttachmentInternal(*attachment, usage, access, descriptor); return ResultCode::Success; } AZ_Error("FrameGraph", false, "No compatible image attachment found for id: '%s'", descriptor.m_attachmentId.GetCStr()); return ResultCode::InvalidArgument; } ResultCode FrameGraph::UseAttachments(AZStd::array_view<ImageScopeAttachmentDescriptor> descriptors, ScopeAttachmentAccess access, ScopeAttachmentUsage usage) { for (const ImageScopeAttachmentDescriptor& descriptor : descriptors) { ResultCode resultCode = UseAttachment(descriptor, access, usage); if (resultCode != ResultCode::Success) { AZ_Error("FrameGraph", false, "Error loading image scope attachment array. Attachment that errored is '%s'", descriptor.m_attachmentId.GetCStr()); return resultCode; } } return ResultCode::Success; } ResultCode FrameGraph::UseResolveAttachment(const ResolveScopeAttachmentDescriptor& descriptor) { ImageFrameAttachment* attachment = m_attachmentDatabase.FindAttachment<ImageFrameAttachment>(descriptor.m_attachmentId); if (attachment) { UseAttachmentInternal(*attachment, descriptor); return ResultCode::Success; } AZ_Error("FrameGraph", false, "No compatible image attachment found for id: '%s'", descriptor.m_attachmentId.GetCStr()); return ResultCode::InvalidArgument; } ResultCode FrameGraph::UseColorAttachments(AZStd::array_view<ImageScopeAttachmentDescriptor> descriptors) { return UseAttachments(descriptors, ScopeAttachmentAccess::Write, ScopeAttachmentUsage::RenderTarget); } ResultCode FrameGraph::UseDepthStencilAttachment(const ImageScopeAttachmentDescriptor& descriptor, ScopeAttachmentAccess access) { return UseAttachment(descriptor, access, ScopeAttachmentUsage::DepthStencil); } ResultCode FrameGraph::UseSubpassInputAttachments(AZStd::array_view<ImageScopeAttachmentDescriptor> descriptors) { return UseAttachments(descriptors, ScopeAttachmentAccess::Read, ScopeAttachmentUsage::SubpassInput); } ResultCode FrameGraph::UseShaderAttachment(const BufferScopeAttachmentDescriptor& descriptor, ScopeAttachmentAccess access) { return UseAttachment(descriptor, access, ScopeAttachmentUsage::Shader); } ResultCode FrameGraph::UseShaderAttachment(const ImageScopeAttachmentDescriptor& descriptor, ScopeAttachmentAccess access) { return UseAttachment(descriptor, access, ScopeAttachmentUsage::Shader); } ResultCode FrameGraph::UseCopyAttachment(const BufferScopeAttachmentDescriptor& descriptor, ScopeAttachmentAccess access) { return UseAttachment(descriptor, access, ScopeAttachmentUsage::Copy); } ResultCode FrameGraph::UseCopyAttachment(const ImageScopeAttachmentDescriptor& descriptor, ScopeAttachmentAccess access) { return UseAttachment(descriptor, access, ScopeAttachmentUsage::Copy); } ResultCode FrameGraph::UseQueryPool(Ptr<QueryPool> queryPool, const RHI::Interval& interval, QueryPoolScopeAttachmentType type, ScopeAttachmentAccess access) { // We only insert an edge into the graph if the type of attachment is Local (i.e. is going to be accessed by other scopes in the current frame) if (type == QueryPoolScopeAttachmentType::Local) { ScopeId id = m_attachmentDatabase.EmplaceResourcePoolUse(*queryPool, m_currentScope->GetId()); auto found = m_scopeLookup.find(id); if (found != m_scopeLookup.end()) { InsertEdge(*found->second, *m_currentScope); } } m_currentScope->AddQueryPoolUse(queryPool, interval, access); return ResultCode::Success; } void FrameGraph::ExecuteAfter(const ScopeId& producerScopeId) { if (Scope* producer = FindScope(producerScopeId)) { InsertEdge(*producer, *m_currentScope); } } void FrameGraph::ExecuteBefore(const ScopeId& consumerScopeId) { if (Scope* consumer = FindScope(consumerScopeId)) { InsertEdge(*m_currentScope, *consumer); } } void FrameGraph::SignalFence(Fence& fence) { m_currentScope->m_fencesToSignal.push_back(&fence); } ResultCode FrameGraph::TopologicalSort() { struct NodeId { uint16_t m_nodeIndex; uint16_t m_groupId; }; AZStd::vector<NodeId> unblockedNodes; unblockedNodes.reserve(m_graphNodes.size()); // Build a list with the edges for each producer node. AZStd::vector<AZStd::list<uint32_t>> graphEdges(m_graphNodes.size()); for (uint32_t edgeIndex = 0; edgeIndex < m_graphEdges.size(); ++edgeIndex) { const GraphEdge& edge = m_graphEdges[edgeIndex]; AZStd::list<uint32_t>& edgeList = graphEdges[edge.m_producerIndex]; // Push group edges at the front so they are processed before the single ones. // We need this so nodes in the same group are together. switch (edge.m_type) { case GraphEdgeType::DifferentGroup: edgeList.push_back(edgeIndex); break; case GraphEdgeType::SameGroup: edgeList.push_front(edgeIndex); break; default: AZ_Assert(false, "Invalid edge type %d", edge.m_type); break; } } uint16_t groupCount = 0; // This loop will add all unblocked nodes, i.e. nodes that don't have any producers. This // includes the root node. for (size_t nodeIndex = 0; nodeIndex < m_graphNodes.size(); ++nodeIndex) { const GraphNode& graphNode = m_graphNodes[nodeIndex]; if (graphNode.m_unsortedProducerCount == 0) { unblockedNodes.push_back({ static_cast<uint16_t>(nodeIndex), groupCount++ }); } } // Process nodes that don't have any producers left (they have already been processed). // They get added to the unblockedNodes vector in a topological manner. while (!unblockedNodes.empty()) { const NodeId& producerNodeId = unblockedNodes.back(); const uint16_t producerIndex = producerNodeId.m_nodeIndex; const uint16_t producerGroupId = producerNodeId.m_groupId; unblockedNodes.pop_back(); const uint32_t scopeIndexNext = aznumeric_caster(m_scopes.size()); Scope* scope = m_graphNodes[producerIndex].m_scope; // Activate the scope in topological order. scope->Activate(this, scopeIndexNext, GraphGroupId(producerGroupId)); m_scopes.push_back(scope); // Go through all the edges of this node, find the consumer nodes that are fully sorted and add them to the unblockedNodes. for (const uint32_t edgeIndex : graphEdges[producerIndex]) { const GraphEdge& graphEdge = m_graphEdges[edgeIndex]; const uint16_t consumerIndex = static_cast<uint16_t>(graphEdge.m_consumerIndex); if (--m_graphNodes[consumerIndex].m_unsortedProducerCount == 0) { NodeId newNode; newNode.m_nodeIndex = consumerIndex; newNode.m_groupId = graphEdge.m_type == GraphEdgeType::SameGroup ? producerGroupId : groupCount++; unblockedNodes.emplace_back(newNode); } } graphEdges[producerIndex].clear(); } if (m_graphNodes.size() == m_scopes.size()) { return ResultCode::Success; } if (Validation::IsEnabled()) { AZStd::string cycleInfoString = "Error, a cycle exists in the graph. Failed to topologically sort. Remaining Edges:\n"; for (const AZStd::list<uint32_t>& edgeList : graphEdges) { for (uint32_t edgeIndex : edgeList) { const GraphEdge& edge = m_graphEdges[edgeIndex]; cycleInfoString += AZStd::string::format( "\t[Producer: %s], [Consumer: %s]\n", m_graphNodes[edge.m_producerIndex].m_scope->GetId().GetCStr(), m_graphNodes[edge.m_consumerIndex].m_scope->GetId().GetCStr()); } } AZ_Error("FrameGraph", false, "%s", cycleInfoString.data()); } return ResultCode::InvalidArgument; } const Scope* FrameGraph::FindScope(const ScopeId& scopeId) const { auto findIt = m_scopeLookup.find(scopeId); if (findIt != m_scopeLookup.end()) { return findIt->second; } return nullptr; } Scope* FrameGraph::FindScope(const ScopeId& scopeId) { return const_cast<Scope*>(const_cast<const FrameGraph*>(this)->FindScope(scopeId)); } Scope* FrameGraph::GetRootScope() const { return m_scopes[0]; } const AZStd::vector<Scope*>& FrameGraph::GetScopes() const { return m_scopes; } const AZStd::vector<Scope*>& FrameGraph::GetConsumers(const Scope& producer) const { return m_graphNodes[producer.m_graphNodeIndex.GetIndex()].m_consumers; } const AZStd::vector<Scope*>& FrameGraph::GetProducers(const Scope& consumer) const { return m_graphNodes[consumer.m_graphNodeIndex.GetIndex()].m_producers; } void FrameGraph::InsertEdge(Scope& producer, Scope& consumer, GraphEdgeType edgeType /*= GraphEdgeType::DifferentGroup*/) { // Ignore edges where the read and write are pointing to the same scope // This can happen if a scope is reading and writing to different mips of the same attachment if (&producer == &consumer) { return; } const GraphEdge graphEdge = { producer.m_graphNodeIndex.GetIndex(), consumer.m_graphNodeIndex.GetIndex(), edgeType }; auto findIter = AZStd::find_if(m_graphEdges.begin(), m_graphEdges.end(), [&graphEdge](const GraphEdge& element) { return element.m_consumerIndex == graphEdge.m_consumerIndex && element.m_producerIndex == graphEdge.m_producerIndex; }); if (findIter == m_graphEdges.end()) { m_graphEdges.push_back(graphEdge); GraphNode& consumerGraphNode = m_graphNodes[graphEdge.m_consumerIndex]; consumerGraphNode.m_producers.push_back(&producer); consumerGraphNode.m_unsortedProducerCount++; GraphNode& producerGraphNode = m_graphNodes[graphEdge.m_producerIndex]; producerGraphNode.m_consumers.push_back(&consumer); } else { // Update the edge type if needed. GraphEdge& edge = *findIter; edge.m_type = edgeType == GraphEdgeType::SameGroup ? edgeType : edge.m_type; } } } }
#define BOARD RASPBERRY_PI #include "Adafruit_PWMServoDriver.h" #include <unistd.h> Adafruit_PWMServoDriver::Adafruit_PWMServoDriver(const char* connector, uint8_t addr) : i2c_(connector, addr) {} void Adafruit_PWMServoDriver::begin() { reset(); } void Adafruit_PWMServoDriver::setPWM(uint8_t num, uint16_t on, uint16_t off) { //Serial.print("Setting PWM "); Serial.print(num); Serial.print(": "); Serial.print(on); Serial.print("->"); Serial.println(off); uint8_t buffer[5] = {static_cast<uint8_t>(LED0_ON_L+4*num), static_cast<uint8_t>(on), static_cast<uint8_t>(on >> 8), static_cast<uint8_t>(off), static_cast<uint8_t>(off >> 8)}; i2c_.send(buffer, 5); } uint8_t Adafruit_PWMServoDriver::read8(uint8_t addr) { uint8_t ret; i2c_.receive(addr, &ret, 1); return ret; } void Adafruit_PWMServoDriver::write8(uint8_t addr, uint8_t d) { i2c_.send(addr, &d, 1); } void Adafruit_PWMServoDriver::pwmDelay(unsigned int millisec) { usleep(millisec); } /* int mainExample() { gnublin_i2c i2c; i2c.setAddress(0x42); // set the address of the slave you want to read/write char buffer[8]; char RxBuf[8]; buffer[0]=0x22; i2c.send(buffer,5); i2c.send(0x12, buffer, 2); //send 2 bytes from buffer to register-address 0x12 i2c.receive(RxBuf, 3); // read 3 bytes and store them in RxBuf i2c.receive(0x23, RxBuf, 3); // read from tegister-address 0x23 3 bytes and store them in RxBuf }*/
#include <iostream> #include <Engine.h> #include "MainScene.h" #include "SDL.h" using namespace core; int main(int argc, char* args[]) { Engine e(new MainScene()); if (e.Init()) { std::cout << "Ensign cannot initialize" << std::endl; } return 0; }
// Copyright (c) 2011-2016 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 Bitcoin Test Suite #include <banman.h> #include <net.h> #include <boost/test/unit_test.hpp> std::unique_ptr<CConnman> g_connman; std::unique_ptr<BanMan> g_banman; [[noreturn]] void Shutdown(void *parg) { std::exit(EXIT_SUCCESS); } [[noreturn]] void StartShutdown() { std::exit(EXIT_SUCCESS); } bool ShutdownRequested() { return false; }
// Copyright 2019 The Fuchsia 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 "contiguous_pooled_memory_allocator.h" #include <lib/async-testing/test_loop.h> #include <lib/ddk/platform-defs.h> #include <lib/fake-bti/bti.h> #include <lib/inspect/cpp/reader.h> #include <lib/zx/clock.h> #include <lib/zx/vmar.h> #include <vector> #include <zxtest/zxtest.h> #include "lib/async-loop/loop.h" namespace sysmem_driver { namespace { class FakeOwner : public MemoryAllocator::Owner { public: explicit FakeOwner(inspect::Node* heap_node) : heap_node_(heap_node) { EXPECT_OK(fake_bti_create(bti_.reset_and_get_address())); } ~FakeOwner() {} const zx::bti& bti() override { return bti_; } zx_status_t CreatePhysicalVmo(uint64_t base, uint64_t size, zx::vmo* vmo_out) override { return zx::vmo::create(size, 0u, vmo_out); } inspect::Node* heap_node() override { return heap_node_; } TableSet& table_set() override { return table_set_; } private: TableSet table_set_; inspect::Node* heap_node_; zx::bti bti_; }; class ContiguousPooledSystem : public zxtest::Test { public: ContiguousPooledSystem() : allocator_(&fake_owner_, kVmoName, &inspector_.GetRoot(), 0u, kVmoSize * kVmoCount, true, // is_cpu_accessible false, // is_ready true) { // can_be_torn_down // nothing else to do here } protected: static constexpr uint32_t kVmoSize = 4096; static constexpr uint32_t kVmoCount = 1024; static constexpr char kVmoName[] = "test-pool"; inspect::Inspector inspector_; FakeOwner fake_owner_{&inspector_.GetRoot()}; ContiguousPooledMemoryAllocator allocator_; }; TEST_F(ContiguousPooledSystem, VmoNamesAreSet) { EXPECT_OK(allocator_.Init()); allocator_.set_ready(); char name[ZX_MAX_NAME_LEN] = {}; EXPECT_OK(allocator_.GetPoolVmoForTest().get_property(ZX_PROP_NAME, name, sizeof(name))); EXPECT_EQ(0u, strcmp(kVmoName, name)); zx::vmo vmo; EXPECT_OK(allocator_.Allocate(kVmoSize, {}, &vmo)); EXPECT_OK(vmo.get_property(ZX_PROP_NAME, name, sizeof(name))); EXPECT_EQ(0u, strcmp("test-pool-child", name)); allocator_.Delete(std::move(vmo)); } TEST_F(ContiguousPooledSystem, Full) { EXPECT_OK(allocator_.Init()); allocator_.set_ready(); auto hierarchy = inspect::ReadFromVmo(inspector_.DuplicateVmo()); auto* value = hierarchy.value().GetByPath({"test-pool"}); ASSERT_TRUE(value); EXPECT_LT( 0u, value->node().get_property<inspect::UintPropertyValue>("free_at_high_water_mark")->value()); std::vector<zx::vmo> vmos; for (uint32_t i = 0; i < kVmoCount; ++i) { zx::vmo vmo; EXPECT_OK(allocator_.Allocate(kVmoSize, {}, &vmo)); vmos.push_back(std::move(vmo)); } EXPECT_EQ(0u, value->node() .get_property<inspect::UintPropertyValue>("last_allocation_failed_timestamp_ns") ->value()); auto before_time = zx::clock::get_monotonic(); zx::vmo vmo; EXPECT_NOT_OK(allocator_.Allocate(kVmoSize, {}, &vmo)); auto after_time = zx::clock::get_monotonic(); hierarchy = inspect::ReadFromVmo(inspector_.DuplicateVmo()); value = hierarchy.value().GetByPath({"test-pool"}); EXPECT_LE(before_time.get(), value->node() .get_property<inspect::UintPropertyValue>("last_allocation_failed_timestamp_ns") ->value()); EXPECT_GE(after_time.get(), value->node() .get_property<inspect::UintPropertyValue>("last_allocation_failed_timestamp_ns") ->value()); allocator_.Delete(std::move(vmos[0])); EXPECT_OK(allocator_.Allocate(kVmoSize, {}, &vmos[0])); // Destroy half of all vmos. for (uint32_t i = 0; i < kVmoCount; i += 2) { ZX_DEBUG_ASSERT(vmos[i]); allocator_.Delete(std::move(vmos[i])); } // There shouldn't be enough contiguous address space for even 1 extra byte. // This check relies on sequential Allocate() calls to a brand-new allocator // being laid out sequentially, so isn't a fundamental check - if the // allocator's layout strategy changes this check might start to fail // without there necessarily being a real problem. EXPECT_NOT_OK(allocator_.Allocate(kVmoSize + 1, {}, &vmo)); // This allocation should fail because there's not enough space in the pool, with or without // fragmentation.: EXPECT_NOT_OK(allocator_.Allocate(kVmoSize * kVmoCount - 1, {}, &vmo)); hierarchy = inspect::ReadFromVmo(inspector_.DuplicateVmo()); value = hierarchy.value().GetByPath({"test-pool"}); EXPECT_EQ(3u, value->node().get_property<inspect::UintPropertyValue>("allocations_failed")->value()); EXPECT_EQ(1u, value->node() .get_property<inspect::UintPropertyValue>("allocations_failed_fragmentation") ->value()); // All memory was used at high water. EXPECT_EQ( 0u, value->node().get_property<inspect::UintPropertyValue>("max_free_at_high_water")->value()); EXPECT_EQ( 0u, value->node().get_property<inspect::UintPropertyValue>("free_at_high_water_mark")->value()); for (auto& vmo : vmos) { if (vmo) allocator_.Delete(std::move(vmo)); } } TEST_F(ContiguousPooledSystem, GetPhysicalMemoryInfo) { EXPECT_OK(allocator_.Init()); allocator_.set_ready(); zx_paddr_t base; size_t size; ASSERT_OK(allocator_.GetPhysicalMemoryInfo(&base, &size)); EXPECT_EQ(base, FAKE_BTI_PHYS_ADDR); EXPECT_EQ(size, kVmoSize * kVmoCount); } TEST_F(ContiguousPooledSystem, InitPhysical) { // Using fake-bti and the FakeOwner above, it won't be a real physical VMO anyway. EXPECT_OK(allocator_.InitPhysical(FAKE_BTI_PHYS_ADDR)); allocator_.set_ready(); zx_paddr_t base; size_t size; ASSERT_OK(allocator_.GetPhysicalMemoryInfo(&base, &size)); EXPECT_EQ(base, FAKE_BTI_PHYS_ADDR); EXPECT_EQ(size, kVmoSize * kVmoCount); zx::vmo vmo; EXPECT_OK(allocator_.Allocate(kVmoSize, {}, &vmo)); allocator_.Delete(std::move(vmo)); } TEST_F(ContiguousPooledSystem, SetReady) { EXPECT_OK(allocator_.Init()); EXPECT_FALSE(allocator_.is_ready()); zx::vmo vmo; EXPECT_EQ(ZX_ERR_BAD_STATE, allocator_.Allocate(kVmoSize, {}, &vmo)); allocator_.set_ready(); EXPECT_TRUE(allocator_.is_ready()); EXPECT_OK(allocator_.Allocate(kVmoSize, {}, &vmo)); allocator_.Delete(std::move(vmo)); } TEST_F(ContiguousPooledSystem, GuardPages) { async::TestLoop loop; const uint32_t kGuardRegionSize = zx_system_get_page_size(); EXPECT_OK(allocator_.Init()); allocator_.InitGuardRegion(kGuardRegionSize, true, false, loop.dispatcher()); allocator_.set_ready(); zx::vmo vmo; EXPECT_OK(allocator_.Allocate(kVmoSize, {}, &vmo)); EXPECT_EQ(0u, allocator_.failed_guard_region_checks()); // The guard check happens every 5 seconds, so run for 6 seconds to ensure one // happens. We're using a test loop, so it's guaranteed that it runs exactly this length of time. constexpr uint32_t kLoopTimeSeconds = 6; loop.RunFor(zx::sec(kLoopTimeSeconds)); EXPECT_EQ(0u, allocator_.failed_guard_region_checks()); uint8_t data_to_write = 1; uint64_t guard_offset = allocator_.GetVmoRegionOffsetForTest(vmo) - 1; allocator_.GetPoolVmoForTest().write(&data_to_write, guard_offset, sizeof(data_to_write)); guard_offset = allocator_.GetVmoRegionOffsetForTest(vmo) + kVmoSize + kGuardRegionSize - 1; allocator_.GetPoolVmoForTest().write(&data_to_write, guard_offset, sizeof(data_to_write)); loop.RunFor(zx::sec(kLoopTimeSeconds)); // One each for beginning and end. EXPECT_EQ(2u, allocator_.failed_guard_region_checks()); allocator_.Delete(std::move(vmo)); // Two more. EXPECT_EQ(4u, allocator_.failed_guard_region_checks()); } TEST_F(ContiguousPooledSystem, ExternalGuardPages) { async::TestLoop loop; const uint32_t kGuardRegionSize = zx_system_get_page_size(); EXPECT_OK(allocator_.Init()); allocator_.InitGuardRegion(kGuardRegionSize, false, false, loop.dispatcher()); allocator_.set_ready(); zx::vmo vmo; EXPECT_OK(allocator_.Allocate(kVmoSize, {}, &vmo)); EXPECT_EQ(0u, allocator_.failed_guard_region_checks()); // The guard check happens every 5 seconds, so run for 6 seconds to ensure one // happens. We're using a test loop, so it's guaranteed that it runs exactly this length of time. constexpr uint32_t kLoopTimeSeconds = 6; loop.RunFor(zx::sec(kLoopTimeSeconds)); EXPECT_EQ(0u, allocator_.failed_guard_region_checks()); uint8_t data_to_write = 1; uint64_t guard_offset = 1; allocator_.GetPoolVmoForTest().write(&data_to_write, guard_offset, sizeof(data_to_write)); guard_offset = kVmoSize * kVmoCount - 1; allocator_.GetPoolVmoForTest().write(&data_to_write, guard_offset, sizeof(data_to_write)); { // Write into what would be the internal guard region, to check that it isn't caught. uint8_t data_to_write = 1; uint64_t guard_offset = allocator_.GetVmoRegionOffsetForTest(vmo) - 1; allocator_.GetPoolVmoForTest().write(&data_to_write, guard_offset, sizeof(data_to_write)); guard_offset = allocator_.GetVmoRegionOffsetForTest(vmo) + kVmoSize + kGuardRegionSize - 1; allocator_.GetPoolVmoForTest().write(&data_to_write, guard_offset, sizeof(data_to_write)); } loop.RunFor(zx::sec(kLoopTimeSeconds)); // One each for beginning and end. EXPECT_EQ(2u, allocator_.failed_guard_region_checks()); allocator_.Delete(std::move(vmo)); // Deleting the allocator won't cause an external guard region check, so the count should be the // same. EXPECT_EQ(2u, allocator_.failed_guard_region_checks()); } } // namespace } // namespace sysmem_driver
// 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 "walletview.h" #include "addressbookpage.h" #include "askpassphrasedialog.h" #include "navcoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "optionsmodel.h" #include "overviewpage.h" #include "platformstyle.h" #include "getaddresstoreceive.h" #include "receivecoinsdialog.h" #include "sendcoinsdialog.h" #include "signverifymessagedialog.h" #include "transactiontablemodel.h" #include "transactionview.h" #include "walletmodel.h" #include "ui_interface.h" #include "main.h" #include <QAction> #include <QActionGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QInputDialog> #include <QProgressDialog> #include <QPushButton> #include <QVBoxLayout> WalletView::WalletView(const PlatformStyle *platformStyle, QWidget *parent): QStackedWidget(parent), clientModel(0), walletModel(0), platformStyle(platformStyle) { // Create tabs overviewPage = new OverviewPage(platformStyle); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); QHBoxLayout *hbox_buttons = new QHBoxLayout(); transactionView = new TransactionView(platformStyle, this); vbox->addWidget(transactionView); QPushButton *exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); hbox_buttons->addStretch(); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); transactionsPage->setLayout(vbox); receiveCoinsPage = new ReceiveCoinsDialog(platformStyle); sendCoinsPage = new SendCoinsDialog(platformStyle); requestPaymentPage = new getAddressToReceive(); usedSendingAddressesPage = new AddressBookPage(platformStyle, AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); usedReceivingAddressesPage = new AddressBookPage(platformStyle, AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); addWidget(overviewPage); addWidget(transactionsPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); addWidget(requestPaymentPage); // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); // Clicking on "Export" allows to export the transaction list connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked())); // Pass through messages from sendCoinsPage connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Pass through messages from transactionView connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); connect(requestPaymentPage, SIGNAL(requestPayment()), this, SLOT(gotoReceiveCoinsPage())); connect(requestPaymentPage, SIGNAL(requestAddressHistory()), this, SLOT(requestAddressHistory())); } WalletView::~WalletView() { } void WalletView::setNavCoinGUI(NavCoinGUI *gui) { if (gui) { // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage())); // Receive and report messages connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int))); // Pass through encryption status changed signals connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int))); // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString,QString))); } } void WalletView::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; overviewPage->setClientModel(clientModel); sendCoinsPage->setClientModel(clientModel); } void WalletView::requestAddressHistory() { Q_EMIT openAddressHistory(); } void WalletView::setWalletModel(WalletModel *walletModel) { this->walletModel = walletModel; // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); receiveCoinsPage->setModel(walletModel); requestPaymentPage->setModel(walletModel); requestPaymentPage->showQR(); sendCoinsPage->setModel(walletModel); usedReceivingAddressesPage->setModel(walletModel->getAddressTableModel()); usedSendingAddressesPage->setModel(walletModel->getAddressTableModel()); if (walletModel) { // Receive and pass through messages from wallet model connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Handle changes in encryption status connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int))); updateEncryptionStatus(); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(processNewTransaction(QModelIndex,int,int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int))); } } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); if (!ttm || ttm->processingQueuedTransactions()) return; QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QModelIndex index = ttm->index(start, 0, parent); QString address = ttm->data(index, TransactionTableModel::AddressRole).toString(); QString label = ttm->data(index, TransactionTableModel::LabelRole).toString(); Q_EMIT incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address, label); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); overviewPage->updateStakeReportNow(); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoRequestPaymentPage(){ setCurrentWidget(requestPaymentPage); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsPage->setAddress(addr); } void WalletView::setStatusTitleBlocks(QString text) { overviewPage->setStatusTitleBlocks(text); } void WalletView::setStatusTitleConnections(QString text) { overviewPage->setStatusTitleConnections(text); } void WalletView::setStatusTitle(QString text) { overviewPage->setStatusTitle(text); } void WalletView::setVotingStatus(QString text) { overviewPage->setVotingStatus(text); } void WalletView::setStakingStatus(QString text) { overviewPage->setStakingStatus(text); } void WalletView::showStatusTitleConnections(){ overviewPage->showStatusTitleConnections(); }; void WalletView::hideStatusTitleConnections(){ overviewPage->hideStatusTitleConnections(); }; void WalletView::showStatusTitleBlocks(){ overviewPage->showStatusTitleBlocks(); }; void WalletView::hideStatusTitleBlocks(){ overviewPage->hideStatusTitleBlocks(); }; void WalletView::showLockStaking(bool status) { overviewPage->showLockStaking(status); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(platformStyle, this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(platformStyle, this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsPage->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); } void WalletView::updateEncryptionStatus() { Q_EMIT encryptionStatusChanged(walletModel->getEncryptionStatus()); } void WalletView::encryptWallet(bool status) { if(!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this); dlg.setModel(walletModel); dlg.exec(); updateEncryptionStatus(); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), tr("Wallet Data (*.dat)"), NULL); if (filename.isEmpty()) return; if (!walletModel->backupWallet(filename)) { Q_EMIT message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } else { Q_EMIT message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); } } void WalletView::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this); dlg.setModel(walletModel); dlg.exec(); } void WalletView::setStakingStats(QString day, QString week, QString month) { overviewPage->setStakingStats(day,week,month); } void WalletView::unlockWallet() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this); dlg.setModel(walletModel); dlg.exec(); } } void WalletView::importPrivateKey() { bool ok; QString privKey = QInputDialog::getText(this, tr("Import Private Key"), tr("Private Key:"), QLineEdit::Normal, "", &ok); if (ok && !privKey.isEmpty()) { LOCK2(cs_main, pwalletMain->cs_wallet); WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled return; } CNavCoinSecret vchSecret; bool fGood = vchSecret.SetString(privKey.toStdString()); if (!fGood) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Invalid private key encoding.")); return; } CKey key = vchSecret.GetKey(); if (!key.IsValid()) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Private key outside allowed range.")); return; } CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, "", "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Address already added.")); return; } pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error adding key to wallet.")); return; } QMessageBox::information(0, tr(PACKAGE_NAME), tr("NavCoin needs to scan the chain... Please, wait.")); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } QMessageBox::information(0, tr(PACKAGE_NAME), tr("Private key correctly added!")); return; } } void WalletView::unlockWalletStaking() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::UnlockStaking, this); dlg.setModel(walletModel); dlg.exec(); } } void WalletView::lockWallet() { if(!walletModel) return; walletModel->setWalletLocked(true); } void WalletView::usedSendingAddresses() { if(!walletModel) return; usedSendingAddressesPage->show(); usedSendingAddressesPage->raise(); usedSendingAddressesPage->activateWindow(); } void WalletView::usedReceivingAddresses() { if(!walletModel) return; usedReceivingAddressesPage->show(); usedReceivingAddressesPage->raise(); usedReceivingAddressesPage->activateWindow(); } void WalletView::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); }
/** * Copyright 2020 The Magma Authors. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * 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 "SessionEvents.h" using magma::orc8r::Event; using magma::orc8r::Void; namespace { // anonymous const std::string SESSIOND_SERVICE_EV = "sessiond"; const std::string SESSION_CREATED_EV = "session_created"; const std::string SESSION_CREATE_FAILURE_EV = "session_create_failure"; const std::string SESSION_UPDATED_EV = "session_updated"; const std::string SESSION_UPDATE_FAILURE_EV = "session_update_failure"; const std::string SESSION_TERMINATED_EV = "session_terminated"; const std::string SESSION_ID = "session_id"; const std::string IMSI = "imsi"; const std::string IP_ADDR = "ip_addr"; const std::string MAC_ADDR = "mac_addr"; const std::string APN = "apn"; const std::string FAILURE_REASON = "failure_reason"; const std::string CHARGING_TX = "charging_tx"; const std::string CHARGING_RX = "charging_rx"; const std::string MONITORING_TX = "monitoring_tx"; const std::string MONITORING_RX = "monitoring_rx"; } // namespace namespace magma { namespace lte { EventsReporterImpl::EventsReporterImpl(AsyncEventdClient& eventd_client) : eventd_client_(eventd_client) {} void EventsReporterImpl::session_created( const std::string& imsi, const std::string& session_id, const SessionConfig& session_context) { auto event = magma::orc8r::Event(); event.set_stream_name(SESSIOND_SERVICE_EV); event.set_event_type(SESSION_CREATED_EV); event.set_tag(imsi); folly::dynamic event_value = folly::dynamic::object; event_value[IMSI] = imsi; event_value[SESSION_ID] = session_id; event_value[APN] = session_context.common_context.apn(); event_value[MAC_ADDR] = get_mac_addr(session_context); std::string event_value_string = folly::toJson(event_value); event.set_value(event_value_string); eventd_client_.log_event(event, [=](Status status, Void v) { if (!status.ok()) { MLOG(MERROR) << "Could not log " << SESSION_CREATED_EV << " event " << event_value_string << ", Error Message: " << status.error_message(); } }); } void EventsReporterImpl::session_create_failure( const std::string& imsi, const SessionConfig& session_context, const std::string& failure_reason) { auto event = magma::orc8r::Event(); event.set_stream_name(SESSIOND_SERVICE_EV); event.set_event_type(SESSION_CREATE_FAILURE_EV); event.set_tag(imsi); folly::dynamic event_value = folly::dynamic::object; event_value[IMSI] = imsi; event_value[APN] = session_context.common_context.apn(); event_value[FAILURE_REASON] = failure_reason; event_value[MAC_ADDR] = get_mac_addr(session_context); std::string event_value_string = folly::toJson(event_value); event.set_value(event_value_string); eventd_client_.log_event(event, [=](Status status, Void v) { if (!status.ok()) { MLOG(MERROR) << "Could not log " << SESSION_CREATE_FAILURE_EV << " event " << event_value_string << ", Error Message: " << status.error_message(); } }); } void EventsReporterImpl::session_updated( const std::string& imsi, const std::string& session_id, const SessionConfig& session_context) { auto event = magma::orc8r::Event(); event.set_stream_name(SESSIOND_SERVICE_EV); event.set_event_type(SESSION_UPDATED_EV); event.set_tag(imsi); folly::dynamic event_value = folly::dynamic::object; event_value[IMSI] = imsi; event_value[SESSION_ID] = session_id; event_value[IP_ADDR] = session_context.common_context.ue_ipv4(); event_value[APN] = session_context.common_context.apn(); event_value[MAC_ADDR] = get_mac_addr(session_context); std::string event_value_string = folly::toJson(event_value); event.set_value(event_value_string); eventd_client_.log_event(event, [=](Status status, Void v) { if (!status.ok()) { MLOG(MERROR) << "Could not log " << SESSION_UPDATED_EV << " event " << event_value_string << ", Error Message: " << status.error_message(); } }); } void EventsReporterImpl::session_update_failure( const std::string& imsi, const std::string& session_id, const SessionConfig& session_context, const std::string& failure_reason) { auto event = magma::orc8r::Event(); event.set_stream_name(SESSIOND_SERVICE_EV); event.set_event_type(SESSION_UPDATE_FAILURE_EV); folly::dynamic event_value = folly::dynamic::object; event_value[IMSI] = imsi; event_value[SESSION_ID] = session_id; event_value[IP_ADDR] = session_context.common_context.ue_ipv4(); event_value[MAC_ADDR] = get_mac_addr(session_context); event_value[APN] = session_context.common_context.apn(); event_value[FAILURE_REASON] = failure_reason; std::string event_value_string = folly::toJson(event_value); event.set_value(event_value_string); eventd_client_.log_event(event, [=](Status status, Void v) { if (!status.ok()) { MLOG(MERROR) << "Could not log " << SESSION_UPDATE_FAILURE_EV << " event " << event_value_string << ", Error Message: " << status.error_message(); } }); } void EventsReporterImpl::session_terminated( const std::string& imsi, const std::unique_ptr<SessionState>& session) { auto event = magma::orc8r::Event(); auto session_cfg = session->get_config(); event.set_stream_name(SESSIOND_SERVICE_EV); event.set_event_type(SESSION_TERMINATED_EV); event.set_tag(imsi); folly::dynamic event_value = folly::dynamic::object; event_value[IMSI] = imsi; event_value[IP_ADDR] = session_cfg.common_context.ue_ipv4(); event_value[SESSION_ID] = session->get_session_id(); event_value[MAC_ADDR] = get_mac_addr(session_cfg); event_value[APN] = session_cfg.common_context.apn(); SessionState::TotalCreditUsage usage = session->get_total_credit_usage(); event_value[CHARGING_TX] = usage.charging_tx; event_value[CHARGING_RX] = usage.charging_rx; event_value[MONITORING_TX] = usage.monitoring_tx; event_value[MONITORING_RX] = usage.monitoring_rx; std::string event_value_string = folly::toJson(event_value); event.set_value(event_value_string); eventd_client_.log_event(event, [=](Status status, Void v) { if (!status.ok()) { MLOG(MERROR) << "Could not log " << SESSION_TERMINATED_EV << " event " << event_value_string << ", Error Message: " << status.error_message(); } }); } std::string EventsReporterImpl::get_mac_addr(const SessionConfig& config) { // MacAddr is only relevant for WLAN const auto& rat_specific = config.rat_specific_context; std::string mac_addr = ""; if (rat_specific.has_wlan_context()) { mac_addr = rat_specific.wlan_context().mac_addr(); } return mac_addr; } } // namespace lte } // namespace magma
#include <iostream> #include <stack> #include <string> #include <utility> using namespace std; class Solution { public: string decodeString(const string& s) { stack<pair<string, int>> todo; todo.emplace(string(), 1); for (int i = 0; i < static_cast<int>(s.length()); ++i) { if (isdigit(s[i])) { char *end; int count = strtol(s.c_str() + i, &end, 10); todo.emplace(string(), count); i = end - s.c_str(); } else if (s[i] == ']') { auto p = move(todo.top()); todo.pop(); for (int j = 0; j < p.second; ++j) todo.top().first.append(p.first); } else { todo.top().first.push_back(s[i]); } } return todo.top().first; } }; int main() { string input[] = { "", // "" "a", // "a" "2[]", // "" "0[a]", // "" "1[a]", // "a" "2[a]", // "aa" "2[ab]", // "abab" "3[a]2[bc]", // "aaabcbc" "3[a2[c]]", // "accaccacc" "2[abc]3[cd]ef", // "abcabccdcdcdef" }; Solution solution; for (const auto& s: input) { cout << '"' << s << "\" => \"" << solution.decodeString(s) << '"' << endl; } return 0; }
// Copyright 2015 the V8 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. #include "src/compiler/wasm-compiler.h" #include <memory> #include "src/assembler-inl.h" #include "src/assembler.h" #include "src/base/optional.h" #include "src/base/platform/elapsed-timer.h" #include "src/base/platform/platform.h" #include "src/base/v8-fallthrough.h" #include "src/builtins/builtins.h" #include "src/code-factory.h" #include "src/compiler/backend/code-generator.h" #include "src/compiler/backend/instruction-selector.h" #include "src/compiler/common-operator.h" #include "src/compiler/compiler-source-position-table.h" #include "src/compiler/diamond.h" #include "src/compiler/graph-visualizer.h" #include "src/compiler/graph.h" #include "src/compiler/int64-lowering.h" #include "src/compiler/js-graph.h" #include "src/compiler/js-operator.h" #include "src/compiler/linkage.h" #include "src/compiler/machine-operator.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-origin-table.h" #include "src/compiler/pipeline.h" #include "src/compiler/simd-scalar-lowering.h" #include "src/compiler/zone-stats.h" #include "src/counters.h" #include "src/heap/factory.h" #include "src/interface-descriptors.h" #include "src/isolate-inl.h" #include "src/log-inl.h" #include "src/objects/heap-number.h" #include "src/optimized-compilation-info.h" #include "src/tracing/trace-event.h" #include "src/trap-handler/trap-handler.h" #include "src/wasm/function-body-decoder.h" #include "src/wasm/function-compiler.h" #include "src/wasm/graph-builder-interface.h" #include "src/wasm/jump-table-assembler.h" #include "src/wasm/memory-tracing.h" #include "src/wasm/object-access.h" #include "src/wasm/wasm-code-manager.h" #include "src/wasm/wasm-limits.h" #include "src/wasm/wasm-linkage.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-objects-inl.h" #include "src/wasm/wasm-opcodes.h" #include "src/wasm/wasm-text.h" namespace v8 { namespace internal { namespace compiler { namespace { // TODO(titzer): pull WASM_64 up to a common header. #if !V8_TARGET_ARCH_32_BIT || V8_TARGET_ARCH_X64 #define WASM_64 1 #else #define WASM_64 0 #endif #define FATAL_UNSUPPORTED_OPCODE(opcode) \ FATAL("Unsupported opcode 0x%x:%s", (opcode), \ wasm::WasmOpcodes::OpcodeName(opcode)); MachineType assert_size(int expected_size, MachineType type) { DCHECK_EQ(expected_size, ElementSizeInBytes(type.representation())); return type; } #define WASM_INSTANCE_OBJECT_SIZE(name) \ (WasmInstanceObject::k##name##OffsetEnd - \ WasmInstanceObject::k##name##Offset + 1) // NOLINT(whitespace/indent) #define WASM_INSTANCE_OBJECT_OFFSET(name) \ wasm::ObjectAccess::ToTagged(WasmInstanceObject::k##name##Offset) #define LOAD_RAW(base_pointer, byte_offset, type) \ SetEffect(graph()->NewNode(mcgraph()->machine()->Load(type), base_pointer, \ mcgraph()->Int32Constant(byte_offset), Effect(), \ Control())) #define LOAD_INSTANCE_FIELD(name, type) \ LOAD_RAW(instance_node_.get(), WASM_INSTANCE_OBJECT_OFFSET(name), \ assert_size(WASM_INSTANCE_OBJECT_SIZE(name), type)) #define LOAD_TAGGED_POINTER(base_pointer, byte_offset) \ LOAD_RAW(base_pointer, byte_offset, MachineType::TaggedPointer()) #define LOAD_TAGGED_ANY(base_pointer, byte_offset) \ LOAD_RAW(base_pointer, byte_offset, MachineType::AnyTagged()) #define LOAD_FIXED_ARRAY_SLOT(array_node, index, type) \ LOAD_RAW(array_node, \ wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(index), type) #define LOAD_FIXED_ARRAY_SLOT_SMI(array_node, index) \ LOAD_FIXED_ARRAY_SLOT(array_node, index, MachineType::TaggedSigned()) #define LOAD_FIXED_ARRAY_SLOT_PTR(array_node, index) \ LOAD_FIXED_ARRAY_SLOT(array_node, index, MachineType::TaggedPointer()) #define LOAD_FIXED_ARRAY_SLOT_ANY(array_node, index) \ LOAD_FIXED_ARRAY_SLOT(array_node, index, MachineType::AnyTagged()) // This can be used to store tagged Smi values only. #define STORE_FIXED_ARRAY_SLOT_SMI(array_node, index, value) \ SetEffect(graph()->NewNode( \ mcgraph()->machine()->Store(StoreRepresentation( \ MachineRepresentation::kTaggedSigned, kNoWriteBarrier)), \ array_node, \ mcgraph()->Int32Constant( \ wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(index)), \ value, Effect(), Control())) // This can be used to store any tagged (Smi and HeapObject) value. #define STORE_FIXED_ARRAY_SLOT_ANY(array_node, index, value) \ SetEffect(graph()->NewNode( \ mcgraph()->machine()->Store(StoreRepresentation( \ MachineRepresentation::kTagged, kFullWriteBarrier)), \ array_node, \ mcgraph()->Int32Constant( \ wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(index)), \ value, Effect(), Control())) void MergeControlToEnd(MachineGraph* mcgraph, Node* node) { Graph* g = mcgraph->graph(); if (g->end()) { NodeProperties::MergeControlToEnd(g, mcgraph->common(), node); } else { g->SetEnd(g->NewNode(mcgraph->common()->End(1), node)); } } bool ContainsSimd(wasm::FunctionSig* sig) { for (auto type : sig->all()) { if (type == wasm::kWasmS128) return true; } return false; } bool ContainsInt64(wasm::FunctionSig* sig) { for (auto type : sig->all()) { if (type == wasm::kWasmI64) return true; } return false; } } // namespace WasmGraphBuilder::WasmGraphBuilder( wasm::CompilationEnv* env, Zone* zone, MachineGraph* mcgraph, wasm::FunctionSig* sig, compiler::SourcePositionTable* source_position_table) : zone_(zone), mcgraph_(mcgraph), env_(env), cur_buffer_(def_buffer_), cur_bufsize_(kDefaultBufferSize), has_simd_(ContainsSimd(sig)), untrusted_code_mitigations_(FLAG_untrusted_code_mitigations), sig_(sig), source_position_table_(source_position_table) { DCHECK_IMPLIES(use_trap_handler(), trap_handler::IsTrapHandlerEnabled()); DCHECK_NOT_NULL(mcgraph_); } Node* WasmGraphBuilder::Error() { return mcgraph()->Dead(); } Node* WasmGraphBuilder::Start(unsigned params) { Node* start = graph()->NewNode(mcgraph()->common()->Start(params)); graph()->SetStart(start); return start; } Node* WasmGraphBuilder::Param(unsigned index) { return graph()->NewNode(mcgraph()->common()->Parameter(index), graph()->start()); } Node* WasmGraphBuilder::Loop(Node* entry) { return graph()->NewNode(mcgraph()->common()->Loop(1), entry); } Node* WasmGraphBuilder::TerminateLoop(Node* effect, Node* control) { Node* terminate = graph()->NewNode(mcgraph()->common()->Terminate(), effect, control); MergeControlToEnd(mcgraph(), terminate); return terminate; } Node* WasmGraphBuilder::TerminateThrow(Node* effect, Node* control) { Node* terminate = graph()->NewNode(mcgraph()->common()->Throw(), effect, control); MergeControlToEnd(mcgraph(), terminate); return terminate; } bool WasmGraphBuilder::IsPhiWithMerge(Node* phi, Node* merge) { return phi && IrOpcode::IsPhiOpcode(phi->opcode()) && NodeProperties::GetControlInput(phi) == merge; } bool WasmGraphBuilder::ThrowsException(Node* node, Node** if_success, Node** if_exception) { if (node->op()->HasProperty(compiler::Operator::kNoThrow)) { return false; } *if_success = graph()->NewNode(mcgraph()->common()->IfSuccess(), node); *if_exception = graph()->NewNode(mcgraph()->common()->IfException(), node, node); return true; } void WasmGraphBuilder::AppendToMerge(Node* merge, Node* from) { DCHECK(IrOpcode::IsMergeOpcode(merge->opcode())); merge->AppendInput(mcgraph()->zone(), from); int new_size = merge->InputCount(); NodeProperties::ChangeOp( merge, mcgraph()->common()->ResizeMergeOrPhi(merge->op(), new_size)); } void WasmGraphBuilder::AppendToPhi(Node* phi, Node* from) { DCHECK(IrOpcode::IsPhiOpcode(phi->opcode())); int new_size = phi->InputCount(); phi->InsertInput(mcgraph()->zone(), phi->InputCount() - 1, from); NodeProperties::ChangeOp( phi, mcgraph()->common()->ResizeMergeOrPhi(phi->op(), new_size)); } Node* WasmGraphBuilder::Merge(unsigned count, Node** controls) { return graph()->NewNode(mcgraph()->common()->Merge(count), count, controls); } Node* WasmGraphBuilder::Phi(wasm::ValueType type, unsigned count, Node** vals, Node* control) { DCHECK(IrOpcode::IsMergeOpcode(control->opcode())); Node** buf = Realloc(vals, count, count + 1); buf[count] = control; return graph()->NewNode( mcgraph()->common()->Phi(wasm::ValueTypes::MachineRepresentationFor(type), count), count + 1, buf); } Node* WasmGraphBuilder::EffectPhi(unsigned count, Node** effects, Node* control) { DCHECK(IrOpcode::IsMergeOpcode(control->opcode())); Node** buf = Realloc(effects, count, count + 1); buf[count] = control; return graph()->NewNode(mcgraph()->common()->EffectPhi(count), count + 1, buf); } Node* WasmGraphBuilder::RefNull() { return LOAD_INSTANCE_FIELD(NullValue, MachineType::TaggedPointer()); } Node* WasmGraphBuilder::NoContextConstant() { // TODO(titzer): avoiding a dependency on JSGraph here. Refactor. return mcgraph()->IntPtrConstant(0); } Node* WasmGraphBuilder::Uint32Constant(uint32_t value) { return mcgraph()->Uint32Constant(value); } Node* WasmGraphBuilder::Int32Constant(int32_t value) { return mcgraph()->Int32Constant(value); } Node* WasmGraphBuilder::Int64Constant(int64_t value) { return mcgraph()->Int64Constant(value); } Node* WasmGraphBuilder::IntPtrConstant(intptr_t value) { return mcgraph()->IntPtrConstant(value); } void WasmGraphBuilder::StackCheck(wasm::WasmCodePosition position, Node** effect, Node** control) { DCHECK_NOT_NULL(env_); // Wrappers don't get stack checks. if (FLAG_wasm_no_stack_checks || !env_->runtime_exception_support) { return; } if (effect == nullptr) effect = effect_; if (control == nullptr) control = control_; // This instruction sequence is matched in the instruction selector to // load the stack pointer directly on some platforms. Hence, when modifying // please also fix WasmStackCheckMatcher in node-matchers.h Node* limit_address = graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), instance_node_.get(), mcgraph()->Int32Constant(WASM_INSTANCE_OBJECT_OFFSET(StackLimitAddress)), *effect, *control); Node* limit = graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), limit_address, mcgraph()->IntPtrConstant(0), limit_address, *control); *effect = limit; Node* pointer = graph()->NewNode(mcgraph()->machine()->LoadStackPointer()); Node* check = graph()->NewNode(mcgraph()->machine()->UintLessThan(), limit, pointer); Diamond stack_check(graph(), mcgraph()->common(), check, BranchHint::kTrue); stack_check.Chain(*control); if (stack_check_call_operator_ == nullptr) { // Build and cache the stack check call operator and the constant // representing the stack check code. auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), // zone NoContextDescriptor{}, // descriptor 0, // stack parameter count CallDescriptor::kNoFlags, // flags Operator::kNoProperties, // properties StubCallMode::kCallWasmRuntimeStub); // stub call mode // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. stack_check_code_node_.set(mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmStackGuard, RelocInfo::WASM_STUB_CALL)); stack_check_call_operator_ = mcgraph()->common()->Call(call_descriptor); } Node* call = graph()->NewNode(stack_check_call_operator_.get(), stack_check_code_node_.get(), *effect, stack_check.if_false); SetSourcePosition(call, position); Node* ephi = stack_check.EffectPhi(*effect, call); *control = stack_check.merge; *effect = ephi; } void WasmGraphBuilder::PatchInStackCheckIfNeeded() { if (!needs_stack_check_) return; Node* start = graph()->start(); // Place a stack check which uses a dummy node as control and effect. Node* dummy = graph()->NewNode(mcgraph()->common()->Dead()); Node* control = dummy; Node* effect = dummy; // The function-prologue stack check is associated with position 0, which // is never a position of any instruction in the function. StackCheck(0, &effect, &control); // In testing, no steck checks were emitted. Nothing to rewire then. if (effect == dummy) return; // Now patch all control uses of {start} to use {control} and all effect uses // to use {effect} instead. Then rewire the dummy node to use start instead. NodeProperties::ReplaceUses(start, start, effect, control); NodeProperties::ReplaceUses(dummy, nullptr, start, start); } Node* WasmGraphBuilder::Binop(wasm::WasmOpcode opcode, Node* left, Node* right, wasm::WasmCodePosition position) { const Operator* op; MachineOperatorBuilder* m = mcgraph()->machine(); switch (opcode) { case wasm::kExprI32Add: op = m->Int32Add(); break; case wasm::kExprI32Sub: op = m->Int32Sub(); break; case wasm::kExprI32Mul: op = m->Int32Mul(); break; case wasm::kExprI32DivS: return BuildI32DivS(left, right, position); case wasm::kExprI32DivU: return BuildI32DivU(left, right, position); case wasm::kExprI32RemS: return BuildI32RemS(left, right, position); case wasm::kExprI32RemU: return BuildI32RemU(left, right, position); case wasm::kExprI32And: op = m->Word32And(); break; case wasm::kExprI32Ior: op = m->Word32Or(); break; case wasm::kExprI32Xor: op = m->Word32Xor(); break; case wasm::kExprI32Shl: op = m->Word32Shl(); right = MaskShiftCount32(right); break; case wasm::kExprI32ShrU: op = m->Word32Shr(); right = MaskShiftCount32(right); break; case wasm::kExprI32ShrS: op = m->Word32Sar(); right = MaskShiftCount32(right); break; case wasm::kExprI32Ror: op = m->Word32Ror(); right = MaskShiftCount32(right); break; case wasm::kExprI32Rol: right = MaskShiftCount32(right); return BuildI32Rol(left, right); case wasm::kExprI32Eq: op = m->Word32Equal(); break; case wasm::kExprI32Ne: return Invert(Binop(wasm::kExprI32Eq, left, right)); case wasm::kExprI32LtS: op = m->Int32LessThan(); break; case wasm::kExprI32LeS: op = m->Int32LessThanOrEqual(); break; case wasm::kExprI32LtU: op = m->Uint32LessThan(); break; case wasm::kExprI32LeU: op = m->Uint32LessThanOrEqual(); break; case wasm::kExprI32GtS: op = m->Int32LessThan(); std::swap(left, right); break; case wasm::kExprI32GeS: op = m->Int32LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI32GtU: op = m->Uint32LessThan(); std::swap(left, right); break; case wasm::kExprI32GeU: op = m->Uint32LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI64And: op = m->Word64And(); break; case wasm::kExprI64Add: op = m->Int64Add(); break; case wasm::kExprI64Sub: op = m->Int64Sub(); break; case wasm::kExprI64Mul: op = m->Int64Mul(); break; case wasm::kExprI64DivS: return BuildI64DivS(left, right, position); case wasm::kExprI64DivU: return BuildI64DivU(left, right, position); case wasm::kExprI64RemS: return BuildI64RemS(left, right, position); case wasm::kExprI64RemU: return BuildI64RemU(left, right, position); case wasm::kExprI64Ior: op = m->Word64Or(); break; case wasm::kExprI64Xor: op = m->Word64Xor(); break; case wasm::kExprI64Shl: op = m->Word64Shl(); right = MaskShiftCount64(right); break; case wasm::kExprI64ShrU: op = m->Word64Shr(); right = MaskShiftCount64(right); break; case wasm::kExprI64ShrS: op = m->Word64Sar(); right = MaskShiftCount64(right); break; case wasm::kExprI64Eq: op = m->Word64Equal(); break; case wasm::kExprI64Ne: return Invert(Binop(wasm::kExprI64Eq, left, right)); case wasm::kExprI64LtS: op = m->Int64LessThan(); break; case wasm::kExprI64LeS: op = m->Int64LessThanOrEqual(); break; case wasm::kExprI64LtU: op = m->Uint64LessThan(); break; case wasm::kExprI64LeU: op = m->Uint64LessThanOrEqual(); break; case wasm::kExprI64GtS: op = m->Int64LessThan(); std::swap(left, right); break; case wasm::kExprI64GeS: op = m->Int64LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI64GtU: op = m->Uint64LessThan(); std::swap(left, right); break; case wasm::kExprI64GeU: op = m->Uint64LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI64Ror: op = m->Word64Ror(); right = MaskShiftCount64(right); break; case wasm::kExprI64Rol: return BuildI64Rol(left, right); case wasm::kExprF32CopySign: return BuildF32CopySign(left, right); case wasm::kExprF64CopySign: return BuildF64CopySign(left, right); case wasm::kExprF32Add: op = m->Float32Add(); break; case wasm::kExprF32Sub: op = m->Float32Sub(); break; case wasm::kExprF32Mul: op = m->Float32Mul(); break; case wasm::kExprF32Div: op = m->Float32Div(); break; case wasm::kExprF32Eq: op = m->Float32Equal(); break; case wasm::kExprF32Ne: return Invert(Binop(wasm::kExprF32Eq, left, right)); case wasm::kExprF32Lt: op = m->Float32LessThan(); break; case wasm::kExprF32Ge: op = m->Float32LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprF32Gt: op = m->Float32LessThan(); std::swap(left, right); break; case wasm::kExprF32Le: op = m->Float32LessThanOrEqual(); break; case wasm::kExprF64Add: op = m->Float64Add(); break; case wasm::kExprF64Sub: op = m->Float64Sub(); break; case wasm::kExprF64Mul: op = m->Float64Mul(); break; case wasm::kExprF64Div: op = m->Float64Div(); break; case wasm::kExprF64Eq: op = m->Float64Equal(); break; case wasm::kExprF64Ne: return Invert(Binop(wasm::kExprF64Eq, left, right)); case wasm::kExprF64Lt: op = m->Float64LessThan(); break; case wasm::kExprF64Le: op = m->Float64LessThanOrEqual(); break; case wasm::kExprF64Gt: op = m->Float64LessThan(); std::swap(left, right); break; case wasm::kExprF64Ge: op = m->Float64LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprF32Min: op = m->Float32Min(); break; case wasm::kExprF64Min: op = m->Float64Min(); break; case wasm::kExprF32Max: op = m->Float32Max(); break; case wasm::kExprF64Max: op = m->Float64Max(); break; case wasm::kExprF64Pow: return BuildF64Pow(left, right); case wasm::kExprF64Atan2: op = m->Float64Atan2(); break; case wasm::kExprF64Mod: return BuildF64Mod(left, right); case wasm::kExprI32AsmjsDivS: return BuildI32AsmjsDivS(left, right); case wasm::kExprI32AsmjsDivU: return BuildI32AsmjsDivU(left, right); case wasm::kExprI32AsmjsRemS: return BuildI32AsmjsRemS(left, right); case wasm::kExprI32AsmjsRemU: return BuildI32AsmjsRemU(left, right); case wasm::kExprI32AsmjsStoreMem8: return BuildAsmjsStoreMem(MachineType::Int8(), left, right); case wasm::kExprI32AsmjsStoreMem16: return BuildAsmjsStoreMem(MachineType::Int16(), left, right); case wasm::kExprI32AsmjsStoreMem: return BuildAsmjsStoreMem(MachineType::Int32(), left, right); case wasm::kExprF32AsmjsStoreMem: return BuildAsmjsStoreMem(MachineType::Float32(), left, right); case wasm::kExprF64AsmjsStoreMem: return BuildAsmjsStoreMem(MachineType::Float64(), left, right); default: FATAL_UNSUPPORTED_OPCODE(opcode); } return graph()->NewNode(op, left, right); } Node* WasmGraphBuilder::Unop(wasm::WasmOpcode opcode, Node* input, wasm::WasmCodePosition position) { const Operator* op; MachineOperatorBuilder* m = mcgraph()->machine(); switch (opcode) { case wasm::kExprI32Eqz: op = m->Word32Equal(); return graph()->NewNode(op, input, mcgraph()->Int32Constant(0)); case wasm::kExprF32Abs: op = m->Float32Abs(); break; case wasm::kExprF32Neg: { op = m->Float32Neg(); break; } case wasm::kExprF32Sqrt: op = m->Float32Sqrt(); break; case wasm::kExprF64Abs: op = m->Float64Abs(); break; case wasm::kExprF64Neg: { op = m->Float64Neg(); break; } case wasm::kExprF64Sqrt: op = m->Float64Sqrt(); break; case wasm::kExprI32SConvertF32: case wasm::kExprI32UConvertF32: case wasm::kExprI32SConvertF64: case wasm::kExprI32UConvertF64: case wasm::kExprI32SConvertSatF64: case wasm::kExprI32UConvertSatF64: case wasm::kExprI32SConvertSatF32: case wasm::kExprI32UConvertSatF32: return BuildIntConvertFloat(input, position, opcode); case wasm::kExprI32AsmjsSConvertF64: return BuildI32AsmjsSConvertF64(input); case wasm::kExprI32AsmjsUConvertF64: return BuildI32AsmjsUConvertF64(input); case wasm::kExprF32ConvertF64: op = m->TruncateFloat64ToFloat32(); break; case wasm::kExprF64SConvertI32: op = m->ChangeInt32ToFloat64(); break; case wasm::kExprF64UConvertI32: op = m->ChangeUint32ToFloat64(); break; case wasm::kExprF32SConvertI32: op = m->RoundInt32ToFloat32(); break; case wasm::kExprF32UConvertI32: op = m->RoundUint32ToFloat32(); break; case wasm::kExprI32AsmjsSConvertF32: return BuildI32AsmjsSConvertF32(input); case wasm::kExprI32AsmjsUConvertF32: return BuildI32AsmjsUConvertF32(input); case wasm::kExprF64ConvertF32: op = m->ChangeFloat32ToFloat64(); break; case wasm::kExprF32ReinterpretI32: op = m->BitcastInt32ToFloat32(); break; case wasm::kExprI32ReinterpretF32: op = m->BitcastFloat32ToInt32(); break; case wasm::kExprI32Clz: op = m->Word32Clz(); break; case wasm::kExprI32Ctz: { if (m->Word32Ctz().IsSupported()) { op = m->Word32Ctz().op(); break; } else if (m->Word32ReverseBits().IsSupported()) { Node* reversed = graph()->NewNode(m->Word32ReverseBits().op(), input); Node* result = graph()->NewNode(m->Word32Clz(), reversed); return result; } else { return BuildI32Ctz(input); } } case wasm::kExprI32Popcnt: { if (m->Word32Popcnt().IsSupported()) { op = m->Word32Popcnt().op(); break; } else { return BuildI32Popcnt(input); } } case wasm::kExprF32Floor: { if (!m->Float32RoundDown().IsSupported()) return BuildF32Floor(input); op = m->Float32RoundDown().op(); break; } case wasm::kExprF32Ceil: { if (!m->Float32RoundUp().IsSupported()) return BuildF32Ceil(input); op = m->Float32RoundUp().op(); break; } case wasm::kExprF32Trunc: { if (!m->Float32RoundTruncate().IsSupported()) return BuildF32Trunc(input); op = m->Float32RoundTruncate().op(); break; } case wasm::kExprF32NearestInt: { if (!m->Float32RoundTiesEven().IsSupported()) return BuildF32NearestInt(input); op = m->Float32RoundTiesEven().op(); break; } case wasm::kExprF64Floor: { if (!m->Float64RoundDown().IsSupported()) return BuildF64Floor(input); op = m->Float64RoundDown().op(); break; } case wasm::kExprF64Ceil: { if (!m->Float64RoundUp().IsSupported()) return BuildF64Ceil(input); op = m->Float64RoundUp().op(); break; } case wasm::kExprF64Trunc: { if (!m->Float64RoundTruncate().IsSupported()) return BuildF64Trunc(input); op = m->Float64RoundTruncate().op(); break; } case wasm::kExprF64NearestInt: { if (!m->Float64RoundTiesEven().IsSupported()) return BuildF64NearestInt(input); op = m->Float64RoundTiesEven().op(); break; } case wasm::kExprF64Acos: { return BuildF64Acos(input); } case wasm::kExprF64Asin: { return BuildF64Asin(input); } case wasm::kExprF64Atan: op = m->Float64Atan(); break; case wasm::kExprF64Cos: { op = m->Float64Cos(); break; } case wasm::kExprF64Sin: { op = m->Float64Sin(); break; } case wasm::kExprF64Tan: { op = m->Float64Tan(); break; } case wasm::kExprF64Exp: { op = m->Float64Exp(); break; } case wasm::kExprF64Log: op = m->Float64Log(); break; case wasm::kExprI32ConvertI64: op = m->TruncateInt64ToInt32(); break; case wasm::kExprI64SConvertI32: op = m->ChangeInt32ToInt64(); break; case wasm::kExprI64UConvertI32: op = m->ChangeUint32ToUint64(); break; case wasm::kExprF64ReinterpretI64: op = m->BitcastInt64ToFloat64(); break; case wasm::kExprI64ReinterpretF64: op = m->BitcastFloat64ToInt64(); break; case wasm::kExprI64Clz: op = m->Word64Clz(); break; case wasm::kExprI64Ctz: { OptionalOperator ctz64 = m->Word64Ctz(); if (ctz64.IsSupported()) { op = ctz64.op(); break; } else if (m->Is32() && m->Word32Ctz().IsSupported()) { op = ctz64.placeholder(); break; } else if (m->Word64ReverseBits().IsSupported()) { Node* reversed = graph()->NewNode(m->Word64ReverseBits().op(), input); Node* result = graph()->NewNode(m->Word64Clz(), reversed); return result; } else { return BuildI64Ctz(input); } } case wasm::kExprI64Popcnt: { OptionalOperator popcnt64 = m->Word64Popcnt(); if (popcnt64.IsSupported()) { op = popcnt64.op(); } else if (m->Is32() && m->Word32Popcnt().IsSupported()) { op = popcnt64.placeholder(); } else { return BuildI64Popcnt(input); } break; } case wasm::kExprI64Eqz: op = m->Word64Equal(); return graph()->NewNode(op, input, mcgraph()->Int64Constant(0)); case wasm::kExprF32SConvertI64: if (m->Is32()) { return BuildF32SConvertI64(input); } op = m->RoundInt64ToFloat32(); break; case wasm::kExprF32UConvertI64: if (m->Is32()) { return BuildF32UConvertI64(input); } op = m->RoundUint64ToFloat32(); break; case wasm::kExprF64SConvertI64: if (m->Is32()) { return BuildF64SConvertI64(input); } op = m->RoundInt64ToFloat64(); break; case wasm::kExprF64UConvertI64: if (m->Is32()) { return BuildF64UConvertI64(input); } op = m->RoundUint64ToFloat64(); break; case wasm::kExprI32SExtendI8: op = m->SignExtendWord8ToInt32(); break; case wasm::kExprI32SExtendI16: op = m->SignExtendWord16ToInt32(); break; case wasm::kExprI64SExtendI8: op = m->SignExtendWord8ToInt64(); break; case wasm::kExprI64SExtendI16: op = m->SignExtendWord16ToInt64(); break; case wasm::kExprI64SExtendI32: op = m->SignExtendWord32ToInt64(); break; case wasm::kExprI64SConvertF32: case wasm::kExprI64UConvertF32: case wasm::kExprI64SConvertF64: case wasm::kExprI64UConvertF64: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64UConvertSatF32: case wasm::kExprI64SConvertSatF64: case wasm::kExprI64UConvertSatF64: return mcgraph()->machine()->Is32() ? BuildCcallConvertFloat(input, position, opcode) : BuildIntConvertFloat(input, position, opcode); case wasm::kExprRefIsNull: return graph()->NewNode(m->WordEqual(), input, RefNull()); case wasm::kExprI32AsmjsLoadMem8S: return BuildAsmjsLoadMem(MachineType::Int8(), input); case wasm::kExprI32AsmjsLoadMem8U: return BuildAsmjsLoadMem(MachineType::Uint8(), input); case wasm::kExprI32AsmjsLoadMem16S: return BuildAsmjsLoadMem(MachineType::Int16(), input); case wasm::kExprI32AsmjsLoadMem16U: return BuildAsmjsLoadMem(MachineType::Uint16(), input); case wasm::kExprI32AsmjsLoadMem: return BuildAsmjsLoadMem(MachineType::Int32(), input); case wasm::kExprF32AsmjsLoadMem: return BuildAsmjsLoadMem(MachineType::Float32(), input); case wasm::kExprF64AsmjsLoadMem: return BuildAsmjsLoadMem(MachineType::Float64(), input); default: FATAL_UNSUPPORTED_OPCODE(opcode); } return graph()->NewNode(op, input); } Node* WasmGraphBuilder::Float32Constant(float value) { return mcgraph()->Float32Constant(value); } Node* WasmGraphBuilder::Float64Constant(double value) { return mcgraph()->Float64Constant(value); } namespace { Node* Branch(MachineGraph* mcgraph, Node* cond, Node** true_node, Node** false_node, Node* control, BranchHint hint) { DCHECK_NOT_NULL(cond); DCHECK_NOT_NULL(control); Node* branch = mcgraph->graph()->NewNode(mcgraph->common()->Branch(hint), cond, control); *true_node = mcgraph->graph()->NewNode(mcgraph->common()->IfTrue(), branch); *false_node = mcgraph->graph()->NewNode(mcgraph->common()->IfFalse(), branch); return branch; } } // namespace Node* WasmGraphBuilder::BranchNoHint(Node* cond, Node** true_node, Node** false_node) { return Branch(mcgraph(), cond, true_node, false_node, Control(), BranchHint::kNone); } Node* WasmGraphBuilder::BranchExpectTrue(Node* cond, Node** true_node, Node** false_node) { return Branch(mcgraph(), cond, true_node, false_node, Control(), BranchHint::kTrue); } Node* WasmGraphBuilder::BranchExpectFalse(Node* cond, Node** true_node, Node** false_node) { return Branch(mcgraph(), cond, true_node, false_node, Control(), BranchHint::kFalse); } TrapId WasmGraphBuilder::GetTrapIdForTrap(wasm::TrapReason reason) { // TODO(wasm): "!env_" should not happen when compiling an actual wasm // function. if (!env_ || !env_->runtime_exception_support) { // We use TrapId::kInvalid as a marker to tell the code generator // to generate a call to a testing c-function instead of a runtime // stub. This code should only be called from a cctest. return TrapId::kInvalid; } switch (reason) { #define TRAPREASON_TO_TRAPID(name) \ case wasm::k##name: \ static_assert( \ static_cast<int>(TrapId::k##name) == wasm::WasmCode::kThrowWasm##name, \ "trap id mismatch"); \ return TrapId::k##name; FOREACH_WASM_TRAPREASON(TRAPREASON_TO_TRAPID) #undef TRAPREASON_TO_TRAPID default: UNREACHABLE(); } } Node* WasmGraphBuilder::TrapIfTrue(wasm::TrapReason reason, Node* cond, wasm::WasmCodePosition position) { TrapId trap_id = GetTrapIdForTrap(reason); Node* node = SetControl(graph()->NewNode(mcgraph()->common()->TrapIf(trap_id), cond, Effect(), Control())); SetSourcePosition(node, position); return node; } Node* WasmGraphBuilder::TrapIfFalse(wasm::TrapReason reason, Node* cond, wasm::WasmCodePosition position) { TrapId trap_id = GetTrapIdForTrap(reason); Node* node = SetControl(graph()->NewNode( mcgraph()->common()->TrapUnless(trap_id), cond, Effect(), Control())); SetSourcePosition(node, position); return node; } // Add a check that traps if {node} is equal to {val}. Node* WasmGraphBuilder::TrapIfEq32(wasm::TrapReason reason, Node* node, int32_t val, wasm::WasmCodePosition position) { Int32Matcher m(node); if (m.HasValue() && !m.Is(val)) return graph()->start(); if (val == 0) { return TrapIfFalse(reason, node, position); } else { return TrapIfTrue(reason, graph()->NewNode(mcgraph()->machine()->Word32Equal(), node, mcgraph()->Int32Constant(val)), position); } } // Add a check that traps if {node} is zero. Node* WasmGraphBuilder::ZeroCheck32(wasm::TrapReason reason, Node* node, wasm::WasmCodePosition position) { return TrapIfEq32(reason, node, 0, position); } // Add a check that traps if {node} is equal to {val}. Node* WasmGraphBuilder::TrapIfEq64(wasm::TrapReason reason, Node* node, int64_t val, wasm::WasmCodePosition position) { Int64Matcher m(node); if (m.HasValue() && !m.Is(val)) return graph()->start(); return TrapIfTrue(reason, graph()->NewNode(mcgraph()->machine()->Word64Equal(), node, mcgraph()->Int64Constant(val)), position); } // Add a check that traps if {node} is zero. Node* WasmGraphBuilder::ZeroCheck64(wasm::TrapReason reason, Node* node, wasm::WasmCodePosition position) { return TrapIfEq64(reason, node, 0, position); } Node* WasmGraphBuilder::Switch(unsigned count, Node* key) { return graph()->NewNode(mcgraph()->common()->Switch(count), key, Control()); } Node* WasmGraphBuilder::IfValue(int32_t value, Node* sw) { DCHECK_EQ(IrOpcode::kSwitch, sw->opcode()); return graph()->NewNode(mcgraph()->common()->IfValue(value), sw); } Node* WasmGraphBuilder::IfDefault(Node* sw) { DCHECK_EQ(IrOpcode::kSwitch, sw->opcode()); return graph()->NewNode(mcgraph()->common()->IfDefault(), sw); } Node* WasmGraphBuilder::Return(unsigned count, Node** vals) { static const int kStackAllocatedNodeBufferSize = 8; Node* stack_buffer[kStackAllocatedNodeBufferSize]; std::vector<Node*> heap_buffer; Node** buf = stack_buffer; if (count + 3 > kStackAllocatedNodeBufferSize) { heap_buffer.resize(count + 3); buf = heap_buffer.data(); } buf[0] = mcgraph()->Int32Constant(0); memcpy(buf + 1, vals, sizeof(void*) * count); buf[count + 1] = Effect(); buf[count + 2] = Control(); Node* ret = graph()->NewNode(mcgraph()->common()->Return(count), count + 3, buf); MergeControlToEnd(mcgraph(), ret); return ret; } Node* WasmGraphBuilder::ReturnVoid() { return Return(0, nullptr); } Node* WasmGraphBuilder::Unreachable(wasm::WasmCodePosition position) { TrapIfFalse(wasm::TrapReason::kTrapUnreachable, Int32Constant(0), position); ReturnVoid(); return nullptr; } Node* WasmGraphBuilder::MaskShiftCount32(Node* node) { static const int32_t kMask32 = 0x1F; if (!mcgraph()->machine()->Word32ShiftIsSafe()) { // Shifts by constants are so common we pattern-match them here. Int32Matcher match(node); if (match.HasValue()) { int32_t masked = (match.Value() & kMask32); if (match.Value() != masked) node = mcgraph()->Int32Constant(masked); } else { node = graph()->NewNode(mcgraph()->machine()->Word32And(), node, mcgraph()->Int32Constant(kMask32)); } } return node; } Node* WasmGraphBuilder::MaskShiftCount64(Node* node) { static const int64_t kMask64 = 0x3F; if (!mcgraph()->machine()->Word32ShiftIsSafe()) { // Shifts by constants are so common we pattern-match them here. Int64Matcher match(node); if (match.HasValue()) { int64_t masked = (match.Value() & kMask64); if (match.Value() != masked) node = mcgraph()->Int64Constant(masked); } else { node = graph()->NewNode(mcgraph()->machine()->Word64And(), node, mcgraph()->Int64Constant(kMask64)); } } return node; } static bool ReverseBytesSupported(MachineOperatorBuilder* m, size_t size_in_bytes) { switch (size_in_bytes) { case 4: case 16: return true; case 8: return m->Is64(); default: break; } return false; } Node* WasmGraphBuilder::BuildChangeEndiannessStore( Node* node, MachineRepresentation mem_rep, wasm::ValueType wasmtype) { Node* result; Node* value = node; MachineOperatorBuilder* m = mcgraph()->machine(); int valueSizeInBytes = wasm::ValueTypes::ElementSizeInBytes(wasmtype); int valueSizeInBits = 8 * valueSizeInBytes; bool isFloat = false; switch (wasmtype) { case wasm::kWasmF64: value = graph()->NewNode(m->BitcastFloat64ToInt64(), node); isFloat = true; V8_FALLTHROUGH; case wasm::kWasmI64: result = mcgraph()->Int64Constant(0); break; case wasm::kWasmF32: value = graph()->NewNode(m->BitcastFloat32ToInt32(), node); isFloat = true; V8_FALLTHROUGH; case wasm::kWasmI32: result = mcgraph()->Int32Constant(0); break; case wasm::kWasmS128: DCHECK(ReverseBytesSupported(m, valueSizeInBytes)); break; default: UNREACHABLE(); break; } if (mem_rep == MachineRepresentation::kWord8) { // No need to change endianness for byte size, return original node return node; } if (wasmtype == wasm::kWasmI64 && mem_rep < MachineRepresentation::kWord64) { // In case we store lower part of WasmI64 expression, we can truncate // upper 32bits value = graph()->NewNode(m->TruncateInt64ToInt32(), value); valueSizeInBytes = wasm::ValueTypes::ElementSizeInBytes(wasm::kWasmI32); valueSizeInBits = 8 * valueSizeInBytes; if (mem_rep == MachineRepresentation::kWord16) { value = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(16)); } } else if (wasmtype == wasm::kWasmI32 && mem_rep == MachineRepresentation::kWord16) { value = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(16)); } int i; uint32_t shiftCount; if (ReverseBytesSupported(m, valueSizeInBytes)) { switch (valueSizeInBytes) { case 4: result = graph()->NewNode(m->Word32ReverseBytes(), value); break; case 8: result = graph()->NewNode(m->Word64ReverseBytes(), value); break; case 16: { Node* byte_reversed_lanes[4]; for (int lane = 0; lane < 4; lane++) { byte_reversed_lanes[lane] = graph()->NewNode( m->Word32ReverseBytes(), graph()->NewNode(mcgraph()->machine()->I32x4ExtractLane(lane), value)); } // This is making a copy of the value. result = graph()->NewNode(mcgraph()->machine()->S128And(), value, value); for (int lane = 0; lane < 4; lane++) { result = graph()->NewNode(mcgraph()->machine()->I32x4ReplaceLane(3 - lane), result, byte_reversed_lanes[lane]); } break; } default: UNREACHABLE(); break; } } else { for (i = 0, shiftCount = valueSizeInBits - 8; i < valueSizeInBits / 2; i += 8, shiftCount -= 16) { Node* shiftLower; Node* shiftHigher; Node* lowerByte; Node* higherByte; DCHECK_LT(0, shiftCount); DCHECK_EQ(0, (shiftCount + 8) % 16); if (valueSizeInBits > 32) { shiftLower = graph()->NewNode(m->Word64Shl(), value, mcgraph()->Int64Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word64Shr(), value, mcgraph()->Int64Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word64And(), shiftLower, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word64And(), shiftHigher, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << i)); result = graph()->NewNode(m->Word64Or(), result, lowerByte); result = graph()->NewNode(m->Word64Or(), result, higherByte); } else { shiftLower = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word32Shr(), value, mcgraph()->Int32Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word32And(), shiftLower, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word32And(), shiftHigher, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << i)); result = graph()->NewNode(m->Word32Or(), result, lowerByte); result = graph()->NewNode(m->Word32Or(), result, higherByte); } } } if (isFloat) { switch (wasmtype) { case wasm::kWasmF64: result = graph()->NewNode(m->BitcastInt64ToFloat64(), result); break; case wasm::kWasmF32: result = graph()->NewNode(m->BitcastInt32ToFloat32(), result); break; default: UNREACHABLE(); break; } } return result; } Node* WasmGraphBuilder::BuildChangeEndiannessLoad(Node* node, MachineType memtype, wasm::ValueType wasmtype) { Node* result; Node* value = node; MachineOperatorBuilder* m = mcgraph()->machine(); int valueSizeInBytes = ElementSizeInBytes(memtype.representation()); int valueSizeInBits = 8 * valueSizeInBytes; bool isFloat = false; switch (memtype.representation()) { case MachineRepresentation::kFloat64: value = graph()->NewNode(m->BitcastFloat64ToInt64(), node); isFloat = true; V8_FALLTHROUGH; case MachineRepresentation::kWord64: result = mcgraph()->Int64Constant(0); break; case MachineRepresentation::kFloat32: value = graph()->NewNode(m->BitcastFloat32ToInt32(), node); isFloat = true; V8_FALLTHROUGH; case MachineRepresentation::kWord32: case MachineRepresentation::kWord16: result = mcgraph()->Int32Constant(0); break; case MachineRepresentation::kWord8: // No need to change endianness for byte size, return original node return node; break; case MachineRepresentation::kSimd128: DCHECK(ReverseBytesSupported(m, valueSizeInBytes)); break; default: UNREACHABLE(); break; } int i; uint32_t shiftCount; if (ReverseBytesSupported(m, valueSizeInBytes < 4 ? 4 : valueSizeInBytes)) { switch (valueSizeInBytes) { case 2: result = graph()->NewNode(m->Word32ReverseBytes(), graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(16))); break; case 4: result = graph()->NewNode(m->Word32ReverseBytes(), value); break; case 8: result = graph()->NewNode(m->Word64ReverseBytes(), value); break; case 16: { Node* byte_reversed_lanes[4]; for (int lane = 0; lane < 4; lane++) { byte_reversed_lanes[lane] = graph()->NewNode( m->Word32ReverseBytes(), graph()->NewNode(mcgraph()->machine()->I32x4ExtractLane(lane), value)); } // This is making a copy of the value. result = graph()->NewNode(mcgraph()->machine()->S128And(), value, value); for (int lane = 0; lane < 4; lane++) { result = graph()->NewNode(mcgraph()->machine()->I32x4ReplaceLane(3 - lane), result, byte_reversed_lanes[lane]); } break; } default: UNREACHABLE(); } } else { for (i = 0, shiftCount = valueSizeInBits - 8; i < valueSizeInBits / 2; i += 8, shiftCount -= 16) { Node* shiftLower; Node* shiftHigher; Node* lowerByte; Node* higherByte; DCHECK_LT(0, shiftCount); DCHECK_EQ(0, (shiftCount + 8) % 16); if (valueSizeInBits > 32) { shiftLower = graph()->NewNode(m->Word64Shl(), value, mcgraph()->Int64Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word64Shr(), value, mcgraph()->Int64Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word64And(), shiftLower, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word64And(), shiftHigher, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << i)); result = graph()->NewNode(m->Word64Or(), result, lowerByte); result = graph()->NewNode(m->Word64Or(), result, higherByte); } else { shiftLower = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word32Shr(), value, mcgraph()->Int32Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word32And(), shiftLower, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word32And(), shiftHigher, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << i)); result = graph()->NewNode(m->Word32Or(), result, lowerByte); result = graph()->NewNode(m->Word32Or(), result, higherByte); } } } if (isFloat) { switch (memtype.representation()) { case MachineRepresentation::kFloat64: result = graph()->NewNode(m->BitcastInt64ToFloat64(), result); break; case MachineRepresentation::kFloat32: result = graph()->NewNode(m->BitcastInt32ToFloat32(), result); break; default: UNREACHABLE(); break; } } // We need to sign extend the value if (memtype.IsSigned()) { DCHECK(!isFloat); if (valueSizeInBits < 32) { Node* shiftBitCount; // Perform sign extension using following trick // result = (x << machine_width - type_width) >> (machine_width - // type_width) if (wasmtype == wasm::kWasmI64) { shiftBitCount = mcgraph()->Int32Constant(64 - valueSizeInBits); result = graph()->NewNode( m->Word64Sar(), graph()->NewNode(m->Word64Shl(), graph()->NewNode(m->ChangeInt32ToInt64(), result), shiftBitCount), shiftBitCount); } else if (wasmtype == wasm::kWasmI32) { shiftBitCount = mcgraph()->Int32Constant(32 - valueSizeInBits); result = graph()->NewNode( m->Word32Sar(), graph()->NewNode(m->Word32Shl(), result, shiftBitCount), shiftBitCount); } } } return result; } Node* WasmGraphBuilder::BuildF32CopySign(Node* left, Node* right) { Node* result = Unop( wasm::kExprF32ReinterpretI32, Binop(wasm::kExprI32Ior, Binop(wasm::kExprI32And, Unop(wasm::kExprI32ReinterpretF32, left), mcgraph()->Int32Constant(0x7FFFFFFF)), Binop(wasm::kExprI32And, Unop(wasm::kExprI32ReinterpretF32, right), mcgraph()->Int32Constant(0x80000000)))); return result; } Node* WasmGraphBuilder::BuildF64CopySign(Node* left, Node* right) { #if WASM_64 Node* result = Unop( wasm::kExprF64ReinterpretI64, Binop(wasm::kExprI64Ior, Binop(wasm::kExprI64And, Unop(wasm::kExprI64ReinterpretF64, left), mcgraph()->Int64Constant(0x7FFFFFFFFFFFFFFF)), Binop(wasm::kExprI64And, Unop(wasm::kExprI64ReinterpretF64, right), mcgraph()->Int64Constant(0x8000000000000000)))); return result; #else MachineOperatorBuilder* m = mcgraph()->machine(); Node* high_word_left = graph()->NewNode(m->Float64ExtractHighWord32(), left); Node* high_word_right = graph()->NewNode(m->Float64ExtractHighWord32(), right); Node* new_high_word = Binop(wasm::kExprI32Ior, Binop(wasm::kExprI32And, high_word_left, mcgraph()->Int32Constant(0x7FFFFFFF)), Binop(wasm::kExprI32And, high_word_right, mcgraph()->Int32Constant(0x80000000))); return graph()->NewNode(m->Float64InsertHighWord32(), left, new_high_word); #endif } namespace { MachineType IntConvertType(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32SConvertF64: case wasm::kExprI32SConvertSatF32: case wasm::kExprI32SConvertSatF64: return MachineType::Int32(); case wasm::kExprI32UConvertF32: case wasm::kExprI32UConvertF64: case wasm::kExprI32UConvertSatF32: case wasm::kExprI32UConvertSatF64: return MachineType::Uint32(); case wasm::kExprI64SConvertF32: case wasm::kExprI64SConvertF64: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64SConvertSatF64: return MachineType::Int64(); case wasm::kExprI64UConvertF32: case wasm::kExprI64UConvertF64: case wasm::kExprI64UConvertSatF32: case wasm::kExprI64UConvertSatF64: return MachineType::Uint64(); default: UNREACHABLE(); } } MachineType FloatConvertType(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32UConvertF32: case wasm::kExprI32SConvertSatF32: case wasm::kExprI64SConvertF32: case wasm::kExprI64UConvertF32: case wasm::kExprI32UConvertSatF32: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64UConvertSatF32: return MachineType::Float32(); case wasm::kExprI32SConvertF64: case wasm::kExprI32UConvertF64: case wasm::kExprI64SConvertF64: case wasm::kExprI64UConvertF64: case wasm::kExprI32SConvertSatF64: case wasm::kExprI32UConvertSatF64: case wasm::kExprI64SConvertSatF64: case wasm::kExprI64UConvertSatF64: return MachineType::Float64(); default: UNREACHABLE(); } } const Operator* ConvertOp(WasmGraphBuilder* builder, wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32SConvertSatF32: return builder->mcgraph()->machine()->TruncateFloat32ToInt32(); case wasm::kExprI32UConvertF32: case wasm::kExprI32UConvertSatF32: return builder->mcgraph()->machine()->TruncateFloat32ToUint32(); case wasm::kExprI32SConvertF64: case wasm::kExprI32SConvertSatF64: return builder->mcgraph()->machine()->ChangeFloat64ToInt32(); case wasm::kExprI32UConvertF64: case wasm::kExprI32UConvertSatF64: return builder->mcgraph()->machine()->TruncateFloat64ToUint32(); case wasm::kExprI64SConvertF32: case wasm::kExprI64SConvertSatF32: return builder->mcgraph()->machine()->TryTruncateFloat32ToInt64(); case wasm::kExprI64UConvertF32: case wasm::kExprI64UConvertSatF32: return builder->mcgraph()->machine()->TryTruncateFloat32ToUint64(); case wasm::kExprI64SConvertF64: case wasm::kExprI64SConvertSatF64: return builder->mcgraph()->machine()->TryTruncateFloat64ToInt64(); case wasm::kExprI64UConvertF64: case wasm::kExprI64UConvertSatF64: return builder->mcgraph()->machine()->TryTruncateFloat64ToUint64(); default: UNREACHABLE(); } } wasm::WasmOpcode ConvertBackOp(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32SConvertSatF32: return wasm::kExprF32SConvertI32; case wasm::kExprI32UConvertF32: case wasm::kExprI32UConvertSatF32: return wasm::kExprF32UConvertI32; case wasm::kExprI32SConvertF64: case wasm::kExprI32SConvertSatF64: return wasm::kExprF64SConvertI32; case wasm::kExprI32UConvertF64: case wasm::kExprI32UConvertSatF64: return wasm::kExprF64UConvertI32; default: UNREACHABLE(); } } bool IsTrappingConvertOp(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32UConvertF32: case wasm::kExprI32SConvertF64: case wasm::kExprI32UConvertF64: case wasm::kExprI64SConvertF32: case wasm::kExprI64UConvertF32: case wasm::kExprI64SConvertF64: case wasm::kExprI64UConvertF64: return true; case wasm::kExprI32SConvertSatF64: case wasm::kExprI32UConvertSatF64: case wasm::kExprI32SConvertSatF32: case wasm::kExprI32UConvertSatF32: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64UConvertSatF32: case wasm::kExprI64SConvertSatF64: case wasm::kExprI64UConvertSatF64: return false; default: UNREACHABLE(); } } Node* Zero(WasmGraphBuilder* builder, const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kWord32: return builder->Int32Constant(0); case MachineRepresentation::kWord64: return builder->Int64Constant(0); case MachineRepresentation::kFloat32: return builder->Float32Constant(0.0); case MachineRepresentation::kFloat64: return builder->Float64Constant(0.0); default: UNREACHABLE(); } } Node* Min(WasmGraphBuilder* builder, const MachineType& ty) { switch (ty.semantic()) { case MachineSemantic::kInt32: return builder->Int32Constant(std::numeric_limits<int32_t>::min()); case MachineSemantic::kUint32: return builder->Int32Constant(std::numeric_limits<uint32_t>::min()); case MachineSemantic::kInt64: return builder->Int64Constant(std::numeric_limits<int64_t>::min()); case MachineSemantic::kUint64: return builder->Int64Constant(std::numeric_limits<uint64_t>::min()); default: UNREACHABLE(); } } Node* Max(WasmGraphBuilder* builder, const MachineType& ty) { switch (ty.semantic()) { case MachineSemantic::kInt32: return builder->Int32Constant(std::numeric_limits<int32_t>::max()); case MachineSemantic::kUint32: return builder->Int32Constant(std::numeric_limits<uint32_t>::max()); case MachineSemantic::kInt64: return builder->Int64Constant(std::numeric_limits<int64_t>::max()); case MachineSemantic::kUint64: return builder->Int64Constant(std::numeric_limits<uint64_t>::max()); default: UNREACHABLE(); } } wasm::WasmOpcode TruncOp(const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kFloat32: return wasm::kExprF32Trunc; case MachineRepresentation::kFloat64: return wasm::kExprF64Trunc; default: UNREACHABLE(); } } wasm::WasmOpcode NeOp(const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kFloat32: return wasm::kExprF32Ne; case MachineRepresentation::kFloat64: return wasm::kExprF64Ne; default: UNREACHABLE(); } } wasm::WasmOpcode LtOp(const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kFloat32: return wasm::kExprF32Lt; case MachineRepresentation::kFloat64: return wasm::kExprF64Lt; default: UNREACHABLE(); } } Node* ConvertTrapTest(WasmGraphBuilder* builder, wasm::WasmOpcode opcode, const MachineType& int_ty, const MachineType& float_ty, Node* trunc, Node* converted_value) { if (int_ty.representation() == MachineRepresentation::kWord32) { Node* check = builder->Unop(ConvertBackOp(opcode), converted_value); return builder->Binop(NeOp(float_ty), trunc, check); } return builder->graph()->NewNode(builder->mcgraph()->common()->Projection(1), trunc, builder->graph()->start()); } Node* ConvertSaturateTest(WasmGraphBuilder* builder, wasm::WasmOpcode opcode, const MachineType& int_ty, const MachineType& float_ty, Node* trunc, Node* converted_value) { Node* test = ConvertTrapTest(builder, opcode, int_ty, float_ty, trunc, converted_value); if (int_ty.representation() == MachineRepresentation::kWord64) { test = builder->Binop(wasm::kExprI64Eq, test, builder->Int64Constant(0)); } return test; } } // namespace Node* WasmGraphBuilder::BuildIntConvertFloat(Node* input, wasm::WasmCodePosition position, wasm::WasmOpcode opcode) { const MachineType int_ty = IntConvertType(opcode); const MachineType float_ty = FloatConvertType(opcode); const Operator* conv_op = ConvertOp(this, opcode); Node* trunc = nullptr; Node* converted_value = nullptr; const bool is_int32 = int_ty.representation() == MachineRepresentation::kWord32; if (is_int32) { trunc = Unop(TruncOp(float_ty), input); converted_value = graph()->NewNode(conv_op, trunc); } else { trunc = graph()->NewNode(conv_op, input); converted_value = graph()->NewNode(mcgraph()->common()->Projection(0), trunc, graph()->start()); } if (IsTrappingConvertOp(opcode)) { Node* test = ConvertTrapTest(this, opcode, int_ty, float_ty, trunc, converted_value); if (is_int32) { TrapIfTrue(wasm::kTrapFloatUnrepresentable, test, position); } else { ZeroCheck64(wasm::kTrapFloatUnrepresentable, test, position); } return converted_value; } Node* test = ConvertSaturateTest(this, opcode, int_ty, float_ty, trunc, converted_value); Diamond tl_d(graph(), mcgraph()->common(), test, BranchHint::kFalse); tl_d.Chain(Control()); Node* nan_test = Binop(NeOp(float_ty), input, input); Diamond nan_d(graph(), mcgraph()->common(), nan_test, BranchHint::kFalse); nan_d.Nest(tl_d, true); Node* neg_test = Binop(LtOp(float_ty), input, Zero(this, float_ty)); Diamond sat_d(graph(), mcgraph()->common(), neg_test, BranchHint::kNone); sat_d.Nest(nan_d, false); Node* sat_val = sat_d.Phi(int_ty.representation(), Min(this, int_ty), Max(this, int_ty)); Node* nan_val = nan_d.Phi(int_ty.representation(), Zero(this, int_ty), sat_val); return tl_d.Phi(int_ty.representation(), nan_val, converted_value); } Node* WasmGraphBuilder::BuildI32AsmjsSConvertF32(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. input = graph()->NewNode(m->ChangeFloat32ToFloat64(), input); return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildI32AsmjsSConvertF64(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildI32AsmjsUConvertF32(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. input = graph()->NewNode(m->ChangeFloat32ToFloat64(), input); return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildI32AsmjsUConvertF64(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildBitCountingCall(Node* input, ExternalReference ref, MachineRepresentation input_type) { Node* stack_slot_param = graph()->NewNode(mcgraph()->machine()->StackSlot(input_type)); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(input_type, kNoWriteBarrier)); SetEffect(graph()->NewNode(store_op, stack_slot_param, mcgraph()->Int32Constant(0), input, Effect(), Control())); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); return BuildCCall(&sig, function, stack_slot_param); } Node* WasmGraphBuilder::BuildI32Ctz(Node* input) { return BuildBitCountingCall(input, ExternalReference::wasm_word32_ctz(), MachineRepresentation::kWord32); } Node* WasmGraphBuilder::BuildI64Ctz(Node* input) { return Unop(wasm::kExprI64UConvertI32, BuildBitCountingCall(input, ExternalReference::wasm_word64_ctz(), MachineRepresentation::kWord64)); } Node* WasmGraphBuilder::BuildI32Popcnt(Node* input) { return BuildBitCountingCall(input, ExternalReference::wasm_word32_popcnt(), MachineRepresentation::kWord32); } Node* WasmGraphBuilder::BuildI64Popcnt(Node* input) { return Unop( wasm::kExprI64UConvertI32, BuildBitCountingCall(input, ExternalReference::wasm_word64_popcnt(), MachineRepresentation::kWord64)); } Node* WasmGraphBuilder::BuildF32Trunc(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_trunc(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32Floor(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_floor(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32Ceil(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_ceil(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32NearestInt(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_nearest_int(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Trunc(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_trunc(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Floor(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_floor(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Ceil(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_ceil(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64NearestInt(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_nearest_int(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Acos(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::f64_acos_wrapper_function(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Asin(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::f64_asin_wrapper_function(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Pow(Node* left, Node* right) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_float64_pow(); return BuildCFuncInstruction(ref, type, left, right); } Node* WasmGraphBuilder::BuildF64Mod(Node* left, Node* right) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::f64_mod_wrapper_function(); return BuildCFuncInstruction(ref, type, left, right); } Node* WasmGraphBuilder::BuildCFuncInstruction(ExternalReference ref, MachineType type, Node* input0, Node* input1) { // We do truncation by calling a C function which calculates the result. // The input is passed to the C function as a byte buffer holding the two // input doubles. We reserve this byte buffer as a stack slot, store the // parameters in this buffer slots, pass a pointer to the buffer to the C // function, and after calling the C function we collect the return value from // the buffer. const int type_size = ElementSizeInBytes(type.representation()); const int stack_slot_bytes = (input1 == nullptr ? 1 : 2) * type_size; Node* stack_slot = graph()->NewNode(mcgraph()->machine()->StackSlot(stack_slot_bytes)); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(type.representation(), kNoWriteBarrier)); SetEffect(graph()->NewNode(store_op, stack_slot, mcgraph()->Int32Constant(0), input0, Effect(), Control())); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); if (input1 != nullptr) { SetEffect(graph()->NewNode(store_op, stack_slot, mcgraph()->Int32Constant(type_size), input1, Effect(), Control())); } MachineType sig_types[] = {MachineType::Pointer()}; MachineSignature sig(0, 1, sig_types); BuildCCall(&sig, function, stack_slot); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(type), stack_slot, mcgraph()->Int32Constant(0), Effect(), Control())); } Node* WasmGraphBuilder::BuildF32SConvertI64(Node* input) { // TODO(titzer/bradnelson): Check handlng of asm.js case. return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_int64_to_float32(), MachineRepresentation::kWord64, MachineType::Float32()); } Node* WasmGraphBuilder::BuildF32UConvertI64(Node* input) { // TODO(titzer/bradnelson): Check handlng of asm.js case. return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_uint64_to_float32(), MachineRepresentation::kWord64, MachineType::Float32()); } Node* WasmGraphBuilder::BuildF64SConvertI64(Node* input) { return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_int64_to_float64(), MachineRepresentation::kWord64, MachineType::Float64()); } Node* WasmGraphBuilder::BuildF64UConvertI64(Node* input) { return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_uint64_to_float64(), MachineRepresentation::kWord64, MachineType::Float64()); } Node* WasmGraphBuilder::BuildIntToFloatConversionInstruction( Node* input, ExternalReference ref, MachineRepresentation parameter_representation, const MachineType result_type) { int stack_slot_size = std::max(ElementSizeInBytes(parameter_representation), ElementSizeInBytes(result_type.representation())); Node* stack_slot = graph()->NewNode(mcgraph()->machine()->StackSlot(stack_slot_size)); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(parameter_representation, kNoWriteBarrier)); SetEffect(graph()->NewNode(store_op, stack_slot, mcgraph()->Int32Constant(0), input, Effect(), Control())); MachineType sig_types[] = {MachineType::Pointer()}; MachineSignature sig(0, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); BuildCCall(&sig, function, stack_slot); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(result_type), stack_slot, mcgraph()->Int32Constant(0), Effect(), Control())); } namespace { ExternalReference convert_ccall_ref(WasmGraphBuilder* builder, wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI64SConvertF32: case wasm::kExprI64SConvertSatF32: return ExternalReference::wasm_float32_to_int64(); case wasm::kExprI64UConvertF32: case wasm::kExprI64UConvertSatF32: return ExternalReference::wasm_float32_to_uint64(); case wasm::kExprI64SConvertF64: case wasm::kExprI64SConvertSatF64: return ExternalReference::wasm_float64_to_int64(); case wasm::kExprI64UConvertF64: case wasm::kExprI64UConvertSatF64: return ExternalReference::wasm_float64_to_uint64(); default: UNREACHABLE(); } } } // namespace Node* WasmGraphBuilder::BuildCcallConvertFloat(Node* input, wasm::WasmCodePosition position, wasm::WasmOpcode opcode) { const MachineType int_ty = IntConvertType(opcode); const MachineType float_ty = FloatConvertType(opcode); ExternalReference call_ref = convert_ccall_ref(this, opcode); int stack_slot_size = std::max(ElementSizeInBytes(int_ty.representation()), ElementSizeInBytes(float_ty.representation())); Node* stack_slot = graph()->NewNode(mcgraph()->machine()->StackSlot(stack_slot_size)); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(float_ty.representation(), kNoWriteBarrier)); SetEffect(graph()->NewNode(store_op, stack_slot, Int32Constant(0), input, Effect(), Control())); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(call_ref)); Node* overflow = BuildCCall(&sig, function, stack_slot); if (IsTrappingConvertOp(opcode)) { ZeroCheck32(wasm::kTrapFloatUnrepresentable, overflow, position); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(int_ty), stack_slot, Int32Constant(0), Effect(), Control())); } Node* test = Binop(wasm::kExprI32Eq, overflow, Int32Constant(0), position); Diamond tl_d(graph(), mcgraph()->common(), test, BranchHint::kFalse); tl_d.Chain(Control()); Node* nan_test = Binop(NeOp(float_ty), input, input); Diamond nan_d(graph(), mcgraph()->common(), nan_test, BranchHint::kFalse); nan_d.Nest(tl_d, true); Node* neg_test = Binop(LtOp(float_ty), input, Zero(this, float_ty)); Diamond sat_d(graph(), mcgraph()->common(), neg_test, BranchHint::kNone); sat_d.Nest(nan_d, false); Node* sat_val = sat_d.Phi(int_ty.representation(), Min(this, int_ty), Max(this, int_ty)); Node* load = SetEffect(graph()->NewNode(mcgraph()->machine()->Load(int_ty), stack_slot, Int32Constant(0), Effect(), Control())); Node* nan_val = nan_d.Phi(int_ty.representation(), Zero(this, int_ty), sat_val); return tl_d.Phi(int_ty.representation(), nan_val, load); } Node* WasmGraphBuilder::MemoryGrow(Node* input) { needs_stack_check_ = true; WasmMemoryGrowDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), // zone interface_descriptor, // descriptor interface_descriptor.GetStackParameterCount(), // stack parameter count CallDescriptor::kNoFlags, // flags Operator::kNoProperties, // properties StubCallMode::kCallWasmRuntimeStub); // stub call mode // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmMemoryGrow, RelocInfo::WASM_STUB_CALL); return SetEffect( SetControl(graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, input, Effect(), Control()))); } #ifdef DEBUG namespace { constexpr uint32_t kBytesPerExceptionValuesArrayElement = 2; size_t ComputeEncodedElementSize(wasm::ValueType type) { size_t byte_size = static_cast<size_t>(wasm::ValueTypes::ElementSizeInBytes(type)); DCHECK_EQ(byte_size % kBytesPerExceptionValuesArrayElement, 0); DCHECK_LE(1, byte_size / kBytesPerExceptionValuesArrayElement); return byte_size / kBytesPerExceptionValuesArrayElement; } } // namespace #endif // DEBUG uint32_t WasmGraphBuilder::GetExceptionEncodedSize( const wasm::WasmException* exception) const { const wasm::WasmExceptionSig* sig = exception->sig; uint32_t encoded_size = 0; for (size_t i = 0; i < sig->parameter_count(); ++i) { switch (sig->GetParam(i)) { case wasm::kWasmI32: case wasm::kWasmF32: DCHECK_EQ(2, ComputeEncodedElementSize(sig->GetParam(i))); encoded_size += 2; break; case wasm::kWasmI64: case wasm::kWasmF64: DCHECK_EQ(4, ComputeEncodedElementSize(sig->GetParam(i))); encoded_size += 4; break; case wasm::kWasmS128: DCHECK_EQ(8, ComputeEncodedElementSize(sig->GetParam(i))); encoded_size += 8; break; case wasm::kWasmAnyRef: encoded_size += 1; break; default: UNREACHABLE(); } } return encoded_size; } Node* WasmGraphBuilder::Throw(uint32_t exception_index, const wasm::WasmException* exception, const Vector<Node*> values) { needs_stack_check_ = true; uint32_t encoded_size = GetExceptionEncodedSize(exception); Node* create_parameters[] = { LoadExceptionTagFromTable(exception_index), BuildChangeUint31ToSmi(Uint32Constant(encoded_size))}; Node* except_obj = BuildCallToRuntime(Runtime::kWasmThrowCreate, create_parameters, arraysize(create_parameters)); Node* values_array = BuildCallToRuntime(Runtime::kWasmExceptionGetValues, &except_obj, 1); uint32_t index = 0; const wasm::WasmExceptionSig* sig = exception->sig; MachineOperatorBuilder* m = mcgraph()->machine(); for (size_t i = 0; i < sig->parameter_count(); ++i) { Node* value = values[i]; switch (sig->GetParam(i)) { case wasm::kWasmF32: value = graph()->NewNode(m->BitcastFloat32ToInt32(), value); V8_FALLTHROUGH; case wasm::kWasmI32: BuildEncodeException32BitValue(values_array, &index, value); break; case wasm::kWasmF64: value = graph()->NewNode(m->BitcastFloat64ToInt64(), value); V8_FALLTHROUGH; case wasm::kWasmI64: { Node* upper32 = graph()->NewNode( m->TruncateInt64ToInt32(), Binop(wasm::kExprI64ShrU, value, Int64Constant(32))); BuildEncodeException32BitValue(values_array, &index, upper32); Node* lower32 = graph()->NewNode(m->TruncateInt64ToInt32(), value); BuildEncodeException32BitValue(values_array, &index, lower32); break; } case wasm::kWasmS128: BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(0), value)); BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(1), value)); BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(2), value)); BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(3), value)); break; case wasm::kWasmAnyRef: STORE_FIXED_ARRAY_SLOT_ANY(values_array, index, value); ++index; break; default: UNREACHABLE(); } } DCHECK_EQ(encoded_size, index); WasmThrowDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmThrow, RelocInfo::WASM_STUB_CALL); return SetEffect(SetControl( graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, except_obj, Effect(), Control()))); } void WasmGraphBuilder::BuildEncodeException32BitValue(Node* values_array, uint32_t* index, Node* value) { MachineOperatorBuilder* machine = mcgraph()->machine(); Node* upper_halfword_as_smi = BuildChangeUint31ToSmi( graph()->NewNode(machine->Word32Shr(), value, Int32Constant(16))); STORE_FIXED_ARRAY_SLOT_SMI(values_array, *index, upper_halfword_as_smi); ++(*index); Node* lower_halfword_as_smi = BuildChangeUint31ToSmi( graph()->NewNode(machine->Word32And(), value, Int32Constant(0xFFFFu))); STORE_FIXED_ARRAY_SLOT_SMI(values_array, *index, lower_halfword_as_smi); ++(*index); } Node* WasmGraphBuilder::BuildDecodeException32BitValue(Node* values_array, uint32_t* index) { MachineOperatorBuilder* machine = mcgraph()->machine(); Node* upper = BuildChangeSmiToInt32(LOAD_FIXED_ARRAY_SLOT_SMI(values_array, *index)); (*index)++; upper = graph()->NewNode(machine->Word32Shl(), upper, Int32Constant(16)); Node* lower = BuildChangeSmiToInt32(LOAD_FIXED_ARRAY_SLOT_SMI(values_array, *index)); (*index)++; Node* value = graph()->NewNode(machine->Word32Or(), upper, lower); return value; } Node* WasmGraphBuilder::BuildDecodeException64BitValue(Node* values_array, uint32_t* index) { Node* upper = Binop(wasm::kExprI64Shl, Unop(wasm::kExprI64UConvertI32, BuildDecodeException32BitValue(values_array, index)), Int64Constant(32)); Node* lower = Unop(wasm::kExprI64UConvertI32, BuildDecodeException32BitValue(values_array, index)); return Binop(wasm::kExprI64Ior, upper, lower); } Node* WasmGraphBuilder::Rethrow(Node* except_obj) { needs_stack_check_ = true; WasmThrowDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmThrow, RelocInfo::WASM_STUB_CALL); return SetEffect(SetControl( graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, except_obj, Effect(), Control()))); } Node* WasmGraphBuilder::ExceptionTagEqual(Node* caught_tag, Node* expected_tag) { MachineOperatorBuilder* machine = mcgraph()->machine(); return graph()->NewNode(machine->WordEqual(), caught_tag, expected_tag); } Node* WasmGraphBuilder::LoadExceptionTagFromTable(uint32_t exception_index) { Node* exceptions_table = LOAD_INSTANCE_FIELD(ExceptionsTable, MachineType::TaggedPointer()); Node* tag = LOAD_FIXED_ARRAY_SLOT_PTR(exceptions_table, exception_index); return tag; } Node* WasmGraphBuilder::GetExceptionTag(Node* except_obj) { needs_stack_check_ = true; return BuildCallToRuntime(Runtime::kWasmExceptionGetTag, &except_obj, 1); } Node** WasmGraphBuilder::GetExceptionValues( Node* except_obj, const wasm::WasmException* exception) { Node* values_array = BuildCallToRuntime(Runtime::kWasmExceptionGetValues, &except_obj, 1); uint32_t index = 0; const wasm::WasmExceptionSig* sig = exception->sig; Node** values = Buffer(sig->parameter_count()); for (size_t i = 0; i < sig->parameter_count(); ++i) { Node* value; switch (sig->GetParam(i)) { case wasm::kWasmI32: value = BuildDecodeException32BitValue(values_array, &index); break; case wasm::kWasmI64: value = BuildDecodeException64BitValue(values_array, &index); break; case wasm::kWasmF32: { value = Unop(wasm::kExprF32ReinterpretI32, BuildDecodeException32BitValue(values_array, &index)); break; } case wasm::kWasmF64: { value = Unop(wasm::kExprF64ReinterpretI64, BuildDecodeException64BitValue(values_array, &index)); break; } case wasm::kWasmS128: value = graph()->NewNode( mcgraph()->machine()->I32x4Splat(), BuildDecodeException32BitValue(values_array, &index)); value = graph()->NewNode( mcgraph()->machine()->I32x4ReplaceLane(1), value, BuildDecodeException32BitValue(values_array, &index)); value = graph()->NewNode( mcgraph()->machine()->I32x4ReplaceLane(2), value, BuildDecodeException32BitValue(values_array, &index)); value = graph()->NewNode( mcgraph()->machine()->I32x4ReplaceLane(3), value, BuildDecodeException32BitValue(values_array, &index)); break; case wasm::kWasmAnyRef: value = LOAD_FIXED_ARRAY_SLOT_ANY(values_array, index); ++index; break; default: UNREACHABLE(); } values[i] = value; } DCHECK_EQ(index, GetExceptionEncodedSize(exception)); return values; } Node* WasmGraphBuilder::BuildI32DivS(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); ZeroCheck32(wasm::kTrapDivByZero, right, position); Node* before = Control(); Node* denom_is_m1; Node* denom_is_not_m1; BranchExpectFalse( graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(-1)), &denom_is_m1, &denom_is_not_m1); SetControl(denom_is_m1); TrapIfEq32(wasm::kTrapDivUnrepresentable, left, kMinInt, position); if (Control() != denom_is_m1) { SetControl(graph()->NewNode(mcgraph()->common()->Merge(2), denom_is_not_m1, Control())); } else { SetControl(before); } return graph()->NewNode(m->Int32Div(), left, right, Control()); } Node* WasmGraphBuilder::BuildI32RemS(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); ZeroCheck32(wasm::kTrapRemByZero, right, position); Diamond d( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(-1)), BranchHint::kFalse); d.Chain(Control()); return d.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), graph()->NewNode(m->Int32Mod(), left, right, d.if_false)); } Node* WasmGraphBuilder::BuildI32DivU(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); return graph()->NewNode(m->Uint32Div(), left, right, ZeroCheck32(wasm::kTrapDivByZero, right, position)); } Node* WasmGraphBuilder::BuildI32RemU(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); return graph()->NewNode(m->Uint32Mod(), left, right, ZeroCheck32(wasm::kTrapRemByZero, right, position)); } Node* WasmGraphBuilder::BuildI32AsmjsDivS(Node* left, Node* right) { MachineOperatorBuilder* m = mcgraph()->machine(); Int32Matcher mr(right); if (mr.HasValue()) { if (mr.Value() == 0) { return mcgraph()->Int32Constant(0); } else if (mr.Value() == -1) { // The result is the negation of the left input. return graph()->NewNode(m->Int32Sub(), mcgraph()->Int32Constant(0), left); } return graph()->NewNode(m->Int32Div(), left, right, Control()); } // asm.js semantics return 0 on divide or mod by zero. if (m->Int32DivIsSafe()) { // The hardware instruction does the right thing (e.g. arm). return graph()->NewNode(m->Int32Div(), left, right, graph()->start()); } // Check denominator for zero. Diamond z( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(0)), BranchHint::kFalse); // Check numerator for -1. (avoid minint / -1 case). Diamond n( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(-1)), BranchHint::kFalse); Node* div = graph()->NewNode(m->Int32Div(), left, right, z.if_false); Node* neg = graph()->NewNode(m->Int32Sub(), mcgraph()->Int32Constant(0), left); return n.Phi( MachineRepresentation::kWord32, neg, z.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), div)); } Node* WasmGraphBuilder::BuildI32AsmjsRemS(Node* left, Node* right) { CommonOperatorBuilder* c = mcgraph()->common(); MachineOperatorBuilder* m = mcgraph()->machine(); Node* const zero = mcgraph()->Int32Constant(0); Int32Matcher mr(right); if (mr.HasValue()) { if (mr.Value() == 0 || mr.Value() == -1) { return zero; } return graph()->NewNode(m->Int32Mod(), left, right, Control()); } // General case for signed integer modulus, with optimization for (unknown) // power of 2 right hand side. // // if 0 < right then // msk = right - 1 // if right & msk != 0 then // left % right // else // if left < 0 then // -(-left & msk) // else // left & msk // else // if right < -1 then // left % right // else // zero // // Note: We do not use the Diamond helper class here, because it really hurts // readability with nested diamonds. Node* const minus_one = mcgraph()->Int32Constant(-1); const Operator* const merge_op = c->Merge(2); const Operator* const phi_op = c->Phi(MachineRepresentation::kWord32, 2); Node* check0 = graph()->NewNode(m->Int32LessThan(), zero, right); Node* branch0 = graph()->NewNode(c->Branch(BranchHint::kTrue), check0, graph()->start()); Node* if_true0 = graph()->NewNode(c->IfTrue(), branch0); Node* true0; { Node* msk = graph()->NewNode(m->Int32Add(), right, minus_one); Node* check1 = graph()->NewNode(m->Word32And(), right, msk); Node* branch1 = graph()->NewNode(c->Branch(), check1, if_true0); Node* if_true1 = graph()->NewNode(c->IfTrue(), branch1); Node* true1 = graph()->NewNode(m->Int32Mod(), left, right, if_true1); Node* if_false1 = graph()->NewNode(c->IfFalse(), branch1); Node* false1; { Node* check2 = graph()->NewNode(m->Int32LessThan(), left, zero); Node* branch2 = graph()->NewNode(c->Branch(BranchHint::kFalse), check2, if_false1); Node* if_true2 = graph()->NewNode(c->IfTrue(), branch2); Node* true2 = graph()->NewNode( m->Int32Sub(), zero, graph()->NewNode(m->Word32And(), graph()->NewNode(m->Int32Sub(), zero, left), msk)); Node* if_false2 = graph()->NewNode(c->IfFalse(), branch2); Node* false2 = graph()->NewNode(m->Word32And(), left, msk); if_false1 = graph()->NewNode(merge_op, if_true2, if_false2); false1 = graph()->NewNode(phi_op, true2, false2, if_false1); } if_true0 = graph()->NewNode(merge_op, if_true1, if_false1); true0 = graph()->NewNode(phi_op, true1, false1, if_true0); } Node* if_false0 = graph()->NewNode(c->IfFalse(), branch0); Node* false0; { Node* check1 = graph()->NewNode(m->Int32LessThan(), right, minus_one); Node* branch1 = graph()->NewNode(c->Branch(BranchHint::kTrue), check1, if_false0); Node* if_true1 = graph()->NewNode(c->IfTrue(), branch1); Node* true1 = graph()->NewNode(m->Int32Mod(), left, right, if_true1); Node* if_false1 = graph()->NewNode(c->IfFalse(), branch1); Node* false1 = zero; if_false0 = graph()->NewNode(merge_op, if_true1, if_false1); false0 = graph()->NewNode(phi_op, true1, false1, if_false0); } Node* merge0 = graph()->NewNode(merge_op, if_true0, if_false0); return graph()->NewNode(phi_op, true0, false0, merge0); } Node* WasmGraphBuilder::BuildI32AsmjsDivU(Node* left, Node* right) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js semantics return 0 on divide or mod by zero. if (m->Uint32DivIsSafe()) { // The hardware instruction does the right thing (e.g. arm). return graph()->NewNode(m->Uint32Div(), left, right, graph()->start()); } // Explicit check for x % 0. Diamond z( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(0)), BranchHint::kFalse); return z.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), graph()->NewNode(mcgraph()->machine()->Uint32Div(), left, right, z.if_false)); } Node* WasmGraphBuilder::BuildI32AsmjsRemU(Node* left, Node* right) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js semantics return 0 on divide or mod by zero. // Explicit check for x % 0. Diamond z( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(0)), BranchHint::kFalse); Node* rem = graph()->NewNode(mcgraph()->machine()->Uint32Mod(), left, right, z.if_false); return z.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), rem); } Node* WasmGraphBuilder::BuildI64DivS(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_int64_div(), MachineType::Int64(), wasm::kTrapDivByZero, position); } ZeroCheck64(wasm::kTrapDivByZero, right, position); Node* before = Control(); Node* denom_is_m1; Node* denom_is_not_m1; BranchExpectFalse(graph()->NewNode(mcgraph()->machine()->Word64Equal(), right, mcgraph()->Int64Constant(-1)), &denom_is_m1, &denom_is_not_m1); SetControl(denom_is_m1); TrapIfEq64(wasm::kTrapDivUnrepresentable, left, std::numeric_limits<int64_t>::min(), position); if (Control() != denom_is_m1) { SetControl(graph()->NewNode(mcgraph()->common()->Merge(2), denom_is_not_m1, Control())); } else { SetControl(before); } return graph()->NewNode(mcgraph()->machine()->Int64Div(), left, right, Control()); } Node* WasmGraphBuilder::BuildI64RemS(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_int64_mod(), MachineType::Int64(), wasm::kTrapRemByZero, position); } ZeroCheck64(wasm::kTrapRemByZero, right, position); Diamond d(mcgraph()->graph(), mcgraph()->common(), graph()->NewNode(mcgraph()->machine()->Word64Equal(), right, mcgraph()->Int64Constant(-1))); d.Chain(Control()); Node* rem = graph()->NewNode(mcgraph()->machine()->Int64Mod(), left, right, d.if_false); return d.Phi(MachineRepresentation::kWord64, mcgraph()->Int64Constant(0), rem); } Node* WasmGraphBuilder::BuildI64DivU(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_uint64_div(), MachineType::Int64(), wasm::kTrapDivByZero, position); } return graph()->NewNode(mcgraph()->machine()->Uint64Div(), left, right, ZeroCheck64(wasm::kTrapDivByZero, right, position)); } Node* WasmGraphBuilder::BuildI64RemU(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_uint64_mod(), MachineType::Int64(), wasm::kTrapRemByZero, position); } return graph()->NewNode(mcgraph()->machine()->Uint64Mod(), left, right, ZeroCheck64(wasm::kTrapRemByZero, right, position)); } Node* WasmGraphBuilder::BuildDiv64Call(Node* left, Node* right, ExternalReference ref, MachineType result_type, wasm::TrapReason trap_zero, wasm::WasmCodePosition position) { Node* stack_slot = graph()->NewNode(mcgraph()->machine()->StackSlot(2 * sizeof(double))); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(MachineRepresentation::kWord64, kNoWriteBarrier)); SetEffect(graph()->NewNode(store_op, stack_slot, mcgraph()->Int32Constant(0), left, Effect(), Control())); SetEffect(graph()->NewNode(store_op, stack_slot, mcgraph()->Int32Constant(sizeof(double)), right, Effect(), Control())); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); Node* call = BuildCCall(&sig, function, stack_slot); ZeroCheck32(trap_zero, call, position); TrapIfEq32(wasm::kTrapDivUnrepresentable, call, -1, position); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(result_type), stack_slot, mcgraph()->Int32Constant(0), Effect(), Control())); } template <typename... Args> Node* WasmGraphBuilder::BuildCCall(MachineSignature* sig, Node* function, Args... args) { DCHECK_LE(sig->return_count(), 1); DCHECK_EQ(sizeof...(args), sig->parameter_count()); Node* const call_args[] = {function, args..., Effect(), Control()}; auto call_descriptor = Linkage::GetSimplifiedCDescriptor(mcgraph()->zone(), sig); const Operator* op = mcgraph()->common()->Call(call_descriptor); return SetEffect(graph()->NewNode(op, arraysize(call_args), call_args)); } Node* WasmGraphBuilder::BuildWasmCall(wasm::FunctionSig* sig, Node** args, Node*** rets, wasm::WasmCodePosition position, Node* instance_node, UseRetpoline use_retpoline) { if (instance_node == nullptr) { DCHECK_NOT_NULL(instance_node_); instance_node = instance_node_.get(); } needs_stack_check_ = true; const size_t params = sig->parameter_count(); const size_t extra = 3; // instance_node, effect, and control. const size_t count = 1 + params + extra; // Reallocate the buffer to make space for extra inputs. args = Realloc(args, 1 + params, count); // Make room for the instance_node parameter at index 1, just after code. memmove(&args[2], &args[1], params * sizeof(Node*)); args[1] = instance_node; // Add effect and control inputs. args[params + 2] = Effect(); args[params + 3] = Control(); auto call_descriptor = GetWasmCallDescriptor(mcgraph()->zone(), sig, use_retpoline); const Operator* op = mcgraph()->common()->Call(call_descriptor); Node* call = SetEffect(graph()->NewNode(op, static_cast<int>(count), args)); DCHECK(position == wasm::kNoCodePosition || position > 0); if (position > 0) SetSourcePosition(call, position); size_t ret_count = sig->return_count(); if (ret_count == 0) return call; // No return value. *rets = Buffer(ret_count); if (ret_count == 1) { // Only a single return value. (*rets)[0] = call; } else { // Create projections for all return values. for (size_t i = 0; i < ret_count; i++) { (*rets)[i] = graph()->NewNode(mcgraph()->common()->Projection(i), call, graph()->start()); } } return call; } Node* WasmGraphBuilder::BuildImportCall(wasm::FunctionSig* sig, Node** args, Node*** rets, wasm::WasmCodePosition position, int func_index) { // Load the imported function refs array from the instance. Node* imported_function_refs = LOAD_INSTANCE_FIELD(ImportedFunctionRefs, MachineType::TaggedPointer()); Node* ref_node = LOAD_FIXED_ARRAY_SLOT_PTR(imported_function_refs, func_index); // Load the target from the imported_targets array at a known offset. Node* imported_targets = LOAD_INSTANCE_FIELD(ImportedFunctionTargets, MachineType::Pointer()); Node* target_node = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), imported_targets, mcgraph()->Int32Constant(func_index * kSystemPointerSize), Effect(), Control())); args[0] = target_node; return BuildWasmCall(sig, args, rets, position, ref_node, untrusted_code_mitigations_ ? kRetpoline : kNoRetpoline); } Node* WasmGraphBuilder::BuildImportCall(wasm::FunctionSig* sig, Node** args, Node*** rets, wasm::WasmCodePosition position, Node* func_index) { // Load the imported function refs array from the instance. Node* imported_function_refs = LOAD_INSTANCE_FIELD(ImportedFunctionRefs, MachineType::TaggedPointer()); // Access fixed array at {header_size - tag + func_index * kTaggedSize}. Node* imported_instances_data = graph()->NewNode( mcgraph()->machine()->IntAdd(), imported_function_refs, mcgraph()->IntPtrConstant( wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0))); Node* func_index_times_tagged_size = graph()->NewNode( mcgraph()->machine()->IntMul(), Uint32ToUintptr(func_index), mcgraph()->Int32Constant(kTaggedSize)); Node* ref_node = SetEffect( graph()->NewNode(mcgraph()->machine()->Load(MachineType::TaggedPointer()), imported_instances_data, func_index_times_tagged_size, Effect(), Control())); // Load the target from the imported_targets array at the offset of // {func_index}. STATIC_ASSERT(kTaggedSize == kSystemPointerSize); Node* func_index_times_pointersize = func_index_times_tagged_size; Node* imported_targets = LOAD_INSTANCE_FIELD(ImportedFunctionTargets, MachineType::Pointer()); Node* target_node = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), imported_targets, func_index_times_pointersize, Effect(), Control())); args[0] = target_node; return BuildWasmCall(sig, args, rets, position, ref_node, untrusted_code_mitigations_ ? kRetpoline : kNoRetpoline); } Node* WasmGraphBuilder::CallDirect(uint32_t index, Node** args, Node*** rets, wasm::WasmCodePosition position) { DCHECK_NULL(args[0]); wasm::FunctionSig* sig = env_->module->functions[index].sig; if (env_ && index < env_->module->num_imported_functions) { // Call to an imported function. return BuildImportCall(sig, args, rets, position, index); } // A direct call to a wasm function defined in this module. // Just encode the function index. This will be patched at instantiation. Address code = static_cast<Address>(index); args[0] = mcgraph()->RelocatableIntPtrConstant(code, RelocInfo::WASM_CALL); return BuildWasmCall(sig, args, rets, position, nullptr, kNoRetpoline); } Node* WasmGraphBuilder::CallIndirect(uint32_t sig_index, Node** args, Node*** rets, wasm::WasmCodePosition position) { DCHECK_NOT_NULL(args[0]); DCHECK_NOT_NULL(env_); // Assume only one table for now. wasm::FunctionSig* sig = env_->module->signatures[sig_index]; Node* ift_size = LOAD_INSTANCE_FIELD(IndirectFunctionTableSize, MachineType::Uint32()); MachineOperatorBuilder* machine = mcgraph()->machine(); Node* key = args[0]; // Bounds check against the table size. Node* in_bounds = graph()->NewNode(machine->Uint32LessThan(), key, ift_size); TrapIfFalse(wasm::kTrapFuncInvalid, in_bounds, position); // Mask the key to prevent SSCA. if (untrusted_code_mitigations_) { // mask = ((key - size) & ~key) >> 31 Node* neg_key = graph()->NewNode(machine->Word32Xor(), key, Int32Constant(-1)); Node* masked_diff = graph()->NewNode( machine->Word32And(), graph()->NewNode(machine->Int32Sub(), key, ift_size), neg_key); Node* mask = graph()->NewNode(machine->Word32Sar(), masked_diff, Int32Constant(31)); key = graph()->NewNode(machine->Word32And(), key, mask); } // Load signature from the table and check. Node* ift_sig_ids = LOAD_INSTANCE_FIELD(IndirectFunctionTableSigIds, MachineType::Pointer()); int32_t expected_sig_id = env_->module->signature_ids[sig_index]; Node* int32_scaled_key = Uint32ToUintptr( graph()->NewNode(machine->Word32Shl(), key, Int32Constant(2))); Node* loaded_sig = SetEffect( graph()->NewNode(machine->Load(MachineType::Int32()), ift_sig_ids, int32_scaled_key, Effect(), Control())); Node* sig_match = graph()->NewNode(machine->WordEqual(), loaded_sig, Int32Constant(expected_sig_id)); TrapIfFalse(wasm::kTrapFuncSigMismatch, sig_match, position); Node* ift_targets = LOAD_INSTANCE_FIELD(IndirectFunctionTableTargets, MachineType::Pointer()); Node* ift_instances = LOAD_INSTANCE_FIELD(IndirectFunctionTableRefs, MachineType::TaggedPointer()); Node* intptr_scaled_key = graph()->NewNode( machine->Word32Shl(), key, Int32Constant(kSystemPointerSizeLog2)); Node* target = SetEffect( graph()->NewNode(machine->Load(MachineType::Pointer()), ift_targets, intptr_scaled_key, Effect(), Control())); STATIC_ASSERT(kTaggedSize == kSystemPointerSize); Node* tagged_scaled_key = intptr_scaled_key; Node* target_instance = SetEffect(graph()->NewNode( machine->Load(MachineType::TaggedPointer()), graph()->NewNode(machine->IntAdd(), ift_instances, tagged_scaled_key), Int32Constant(wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0)), Effect(), Control())); args[0] = target; return BuildWasmCall(sig, args, rets, position, target_instance, untrusted_code_mitigations_ ? kRetpoline : kNoRetpoline); } Node* WasmGraphBuilder::BuildI32Rol(Node* left, Node* right) { // Implement Rol by Ror since TurboFan does not have Rol opcode. // TODO(weiliang): support Word32Rol opcode in TurboFan. Int32Matcher m(right); if (m.HasValue()) { return Binop(wasm::kExprI32Ror, left, mcgraph()->Int32Constant(32 - (m.Value() & 0x1F))); } else { return Binop(wasm::kExprI32Ror, left, Binop(wasm::kExprI32Sub, mcgraph()->Int32Constant(32), right)); } } Node* WasmGraphBuilder::BuildI64Rol(Node* left, Node* right) { // Implement Rol by Ror since TurboFan does not have Rol opcode. // TODO(weiliang): support Word64Rol opcode in TurboFan. Int64Matcher m(right); if (m.HasValue()) { return Binop(wasm::kExprI64Ror, left, mcgraph()->Int64Constant(64 - (m.Value() & 0x3F))); } else { return Binop(wasm::kExprI64Ror, left, Binop(wasm::kExprI64Sub, mcgraph()->Int64Constant(64), right)); } } Node* WasmGraphBuilder::Invert(Node* node) { return Unop(wasm::kExprI32Eqz, node); } bool CanCover(Node* value, IrOpcode::Value opcode) { if (value->opcode() != opcode) return false; bool first = true; for (Edge const edge : value->use_edges()) { if (NodeProperties::IsControlEdge(edge)) continue; if (NodeProperties::IsEffectEdge(edge)) continue; DCHECK(NodeProperties::IsValueEdge(edge)); if (!first) return false; first = false; } return true; } Node* WasmGraphBuilder::BuildChangeInt32ToIntPtr(Node* value) { if (mcgraph()->machine()->Is64()) { value = graph()->NewNode(mcgraph()->machine()->ChangeInt32ToInt64(), value); } return value; } Node* WasmGraphBuilder::BuildChangeInt32ToSmi(Node* value) { value = BuildChangeInt32ToIntPtr(value); return graph()->NewNode(mcgraph()->machine()->WordShl(), value, BuildSmiShiftBitsConstant()); } Node* WasmGraphBuilder::BuildChangeUint31ToSmi(Node* value) { return graph()->NewNode(mcgraph()->machine()->WordShl(), Uint32ToUintptr(value), BuildSmiShiftBitsConstant()); } Node* WasmGraphBuilder::BuildSmiShiftBitsConstant() { return mcgraph()->IntPtrConstant(kSmiShiftSize + kSmiTagSize); } Node* WasmGraphBuilder::BuildChangeSmiToInt32(Node* value) { value = graph()->NewNode(mcgraph()->machine()->WordSar(), value, BuildSmiShiftBitsConstant()); if (mcgraph()->machine()->Is64()) { value = graph()->NewNode(mcgraph()->machine()->TruncateInt64ToInt32(), value); } return value; } void WasmGraphBuilder::InitInstanceCache( WasmInstanceCacheNodes* instance_cache) { DCHECK_NOT_NULL(instance_node_); // Load the memory start. instance_cache->mem_start = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), instance_node_.get(), mcgraph()->Int32Constant(WASM_INSTANCE_OBJECT_OFFSET(MemoryStart)), Effect(), Control())); // Load the memory size. instance_cache->mem_size = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), instance_node_.get(), mcgraph()->Int32Constant(WASM_INSTANCE_OBJECT_OFFSET(MemorySize)), Effect(), Control())); if (untrusted_code_mitigations_) { // Load the memory mask. instance_cache->mem_mask = LOAD_INSTANCE_FIELD(MemoryMask, MachineType::UintPtr()); } else { // Explicitly set to nullptr to ensure a SEGV when we try to use it. instance_cache->mem_mask = nullptr; } } void WasmGraphBuilder::PrepareInstanceCacheForLoop( WasmInstanceCacheNodes* instance_cache, Node* control) { #define INTRODUCE_PHI(field, rep) \ instance_cache->field = graph()->NewNode(mcgraph()->common()->Phi(rep, 1), \ instance_cache->field, control); INTRODUCE_PHI(mem_start, MachineType::PointerRepresentation()); INTRODUCE_PHI(mem_size, MachineType::PointerRepresentation()); if (untrusted_code_mitigations_) { INTRODUCE_PHI(mem_mask, MachineType::PointerRepresentation()); } #undef INTRODUCE_PHI } void WasmGraphBuilder::NewInstanceCacheMerge(WasmInstanceCacheNodes* to, WasmInstanceCacheNodes* from, Node* merge) { #define INTRODUCE_PHI(field, rep) \ if (to->field != from->field) { \ Node* vals[] = {to->field, from->field, merge}; \ to->field = graph()->NewNode(mcgraph()->common()->Phi(rep, 2), 3, vals); \ } INTRODUCE_PHI(mem_start, MachineType::PointerRepresentation()); INTRODUCE_PHI(mem_size, MachineRepresentation::kWord32); if (untrusted_code_mitigations_) { INTRODUCE_PHI(mem_mask, MachineRepresentation::kWord32); } #undef INTRODUCE_PHI } void WasmGraphBuilder::MergeInstanceCacheInto(WasmInstanceCacheNodes* to, WasmInstanceCacheNodes* from, Node* merge) { to->mem_size = CreateOrMergeIntoPhi(MachineType::PointerRepresentation(), merge, to->mem_size, from->mem_size); to->mem_start = CreateOrMergeIntoPhi(MachineType::PointerRepresentation(), merge, to->mem_start, from->mem_start); if (untrusted_code_mitigations_) { to->mem_mask = CreateOrMergeIntoPhi(MachineType::PointerRepresentation(), merge, to->mem_mask, from->mem_mask); } } Node* WasmGraphBuilder::CreateOrMergeIntoPhi(MachineRepresentation rep, Node* merge, Node* tnode, Node* fnode) { if (IsPhiWithMerge(tnode, merge)) { AppendToPhi(tnode, fnode); } else if (tnode != fnode) { uint32_t count = merge->InputCount(); // + 1 for the merge node. Node** vals = Buffer(count + 1); for (uint32_t j = 0; j < count - 1; j++) vals[j] = tnode; vals[count - 1] = fnode; vals[count] = merge; return graph()->NewNode(mcgraph()->common()->Phi(rep, count), count + 1, vals); } return tnode; } Node* WasmGraphBuilder::CreateOrMergeIntoEffectPhi(Node* merge, Node* tnode, Node* fnode) { if (IsPhiWithMerge(tnode, merge)) { AppendToPhi(tnode, fnode); } else if (tnode != fnode) { uint32_t count = merge->InputCount(); Node** effects = Buffer(count); for (uint32_t j = 0; j < count - 1; j++) { effects[j] = tnode; } effects[count - 1] = fnode; tnode = EffectPhi(count, effects, merge); } return tnode; } Node* WasmGraphBuilder::GetImportedMutableGlobals() { if (imported_mutable_globals_ == nullptr) { // Load imported_mutable_globals_ from the instance object at runtime. imported_mutable_globals_ = graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), instance_node_.get(), mcgraph()->Int32Constant( WASM_INSTANCE_OBJECT_OFFSET(ImportedMutableGlobals)), graph()->start(), graph()->start()); } return imported_mutable_globals_.get(); } void WasmGraphBuilder::GetGlobalBaseAndOffset(MachineType mem_type, const wasm::WasmGlobal& global, Node** base_node, Node** offset_node) { DCHECK_NOT_NULL(instance_node_); if (global.mutability && global.imported) { *base_node = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), GetImportedMutableGlobals(), mcgraph()->Int32Constant(global.index * sizeof(Address)), Effect(), Control())); *offset_node = mcgraph()->Int32Constant(0); } else { if (globals_start_ == nullptr) { // Load globals_start from the instance object at runtime. // TODO(wasm): we currently generate only one load of the {globals_start} // start per graph, which means it can be placed anywhere by the // scheduler. This is legal because the globals_start should never change. // However, in some cases (e.g. if the instance object is already in a // register), it is slightly more efficient to reload this value from the // instance object. Since this depends on register allocation, it is not // possible to express in the graph, and would essentially constitute a // "mem2reg" optimization in TurboFan. globals_start_ = graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), instance_node_.get(), mcgraph()->Int32Constant(WASM_INSTANCE_OBJECT_OFFSET(GlobalsStart)), graph()->start(), graph()->start()); } *base_node = globals_start_.get(); *offset_node = mcgraph()->Int32Constant(global.offset); if (mem_type == MachineType::Simd128() && global.offset != 0) { // TODO(titzer,bbudge): code generation for SIMD memory offsets is broken. *base_node = graph()->NewNode(mcgraph()->machine()->IntAdd(), *base_node, *offset_node); *offset_node = mcgraph()->Int32Constant(0); } } } void WasmGraphBuilder::GetBaseAndOffsetForImportedMutableAnyRefGlobal( const wasm::WasmGlobal& global, Node** base, Node** offset) { // Load the base from the ImportedMutableGlobalsBuffer of the instance. Node* buffers = LOAD_INSTANCE_FIELD(ImportedMutableGlobalsBuffers, MachineType::TaggedPointer()); *base = LOAD_FIXED_ARRAY_SLOT_ANY(buffers, global.index); // For the offset we need the index of the global in the buffer, and then // calculate the actual offset from the index. Load the index from the // ImportedMutableGlobals array of the instance. Node* index = SetEffect( graph()->NewNode(mcgraph()->machine()->Load(MachineType::UintPtr()), GetImportedMutableGlobals(), mcgraph()->Int32Constant(global.index * sizeof(Address)), Effect(), Control())); // From the index, calculate the actual offset in the FixeArray. This // is kHeaderSize + (index * kTaggedSize). kHeaderSize can be acquired with // wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0). Node* index_times_tagged_size = graph()->NewNode(mcgraph()->machine()->IntMul(), Uint32ToUintptr(index), mcgraph()->Int32Constant(kTaggedSize)); *offset = graph()->NewNode( mcgraph()->machine()->IntAdd(), index_times_tagged_size, mcgraph()->IntPtrConstant( wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0))); } Node* WasmGraphBuilder::MemBuffer(uint32_t offset) { DCHECK_NOT_NULL(instance_cache_); Node* mem_start = instance_cache_->mem_start; DCHECK_NOT_NULL(mem_start); if (offset == 0) return mem_start; return graph()->NewNode(mcgraph()->machine()->IntAdd(), mem_start, mcgraph()->IntPtrConstant(offset)); } Node* WasmGraphBuilder::CurrentMemoryPages() { // CurrentMemoryPages can not be called from asm.js. DCHECK_EQ(wasm::kWasmOrigin, env_->module->origin); DCHECK_NOT_NULL(instance_cache_); Node* mem_size = instance_cache_->mem_size; DCHECK_NOT_NULL(mem_size); Node* result = graph()->NewNode(mcgraph()->machine()->WordShr(), mem_size, mcgraph()->Int32Constant(wasm::kWasmPageSizeLog2)); if (mcgraph()->machine()->Is64()) { result = graph()->NewNode(mcgraph()->machine()->TruncateInt64ToInt32(), result); } return result; } Node* WasmGraphBuilder::BuildLoadBuiltinFromInstance(int builtin_index) { DCHECK(Builtins::IsBuiltinId(builtin_index)); Node* isolate_root = LOAD_INSTANCE_FIELD(IsolateRoot, MachineType::Pointer()); return LOAD_TAGGED_POINTER(isolate_root, IsolateData::builtin_slot_offset(builtin_index)); } // Only call this function for code which is not reused across instantiations, // as we do not patch the embedded js_context. Node* WasmGraphBuilder::BuildCallToRuntimeWithContext( Runtime::FunctionId f, Node* js_context, Node** parameters, int parameter_count, Node** effect, Node* control) { const Runtime::Function* fun = Runtime::FunctionForId(f); auto call_descriptor = Linkage::GetRuntimeCallDescriptor( mcgraph()->zone(), f, fun->nargs, Operator::kNoProperties, CallDescriptor::kNoFlags); // The CEntryStub is loaded from the instance_node so that generated code is // Isolate independent. At the moment this is only done for CEntryStub(1). DCHECK_EQ(1, fun->result_size); Node* centry_stub = LOAD_INSTANCE_FIELD(CEntryStub, MachineType::TaggedPointer()); // TODO(titzer): allow arbitrary number of runtime arguments // At the moment we only allow 5 parameters. If more parameters are needed, // increase this constant accordingly. static const int kMaxParams = 5; DCHECK_GE(kMaxParams, parameter_count); Node* inputs[kMaxParams + 6]; int count = 0; inputs[count++] = centry_stub; for (int i = 0; i < parameter_count; i++) { inputs[count++] = parameters[i]; } inputs[count++] = mcgraph()->ExternalConstant(ExternalReference::Create(f)); // ref inputs[count++] = mcgraph()->Int32Constant(fun->nargs); // arity inputs[count++] = js_context; // js_context inputs[count++] = *effect; inputs[count++] = control; Node* call = mcgraph()->graph()->NewNode( mcgraph()->common()->Call(call_descriptor), count, inputs); *effect = call; return call; } Node* WasmGraphBuilder::BuildCallToRuntime(Runtime::FunctionId f, Node** parameters, int parameter_count) { return BuildCallToRuntimeWithContext(f, NoContextConstant(), parameters, parameter_count, effect_, Control()); } Node* WasmGraphBuilder::GetGlobal(uint32_t index) { const wasm::WasmGlobal& global = env_->module->globals[index]; if (global.type == wasm::ValueType::kWasmAnyRef) { if (global.mutability && global.imported) { Node* base = nullptr; Node* offset = nullptr; GetBaseAndOffsetForImportedMutableAnyRefGlobal(global, &base, &offset); return SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::TaggedPointer()), base, offset, Effect(), Control())); } Node* globals_buffer = LOAD_INSTANCE_FIELD(TaggedGlobalsBuffer, MachineType::TaggedPointer()); return LOAD_FIXED_ARRAY_SLOT_ANY(globals_buffer, global.offset); } MachineType mem_type = wasm::ValueTypes::MachineTypeFor(env_->module->globals[index].type); Node* base = nullptr; Node* offset = nullptr; GetGlobalBaseAndOffset(mem_type, env_->module->globals[index], &base, &offset); Node* result = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(mem_type), base, offset, Effect(), Control())); #if defined(V8_TARGET_BIG_ENDIAN) result = BuildChangeEndiannessLoad(result, mem_type, env_->module->globals[index].type); #endif return result; } Node* WasmGraphBuilder::SetGlobal(uint32_t index, Node* val) { const wasm::WasmGlobal& global = env_->module->globals[index]; if (global.type == wasm::ValueType::kWasmAnyRef) { if (global.mutability && global.imported) { Node* base = nullptr; Node* offset = nullptr; GetBaseAndOffsetForImportedMutableAnyRefGlobal(global, &base, &offset); return SetEffect(graph()->NewNode( mcgraph()->machine()->Store(StoreRepresentation( MachineRepresentation::kTagged, kFullWriteBarrier)), base, offset, val, Effect(), Control())); } Node* globals_buffer = LOAD_INSTANCE_FIELD(TaggedGlobalsBuffer, MachineType::TaggedPointer()); return STORE_FIXED_ARRAY_SLOT_ANY(globals_buffer, env_->module->globals[index].offset, val); } MachineType mem_type = wasm::ValueTypes::MachineTypeFor(env_->module->globals[index].type); Node* base = nullptr; Node* offset = nullptr; GetGlobalBaseAndOffset(mem_type, env_->module->globals[index], &base, &offset); const Operator* op = mcgraph()->machine()->Store( StoreRepresentation(mem_type.representation(), kNoWriteBarrier)); #if defined(V8_TARGET_BIG_ENDIAN) val = BuildChangeEndiannessStore(val, mem_type.representation(), env_->module->globals[index].type); #endif return SetEffect( graph()->NewNode(op, base, offset, val, Effect(), Control())); } Node* WasmGraphBuilder::CheckBoundsAndAlignment( uint8_t access_size, Node* index, uint32_t offset, wasm::WasmCodePosition position) { // Atomic operations need bounds checks until the backend can emit protected // loads. index = BoundsCheckMem(access_size, index, offset, position, kNeedsBoundsCheck); const uintptr_t align_mask = access_size - 1; // Don't emit an alignment check if the index is a constant. // TODO(wasm): a constant match is also done above in {BoundsCheckMem}. UintPtrMatcher match(index); if (match.HasValue()) { uintptr_t effective_offset = match.Value() + offset; if ((effective_offset & align_mask) != 0) { // statically known to be unaligned; trap. TrapIfEq32(wasm::kTrapUnalignedAccess, Int32Constant(0), 0, position); } return index; } // Unlike regular memory accesses, atomic memory accesses should trap if // the effective offset is misaligned. // TODO(wasm): this addition is redundant with one inserted by {MemBuffer}. Node* effective_offset = graph()->NewNode(mcgraph()->machine()->IntAdd(), MemBuffer(offset), index); Node* cond = graph()->NewNode(mcgraph()->machine()->WordAnd(), effective_offset, IntPtrConstant(align_mask)); TrapIfFalse(wasm::kTrapUnalignedAccess, graph()->NewNode(mcgraph()->machine()->Word32Equal(), cond, mcgraph()->Int32Constant(0)), position); return index; } // Insert code to bounds check a memory access if necessary. Return the // bounds-checked index, which is guaranteed to have (the equivalent of) // {uintptr_t} representation. Node* WasmGraphBuilder::BoundsCheckMem(uint8_t access_size, Node* index, uint32_t offset, wasm::WasmCodePosition position, EnforceBoundsCheck enforce_check) { DCHECK_LE(1, access_size); index = Uint32ToUintptr(index); if (FLAG_wasm_no_bounds_checks) return index; if (use_trap_handler() && enforce_check == kCanOmitBoundsCheck) { return index; } const bool statically_oob = access_size > env_->max_memory_size || offset > env_->max_memory_size - access_size; if (statically_oob) { // The access will be out of bounds, even for the largest memory. TrapIfEq32(wasm::kTrapMemOutOfBounds, Int32Constant(0), 0, position); return mcgraph()->IntPtrConstant(0); } uint64_t end_offset = uint64_t{offset} + access_size - 1u; Node* end_offset_node = IntPtrConstant(end_offset); // The accessed memory is [index + offset, index + end_offset]. // Check that the last read byte (at {index + end_offset}) is in bounds. // 1) Check that {end_offset < mem_size}. This also ensures that we can safely // compute {effective_size} as {mem_size - end_offset)}. // {effective_size} is >= 1 if condition 1) holds. // 2) Check that {index + end_offset < mem_size} by // - computing {effective_size} as {mem_size - end_offset} and // - checking that {index < effective_size}. auto m = mcgraph()->machine(); Node* mem_size = instance_cache_->mem_size; if (end_offset >= env_->min_memory_size) { // The end offset is larger than the smallest memory. // Dynamically check the end offset against the dynamic memory size. Node* cond = graph()->NewNode(m->UintLessThan(), end_offset_node, mem_size); TrapIfFalse(wasm::kTrapMemOutOfBounds, cond, position); } else { // The end offset is smaller than the smallest memory, so only one check is // required. Check to see if the index is also a constant. UintPtrMatcher match(index); if (match.HasValue()) { uintptr_t index_val = match.Value(); if (index_val < env_->min_memory_size - end_offset) { // The input index is a constant and everything is statically within // bounds of the smallest possible memory. return index; } } } // This produces a positive number, since {end_offset < min_size <= mem_size}. Node* effective_size = graph()->NewNode(m->IntSub(), mem_size, end_offset_node); // Introduce the actual bounds check. Node* cond = graph()->NewNode(m->UintLessThan(), index, effective_size); TrapIfFalse(wasm::kTrapMemOutOfBounds, cond, position); if (untrusted_code_mitigations_) { // In the fallthrough case, condition the index with the memory mask. Node* mem_mask = instance_cache_->mem_mask; DCHECK_NOT_NULL(mem_mask); index = graph()->NewNode(m->WordAnd(), index, mem_mask); } return index; } // Check that the range [start, start + size) is in the range [0, max). void WasmGraphBuilder::BoundsCheckRange(Node* start, Node* size, Node* max, wasm::WasmCodePosition position) { // The accessed memory is [start, end), where {end} is {start + size}. We // want to check that {start + size <= max}, making sure that {start + size} // doesn't overflow. This can be expressed as {start <= max - size} as long // as {max - size} isn't negative, which is true if {size <= max}. auto m = mcgraph()->machine(); Node* cond = graph()->NewNode(m->Uint32LessThanOrEqual(), size, max); TrapIfFalse(wasm::kTrapMemOutOfBounds, cond, position); // This produces a positive number, since {size <= max}. Node* effective_size = graph()->NewNode(m->Int32Sub(), max, size); // Introduce the actual bounds check. Node* check = graph()->NewNode(m->Uint32LessThanOrEqual(), start, effective_size); TrapIfFalse(wasm::kTrapMemOutOfBounds, check, position); // TODO(binji): Does this need addtional untrusted_code_mitigations_ mask // like BoundsCheckMem above? } Node* WasmGraphBuilder::BoundsCheckMemRange(Node* start, Node* size, wasm::WasmCodePosition position) { // TODO(binji): Support trap handler. if (!FLAG_wasm_no_bounds_checks) { BoundsCheckRange(start, size, instance_cache_->mem_size, position); } return graph()->NewNode(mcgraph()->machine()->IntAdd(), MemBuffer(0), Uint32ToUintptr(start)); } const Operator* WasmGraphBuilder::GetSafeLoadOperator(int offset, wasm::ValueType type) { int alignment = offset % (wasm::ValueTypes::ElementSizeInBytes(type)); MachineType mach_type = wasm::ValueTypes::MachineTypeFor(type); if (alignment == 0 || mcgraph()->machine()->UnalignedLoadSupported( wasm::ValueTypes::MachineRepresentationFor(type))) { return mcgraph()->machine()->Load(mach_type); } return mcgraph()->machine()->UnalignedLoad(mach_type); } const Operator* WasmGraphBuilder::GetSafeStoreOperator(int offset, wasm::ValueType type) { int alignment = offset % (wasm::ValueTypes::ElementSizeInBytes(type)); MachineRepresentation rep = wasm::ValueTypes::MachineRepresentationFor(type); if (alignment == 0 || mcgraph()->machine()->UnalignedStoreSupported(rep)) { StoreRepresentation store_rep(rep, WriteBarrierKind::kNoWriteBarrier); return mcgraph()->machine()->Store(store_rep); } UnalignedStoreRepresentation store_rep(rep); return mcgraph()->machine()->UnalignedStore(store_rep); } Node* WasmGraphBuilder::TraceMemoryOperation(bool is_store, MachineRepresentation rep, Node* index, uint32_t offset, wasm::WasmCodePosition position) { int kAlign = 4; // Ensure that the LSB is 0, such that this looks like a Smi. Node* info = graph()->NewNode( mcgraph()->machine()->StackSlot(sizeof(wasm::MemoryTracingInfo), kAlign)); Node* address = graph()->NewNode(mcgraph()->machine()->Int32Add(), Int32Constant(offset), index); auto store = [&](int offset, MachineRepresentation rep, Node* data) { SetEffect(graph()->NewNode( mcgraph()->machine()->Store(StoreRepresentation(rep, kNoWriteBarrier)), info, mcgraph()->Int32Constant(offset), data, Effect(), Control())); }; // Store address, is_store, and mem_rep. store(offsetof(wasm::MemoryTracingInfo, address), MachineRepresentation::kWord32, address); store(offsetof(wasm::MemoryTracingInfo, is_store), MachineRepresentation::kWord8, mcgraph()->Int32Constant(is_store ? 1 : 0)); store(offsetof(wasm::MemoryTracingInfo, mem_rep), MachineRepresentation::kWord8, mcgraph()->Int32Constant(static_cast<int>(rep))); Node* call = BuildCallToRuntime(Runtime::kWasmTraceMemory, &info, 1); SetSourcePosition(call, position); return call; } Node* WasmGraphBuilder::LoadMem(wasm::ValueType type, MachineType memtype, Node* index, uint32_t offset, uint32_t alignment, wasm::WasmCodePosition position) { Node* load; // Wasm semantics throw on OOB. Introduce explicit bounds check and // conditioning when not using the trap handler. index = BoundsCheckMem(wasm::ValueTypes::MemSize(memtype), index, offset, position, kCanOmitBoundsCheck); if (memtype.representation() == MachineRepresentation::kWord8 || mcgraph()->machine()->UnalignedLoadSupported(memtype.representation())) { if (use_trap_handler()) { load = graph()->NewNode(mcgraph()->machine()->ProtectedLoad(memtype), MemBuffer(offset), index, Effect(), Control()); SetSourcePosition(load, position); } else { load = graph()->NewNode(mcgraph()->machine()->Load(memtype), MemBuffer(offset), index, Effect(), Control()); } } else { // TODO(eholk): Support unaligned loads with trap handlers. DCHECK(!use_trap_handler()); load = graph()->NewNode(mcgraph()->machine()->UnalignedLoad(memtype), MemBuffer(offset), index, Effect(), Control()); } SetEffect(load); #if defined(V8_TARGET_BIG_ENDIAN) load = BuildChangeEndiannessLoad(load, memtype, type); #endif if (type == wasm::kWasmI64 && ElementSizeInBytes(memtype.representation()) < 8) { // TODO(titzer): TF zeroes the upper bits of 64-bit loads for subword sizes. if (memtype.IsSigned()) { // sign extend load = graph()->NewNode(mcgraph()->machine()->ChangeInt32ToInt64(), load); } else { // zero extend load = graph()->NewNode(mcgraph()->machine()->ChangeUint32ToUint64(), load); } } if (FLAG_trace_wasm_memory) { TraceMemoryOperation(false, memtype.representation(), index, offset, position); } return load; } Node* WasmGraphBuilder::StoreMem(MachineRepresentation mem_rep, Node* index, uint32_t offset, uint32_t alignment, Node* val, wasm::WasmCodePosition position, wasm::ValueType type) { Node* store; index = BoundsCheckMem(i::ElementSizeInBytes(mem_rep), index, offset, position, kCanOmitBoundsCheck); #if defined(V8_TARGET_BIG_ENDIAN) val = BuildChangeEndiannessStore(val, mem_rep, type); #endif if (mem_rep == MachineRepresentation::kWord8 || mcgraph()->machine()->UnalignedStoreSupported(mem_rep)) { if (use_trap_handler()) { store = graph()->NewNode(mcgraph()->machine()->ProtectedStore(mem_rep), MemBuffer(offset), index, val, Effect(), Control()); SetSourcePosition(store, position); } else { StoreRepresentation rep(mem_rep, kNoWriteBarrier); store = graph()->NewNode(mcgraph()->machine()->Store(rep), MemBuffer(offset), index, val, Effect(), Control()); } } else { // TODO(eholk): Support unaligned stores with trap handlers. DCHECK(!use_trap_handler()); UnalignedStoreRepresentation rep(mem_rep); store = graph()->NewNode(mcgraph()->machine()->UnalignedStore(rep), MemBuffer(offset), index, val, Effect(), Control()); } SetEffect(store); if (FLAG_trace_wasm_memory) { TraceMemoryOperation(true, mem_rep, index, offset, position); } return store; } namespace { Node* GetAsmJsOOBValue(MachineRepresentation rep, MachineGraph* mcgraph) { switch (rep) { case MachineRepresentation::kWord8: case MachineRepresentation::kWord16: case MachineRepresentation::kWord32: return mcgraph->Int32Constant(0); case MachineRepresentation::kWord64: return mcgraph->Int64Constant(0); case MachineRepresentation::kFloat32: return mcgraph->Float32Constant(std::numeric_limits<float>::quiet_NaN()); case MachineRepresentation::kFloat64: return mcgraph->Float64Constant(std::numeric_limits<double>::quiet_NaN()); default: UNREACHABLE(); } } } // namespace Node* WasmGraphBuilder::BuildAsmjsLoadMem(MachineType type, Node* index) { DCHECK_NOT_NULL(instance_cache_); Node* mem_start = instance_cache_->mem_start; Node* mem_size = instance_cache_->mem_size; DCHECK_NOT_NULL(mem_start); DCHECK_NOT_NULL(mem_size); // Asm.js semantics are defined in terms of typed arrays, hence OOB // reads return {undefined} coerced to the result type (0 for integers, NaN // for float and double). // Note that we check against the memory size ignoring the size of the // stored value, which is conservative if misaligned. Technically, asm.js // should never have misaligned accesses. index = Uint32ToUintptr(index); Diamond bounds_check( graph(), mcgraph()->common(), graph()->NewNode(mcgraph()->machine()->UintLessThan(), index, mem_size), BranchHint::kTrue); bounds_check.Chain(Control()); if (untrusted_code_mitigations_) { // Condition the index with the memory mask. Node* mem_mask = instance_cache_->mem_mask; DCHECK_NOT_NULL(mem_mask); index = graph()->NewNode(mcgraph()->machine()->WordAnd(), index, mem_mask); } Node* load = graph()->NewNode(mcgraph()->machine()->Load(type), mem_start, index, Effect(), bounds_check.if_true); SetEffect(bounds_check.EffectPhi(load, Effect())); SetControl(bounds_check.merge); return bounds_check.Phi(type.representation(), load, GetAsmJsOOBValue(type.representation(), mcgraph())); } Node* WasmGraphBuilder::Uint32ToUintptr(Node* node) { if (mcgraph()->machine()->Is32()) return node; // Fold instances of ChangeUint32ToUint64(IntConstant) directly. Uint32Matcher matcher(node); if (matcher.HasValue()) { uintptr_t value = matcher.Value(); return mcgraph()->IntPtrConstant(bit_cast<intptr_t>(value)); } return graph()->NewNode(mcgraph()->machine()->ChangeUint32ToUint64(), node); } Node* WasmGraphBuilder::BuildAsmjsStoreMem(MachineType type, Node* index, Node* val) { DCHECK_NOT_NULL(instance_cache_); Node* mem_start = instance_cache_->mem_start; Node* mem_size = instance_cache_->mem_size; DCHECK_NOT_NULL(mem_start); DCHECK_NOT_NULL(mem_size); // Asm.js semantics are to ignore OOB writes. // Note that we check against the memory size ignoring the size of the // stored value, which is conservative if misaligned. Technically, asm.js // should never have misaligned accesses. Diamond bounds_check( graph(), mcgraph()->common(), graph()->NewNode(mcgraph()->machine()->Uint32LessThan(), index, mem_size), BranchHint::kTrue); bounds_check.Chain(Control()); if (untrusted_code_mitigations_) { // Condition the index with the memory mask. Node* mem_mask = instance_cache_->mem_mask; DCHECK_NOT_NULL(mem_mask); index = graph()->NewNode(mcgraph()->machine()->Word32And(), index, mem_mask); } index = Uint32ToUintptr(index); const Operator* store_op = mcgraph()->machine()->Store(StoreRepresentation( type.representation(), WriteBarrierKind::kNoWriteBarrier)); Node* store = graph()->NewNode(store_op, mem_start, index, val, Effect(), bounds_check.if_true); SetEffect(bounds_check.EffectPhi(store, Effect())); SetControl(bounds_check.merge); return val; } void WasmGraphBuilder::PrintDebugName(Node* node) { PrintF("#%d:%s", node->id(), node->op()->mnemonic()); } Graph* WasmGraphBuilder::graph() { return mcgraph()->graph(); } namespace { Signature<MachineRepresentation>* CreateMachineSignature( Zone* zone, wasm::FunctionSig* sig) { Signature<MachineRepresentation>::Builder builder(zone, sig->return_count(), sig->parameter_count()); for (auto ret : sig->returns()) { builder.AddReturn(wasm::ValueTypes::MachineRepresentationFor(ret)); } for (auto param : sig->parameters()) { builder.AddParam(wasm::ValueTypes::MachineRepresentationFor(param)); } return builder.Build(); } } // namespace void WasmGraphBuilder::LowerInt64() { if (mcgraph()->machine()->Is64()) return; Int64Lowering r(mcgraph()->graph(), mcgraph()->machine(), mcgraph()->common(), mcgraph()->zone(), CreateMachineSignature(mcgraph()->zone(), sig_)); r.LowerGraph(); } void WasmGraphBuilder::SimdScalarLoweringForTesting() { SimdScalarLowering(mcgraph(), CreateMachineSignature(mcgraph()->zone(), sig_)) .LowerGraph(); } void WasmGraphBuilder::SetSourcePosition(Node* node, wasm::WasmCodePosition position) { DCHECK_NE(position, wasm::kNoCodePosition); if (source_position_table_) source_position_table_->SetSourcePosition(node, SourcePosition(position)); } Node* WasmGraphBuilder::S128Zero() { has_simd_ = true; return graph()->NewNode(mcgraph()->machine()->S128Zero()); } Node* WasmGraphBuilder::SimdOp(wasm::WasmOpcode opcode, Node* const* inputs) { has_simd_ = true; switch (opcode) { case wasm::kExprF32x4Splat: return graph()->NewNode(mcgraph()->machine()->F32x4Splat(), inputs[0]); case wasm::kExprF32x4SConvertI32x4: return graph()->NewNode(mcgraph()->machine()->F32x4SConvertI32x4(), inputs[0]); case wasm::kExprF32x4UConvertI32x4: return graph()->NewNode(mcgraph()->machine()->F32x4UConvertI32x4(), inputs[0]); case wasm::kExprF32x4Abs: return graph()->NewNode(mcgraph()->machine()->F32x4Abs(), inputs[0]); case wasm::kExprF32x4Neg: return graph()->NewNode(mcgraph()->machine()->F32x4Neg(), inputs[0]); case wasm::kExprF32x4RecipApprox: return graph()->NewNode(mcgraph()->machine()->F32x4RecipApprox(), inputs[0]); case wasm::kExprF32x4RecipSqrtApprox: return graph()->NewNode(mcgraph()->machine()->F32x4RecipSqrtApprox(), inputs[0]); case wasm::kExprF32x4Add: return graph()->NewNode(mcgraph()->machine()->F32x4Add(), inputs[0], inputs[1]); case wasm::kExprF32x4AddHoriz: return graph()->NewNode(mcgraph()->machine()->F32x4AddHoriz(), inputs[0], inputs[1]); case wasm::kExprF32x4Sub: return graph()->NewNode(mcgraph()->machine()->F32x4Sub(), inputs[0], inputs[1]); case wasm::kExprF32x4Mul: return graph()->NewNode(mcgraph()->machine()->F32x4Mul(), inputs[0], inputs[1]); case wasm::kExprF32x4Min: return graph()->NewNode(mcgraph()->machine()->F32x4Min(), inputs[0], inputs[1]); case wasm::kExprF32x4Max: return graph()->NewNode(mcgraph()->machine()->F32x4Max(), inputs[0], inputs[1]); case wasm::kExprF32x4Eq: return graph()->NewNode(mcgraph()->machine()->F32x4Eq(), inputs[0], inputs[1]); case wasm::kExprF32x4Ne: return graph()->NewNode(mcgraph()->machine()->F32x4Ne(), inputs[0], inputs[1]); case wasm::kExprF32x4Lt: return graph()->NewNode(mcgraph()->machine()->F32x4Lt(), inputs[0], inputs[1]); case wasm::kExprF32x4Le: return graph()->NewNode(mcgraph()->machine()->F32x4Le(), inputs[0], inputs[1]); case wasm::kExprF32x4Gt: return graph()->NewNode(mcgraph()->machine()->F32x4Lt(), inputs[1], inputs[0]); case wasm::kExprF32x4Ge: return graph()->NewNode(mcgraph()->machine()->F32x4Le(), inputs[1], inputs[0]); case wasm::kExprI32x4Splat: return graph()->NewNode(mcgraph()->machine()->I32x4Splat(), inputs[0]); case wasm::kExprI32x4SConvertF32x4: return graph()->NewNode(mcgraph()->machine()->I32x4SConvertF32x4(), inputs[0]); case wasm::kExprI32x4UConvertF32x4: return graph()->NewNode(mcgraph()->machine()->I32x4UConvertF32x4(), inputs[0]); case wasm::kExprI32x4SConvertI16x8Low: return graph()->NewNode(mcgraph()->machine()->I32x4SConvertI16x8Low(), inputs[0]); case wasm::kExprI32x4SConvertI16x8High: return graph()->NewNode(mcgraph()->machine()->I32x4SConvertI16x8High(), inputs[0]); case wasm::kExprI32x4Neg: return graph()->NewNode(mcgraph()->machine()->I32x4Neg(), inputs[0]); case wasm::kExprI32x4Add: return graph()->NewNode(mcgraph()->machine()->I32x4Add(), inputs[0], inputs[1]); case wasm::kExprI32x4AddHoriz: return graph()->NewNode(mcgraph()->machine()->I32x4AddHoriz(), inputs[0], inputs[1]); case wasm::kExprI32x4Sub: return graph()->NewNode(mcgraph()->machine()->I32x4Sub(), inputs[0], inputs[1]); case wasm::kExprI32x4Mul: return graph()->NewNode(mcgraph()->machine()->I32x4Mul(), inputs[0], inputs[1]); case wasm::kExprI32x4MinS: return graph()->NewNode(mcgraph()->machine()->I32x4MinS(), inputs[0], inputs[1]); case wasm::kExprI32x4MaxS: return graph()->NewNode(mcgraph()->machine()->I32x4MaxS(), inputs[0], inputs[1]); case wasm::kExprI32x4Eq: return graph()->NewNode(mcgraph()->machine()->I32x4Eq(), inputs[0], inputs[1]); case wasm::kExprI32x4Ne: return graph()->NewNode(mcgraph()->machine()->I32x4Ne(), inputs[0], inputs[1]); case wasm::kExprI32x4LtS: return graph()->NewNode(mcgraph()->machine()->I32x4GtS(), inputs[1], inputs[0]); case wasm::kExprI32x4LeS: return graph()->NewNode(mcgraph()->machine()->I32x4GeS(), inputs[1], inputs[0]); case wasm::kExprI32x4GtS: return graph()->NewNode(mcgraph()->machine()->I32x4GtS(), inputs[0], inputs[1]); case wasm::kExprI32x4GeS: return graph()->NewNode(mcgraph()->machine()->I32x4GeS(), inputs[0], inputs[1]); case wasm::kExprI32x4UConvertI16x8Low: return graph()->NewNode(mcgraph()->machine()->I32x4UConvertI16x8Low(), inputs[0]); case wasm::kExprI32x4UConvertI16x8High: return graph()->NewNode(mcgraph()->machine()->I32x4UConvertI16x8High(), inputs[0]); case wasm::kExprI32x4MinU: return graph()->NewNode(mcgraph()->machine()->I32x4MinU(), inputs[0], inputs[1]); case wasm::kExprI32x4MaxU: return graph()->NewNode(mcgraph()->machine()->I32x4MaxU(), inputs[0], inputs[1]); case wasm::kExprI32x4LtU: return graph()->NewNode(mcgraph()->machine()->I32x4GtU(), inputs[1], inputs[0]); case wasm::kExprI32x4LeU: return graph()->NewNode(mcgraph()->machine()->I32x4GeU(), inputs[1], inputs[0]); case wasm::kExprI32x4GtU: return graph()->NewNode(mcgraph()->machine()->I32x4GtU(), inputs[0], inputs[1]); case wasm::kExprI32x4GeU: return graph()->NewNode(mcgraph()->machine()->I32x4GeU(), inputs[0], inputs[1]); case wasm::kExprI16x8Splat: return graph()->NewNode(mcgraph()->machine()->I16x8Splat(), inputs[0]); case wasm::kExprI16x8SConvertI8x16Low: return graph()->NewNode(mcgraph()->machine()->I16x8SConvertI8x16Low(), inputs[0]); case wasm::kExprI16x8SConvertI8x16High: return graph()->NewNode(mcgraph()->machine()->I16x8SConvertI8x16High(), inputs[0]); case wasm::kExprI16x8Neg: return graph()->NewNode(mcgraph()->machine()->I16x8Neg(), inputs[0]); case wasm::kExprI16x8SConvertI32x4: return graph()->NewNode(mcgraph()->machine()->I16x8SConvertI32x4(), inputs[0], inputs[1]); case wasm::kExprI16x8Add: return graph()->NewNode(mcgraph()->machine()->I16x8Add(), inputs[0], inputs[1]); case wasm::kExprI16x8AddSaturateS: return graph()->NewNode(mcgraph()->machine()->I16x8AddSaturateS(), inputs[0], inputs[1]); case wasm::kExprI16x8AddHoriz: return graph()->NewNode(mcgraph()->machine()->I16x8AddHoriz(), inputs[0], inputs[1]); case wasm::kExprI16x8Sub: return graph()->NewNode(mcgraph()->machine()->I16x8Sub(), inputs[0], inputs[1]); case wasm::kExprI16x8SubSaturateS: return graph()->NewNode(mcgraph()->machine()->I16x8SubSaturateS(), inputs[0], inputs[1]); case wasm::kExprI16x8Mul: return graph()->NewNode(mcgraph()->machine()->I16x8Mul(), inputs[0], inputs[1]); case wasm::kExprI16x8MinS: return graph()->NewNode(mcgraph()->machine()->I16x8MinS(), inputs[0], inputs[1]); case wasm::kExprI16x8MaxS: return graph()->NewNode(mcgraph()->machine()->I16x8MaxS(), inputs[0], inputs[1]); case wasm::kExprI16x8Eq: return graph()->NewNode(mcgraph()->machine()->I16x8Eq(), inputs[0], inputs[1]); case wasm::kExprI16x8Ne: return graph()->NewNode(mcgraph()->machine()->I16x8Ne(), inputs[0], inputs[1]); case wasm::kExprI16x8LtS: return graph()->NewNode(mcgraph()->machine()->I16x8GtS(), inputs[1], inputs[0]); case wasm::kExprI16x8LeS: return graph()->NewNode(mcgraph()->machine()->I16x8GeS(), inputs[1], inputs[0]); case wasm::kExprI16x8GtS: return graph()->NewNode(mcgraph()->machine()->I16x8GtS(), inputs[0], inputs[1]); case wasm::kExprI16x8GeS: return graph()->NewNode(mcgraph()->machine()->I16x8GeS(), inputs[0], inputs[1]); case wasm::kExprI16x8UConvertI8x16Low: return graph()->NewNode(mcgraph()->machine()->I16x8UConvertI8x16Low(), inputs[0]); case wasm::kExprI16x8UConvertI8x16High: return graph()->NewNode(mcgraph()->machine()->I16x8UConvertI8x16High(), inputs[0]); case wasm::kExprI16x8UConvertI32x4: return graph()->NewNode(mcgraph()->machine()->I16x8UConvertI32x4(), inputs[0], inputs[1]); case wasm::kExprI16x8AddSaturateU: return graph()->NewNode(mcgraph()->machine()->I16x8AddSaturateU(), inputs[0], inputs[1]); case wasm::kExprI16x8SubSaturateU: return graph()->NewNode(mcgraph()->machine()->I16x8SubSaturateU(), inputs[0], inputs[1]); case wasm::kExprI16x8MinU: return graph()->NewNode(mcgraph()->machine()->I16x8MinU(), inputs[0], inputs[1]); case wasm::kExprI16x8MaxU: return graph()->NewNode(mcgraph()->machine()->I16x8MaxU(), inputs[0], inputs[1]); case wasm::kExprI16x8LtU: return graph()->NewNode(mcgraph()->machine()->I16x8GtU(), inputs[1], inputs[0]); case wasm::kExprI16x8LeU: return graph()->NewNode(mcgraph()->machine()->I16x8GeU(), inputs[1], inputs[0]); case wasm::kExprI16x8GtU: return graph()->NewNode(mcgraph()->machine()->I16x8GtU(), inputs[0], inputs[1]); case wasm::kExprI16x8GeU: return graph()->NewNode(mcgraph()->machine()->I16x8GeU(), inputs[0], inputs[1]); case wasm::kExprI8x16Splat: return graph()->NewNode(mcgraph()->machine()->I8x16Splat(), inputs[0]); case wasm::kExprI8x16Neg: return graph()->NewNode(mcgraph()->machine()->I8x16Neg(), inputs[0]); case wasm::kExprI8x16SConvertI16x8: return graph()->NewNode(mcgraph()->machine()->I8x16SConvertI16x8(), inputs[0], inputs[1]); case wasm::kExprI8x16Add: return graph()->NewNode(mcgraph()->machine()->I8x16Add(), inputs[0], inputs[1]); case wasm::kExprI8x16AddSaturateS: return graph()->NewNode(mcgraph()->machine()->I8x16AddSaturateS(), inputs[0], inputs[1]); case wasm::kExprI8x16Sub: return graph()->NewNode(mcgraph()->machine()->I8x16Sub(), inputs[0], inputs[1]); case wasm::kExprI8x16SubSaturateS: return graph()->NewNode(mcgraph()->machine()->I8x16SubSaturateS(), inputs[0], inputs[1]); case wasm::kExprI8x16Mul: return graph()->NewNode(mcgraph()->machine()->I8x16Mul(), inputs[0], inputs[1]); case wasm::kExprI8x16MinS: return graph()->NewNode(mcgraph()->machine()->I8x16MinS(), inputs[0], inputs[1]); case wasm::kExprI8x16MaxS: return graph()->NewNode(mcgraph()->machine()->I8x16MaxS(), inputs[0], inputs[1]); case wasm::kExprI8x16Eq: return graph()->NewNode(mcgraph()->machine()->I8x16Eq(), inputs[0], inputs[1]); case wasm::kExprI8x16Ne: return graph()->NewNode(mcgraph()->machine()->I8x16Ne(), inputs[0], inputs[1]); case wasm::kExprI8x16LtS: return graph()->NewNode(mcgraph()->machine()->I8x16GtS(), inputs[1], inputs[0]); case wasm::kExprI8x16LeS: return graph()->NewNode(mcgraph()->machine()->I8x16GeS(), inputs[1], inputs[0]); case wasm::kExprI8x16GtS: return graph()->NewNode(mcgraph()->machine()->I8x16GtS(), inputs[0], inputs[1]); case wasm::kExprI8x16GeS: return graph()->NewNode(mcgraph()->machine()->I8x16GeS(), inputs[0], inputs[1]); case wasm::kExprI8x16UConvertI16x8: return graph()->NewNode(mcgraph()->machine()->I8x16UConvertI16x8(), inputs[0], inputs[1]); case wasm::kExprI8x16AddSaturateU: return graph()->NewNode(mcgraph()->machine()->I8x16AddSaturateU(), inputs[0], inputs[1]); case wasm::kExprI8x16SubSaturateU: return graph()->NewNode(mcgraph()->machine()->I8x16SubSaturateU(), inputs[0], inputs[1]); case wasm::kExprI8x16MinU: return graph()->NewNode(mcgraph()->machine()->I8x16MinU(), inputs[0], inputs[1]); case wasm::kExprI8x16MaxU: return graph()->NewNode(mcgraph()->machine()->I8x16MaxU(), inputs[0], inputs[1]); case wasm::kExprI8x16LtU: return graph()->NewNode(mcgraph()->machine()->I8x16GtU(), inputs[1], inputs[0]); case wasm::kExprI8x16LeU: return graph()->NewNode(mcgraph()->machine()->I8x16GeU(), inputs[1], inputs[0]); case wasm::kExprI8x16GtU: return graph()->NewNode(mcgraph()->machine()->I8x16GtU(), inputs[0], inputs[1]); case wasm::kExprI8x16GeU: return graph()->NewNode(mcgraph()->machine()->I8x16GeU(), inputs[0], inputs[1]); case wasm::kExprS128And: return graph()->NewNode(mcgraph()->machine()->S128And(), inputs[0], inputs[1]); case wasm::kExprS128Or: return graph()->NewNode(mcgraph()->machine()->S128Or(), inputs[0], inputs[1]); case wasm::kExprS128Xor: return graph()->NewNode(mcgraph()->machine()->S128Xor(), inputs[0], inputs[1]); case wasm::kExprS128Not: return graph()->NewNode(mcgraph()->machine()->S128Not(), inputs[0]); case wasm::kExprS128Select: return graph()->NewNode(mcgraph()->machine()->S128Select(), inputs[2], inputs[0], inputs[1]); case wasm::kExprS1x4AnyTrue: return graph()->NewNode(mcgraph()->machine()->S1x4AnyTrue(), inputs[0]); case wasm::kExprS1x4AllTrue: return graph()->NewNode(mcgraph()->machine()->S1x4AllTrue(), inputs[0]); case wasm::kExprS1x8AnyTrue: return graph()->NewNode(mcgraph()->machine()->S1x8AnyTrue(), inputs[0]); case wasm::kExprS1x8AllTrue: return graph()->NewNode(mcgraph()->machine()->S1x8AllTrue(), inputs[0]); case wasm::kExprS1x16AnyTrue: return graph()->NewNode(mcgraph()->machine()->S1x16AnyTrue(), inputs[0]); case wasm::kExprS1x16AllTrue: return graph()->NewNode(mcgraph()->machine()->S1x16AllTrue(), inputs[0]); default: FATAL_UNSUPPORTED_OPCODE(opcode); } } Node* WasmGraphBuilder::SimdLaneOp(wasm::WasmOpcode opcode, uint8_t lane, Node* const* inputs) { has_simd_ = true; switch (opcode) { case wasm::kExprF32x4ExtractLane: return graph()->NewNode(mcgraph()->machine()->F32x4ExtractLane(lane), inputs[0]); case wasm::kExprF32x4ReplaceLane: return graph()->NewNode(mcgraph()->machine()->F32x4ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprI32x4ExtractLane: return graph()->NewNode(mcgraph()->machine()->I32x4ExtractLane(lane), inputs[0]); case wasm::kExprI32x4ReplaceLane: return graph()->NewNode(mcgraph()->machine()->I32x4ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprI16x8ExtractLane: return graph()->NewNode(mcgraph()->machine()->I16x8ExtractLane(lane), inputs[0]); case wasm::kExprI16x8ReplaceLane: return graph()->NewNode(mcgraph()->machine()->I16x8ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprI8x16ExtractLane: return graph()->NewNode(mcgraph()->machine()->I8x16ExtractLane(lane), inputs[0]); case wasm::kExprI8x16ReplaceLane: return graph()->NewNode(mcgraph()->machine()->I8x16ReplaceLane(lane), inputs[0], inputs[1]); default: FATAL_UNSUPPORTED_OPCODE(opcode); } } Node* WasmGraphBuilder::SimdShiftOp(wasm::WasmOpcode opcode, uint8_t shift, Node* const* inputs) { has_simd_ = true; switch (opcode) { case wasm::kExprI32x4Shl: return graph()->NewNode(mcgraph()->machine()->I32x4Shl(shift), inputs[0]); case wasm::kExprI32x4ShrS: return graph()->NewNode(mcgraph()->machine()->I32x4ShrS(shift), inputs[0]); case wasm::kExprI32x4ShrU: return graph()->NewNode(mcgraph()->machine()->I32x4ShrU(shift), inputs[0]); case wasm::kExprI16x8Shl: return graph()->NewNode(mcgraph()->machine()->I16x8Shl(shift), inputs[0]); case wasm::kExprI16x8ShrS: return graph()->NewNode(mcgraph()->machine()->I16x8ShrS(shift), inputs[0]); case wasm::kExprI16x8ShrU: return graph()->NewNode(mcgraph()->machine()->I16x8ShrU(shift), inputs[0]); case wasm::kExprI8x16Shl: return graph()->NewNode(mcgraph()->machine()->I8x16Shl(shift), inputs[0]); case wasm::kExprI8x16ShrS: return graph()->NewNode(mcgraph()->machine()->I8x16ShrS(shift), inputs[0]); case wasm::kExprI8x16ShrU: return graph()->NewNode(mcgraph()->machine()->I8x16ShrU(shift), inputs[0]); default: FATAL_UNSUPPORTED_OPCODE(opcode); } } Node* WasmGraphBuilder::Simd8x16ShuffleOp(const uint8_t shuffle[16], Node* const* inputs) { has_simd_ = true; return graph()->NewNode(mcgraph()->machine()->S8x16Shuffle(shuffle), inputs[0], inputs[1]); } #define ATOMIC_BINOP_LIST(V) \ V(I32AtomicAdd, Add, Uint32, Word32) \ V(I64AtomicAdd, Add, Uint64, Word64) \ V(I32AtomicAdd8U, Add, Uint8, Word32) \ V(I32AtomicAdd16U, Add, Uint16, Word32) \ V(I64AtomicAdd8U, Add, Uint8, Word64) \ V(I64AtomicAdd16U, Add, Uint16, Word64) \ V(I64AtomicAdd32U, Add, Uint32, Word64) \ V(I32AtomicSub, Sub, Uint32, Word32) \ V(I64AtomicSub, Sub, Uint64, Word64) \ V(I32AtomicSub8U, Sub, Uint8, Word32) \ V(I32AtomicSub16U, Sub, Uint16, Word32) \ V(I64AtomicSub8U, Sub, Uint8, Word64) \ V(I64AtomicSub16U, Sub, Uint16, Word64) \ V(I64AtomicSub32U, Sub, Uint32, Word64) \ V(I32AtomicAnd, And, Uint32, Word32) \ V(I64AtomicAnd, And, Uint64, Word64) \ V(I32AtomicAnd8U, And, Uint8, Word32) \ V(I64AtomicAnd16U, And, Uint16, Word64) \ V(I32AtomicAnd16U, And, Uint16, Word32) \ V(I64AtomicAnd8U, And, Uint8, Word64) \ V(I64AtomicAnd32U, And, Uint32, Word64) \ V(I32AtomicOr, Or, Uint32, Word32) \ V(I64AtomicOr, Or, Uint64, Word64) \ V(I32AtomicOr8U, Or, Uint8, Word32) \ V(I32AtomicOr16U, Or, Uint16, Word32) \ V(I64AtomicOr8U, Or, Uint8, Word64) \ V(I64AtomicOr16U, Or, Uint16, Word64) \ V(I64AtomicOr32U, Or, Uint32, Word64) \ V(I32AtomicXor, Xor, Uint32, Word32) \ V(I64AtomicXor, Xor, Uint64, Word64) \ V(I32AtomicXor8U, Xor, Uint8, Word32) \ V(I32AtomicXor16U, Xor, Uint16, Word32) \ V(I64AtomicXor8U, Xor, Uint8, Word64) \ V(I64AtomicXor16U, Xor, Uint16, Word64) \ V(I64AtomicXor32U, Xor, Uint32, Word64) \ V(I32AtomicExchange, Exchange, Uint32, Word32) \ V(I64AtomicExchange, Exchange, Uint64, Word64) \ V(I32AtomicExchange8U, Exchange, Uint8, Word32) \ V(I32AtomicExchange16U, Exchange, Uint16, Word32) \ V(I64AtomicExchange8U, Exchange, Uint8, Word64) \ V(I64AtomicExchange16U, Exchange, Uint16, Word64) \ V(I64AtomicExchange32U, Exchange, Uint32, Word64) #define ATOMIC_CMP_EXCHG_LIST(V) \ V(I32AtomicCompareExchange, Uint32, Word32) \ V(I64AtomicCompareExchange, Uint64, Word64) \ V(I32AtomicCompareExchange8U, Uint8, Word32) \ V(I32AtomicCompareExchange16U, Uint16, Word32) \ V(I64AtomicCompareExchange8U, Uint8, Word64) \ V(I64AtomicCompareExchange16U, Uint16, Word64) \ V(I64AtomicCompareExchange32U, Uint32, Word64) #define ATOMIC_LOAD_LIST(V) \ V(I32AtomicLoad, Uint32, Word32) \ V(I64AtomicLoad, Uint64, Word64) \ V(I32AtomicLoad8U, Uint8, Word32) \ V(I32AtomicLoad16U, Uint16, Word32) \ V(I64AtomicLoad8U, Uint8, Word64) \ V(I64AtomicLoad16U, Uint16, Word64) \ V(I64AtomicLoad32U, Uint32, Word64) #define ATOMIC_STORE_LIST(V) \ V(I32AtomicStore, Uint32, kWord32, Word32) \ V(I64AtomicStore, Uint64, kWord64, Word64) \ V(I32AtomicStore8U, Uint8, kWord8, Word32) \ V(I32AtomicStore16U, Uint16, kWord16, Word32) \ V(I64AtomicStore8U, Uint8, kWord8, Word64) \ V(I64AtomicStore16U, Uint16, kWord16, Word64) \ V(I64AtomicStore32U, Uint32, kWord32, Word64) Node* WasmGraphBuilder::AtomicOp(wasm::WasmOpcode opcode, Node* const* inputs, uint32_t alignment, uint32_t offset, wasm::WasmCodePosition position) { Node* node; switch (opcode) { #define BUILD_ATOMIC_BINOP(Name, Operation, Type, Prefix) \ case wasm::kExpr##Name: { \ Node* index = CheckBoundsAndAlignment( \ wasm::ValueTypes::MemSize(MachineType::Type()), inputs[0], offset, \ position); \ node = graph()->NewNode( \ mcgraph()->machine()->Prefix##Atomic##Operation(MachineType::Type()), \ MemBuffer(offset), index, inputs[1], Effect(), Control()); \ break; \ } ATOMIC_BINOP_LIST(BUILD_ATOMIC_BINOP) #undef BUILD_ATOMIC_BINOP #define BUILD_ATOMIC_CMP_EXCHG(Name, Type, Prefix) \ case wasm::kExpr##Name: { \ Node* index = CheckBoundsAndAlignment( \ wasm::ValueTypes::MemSize(MachineType::Type()), inputs[0], offset, \ position); \ node = graph()->NewNode( \ mcgraph()->machine()->Prefix##AtomicCompareExchange( \ MachineType::Type()), \ MemBuffer(offset), index, inputs[1], inputs[2], Effect(), Control()); \ break; \ } ATOMIC_CMP_EXCHG_LIST(BUILD_ATOMIC_CMP_EXCHG) #undef BUILD_ATOMIC_CMP_EXCHG #define BUILD_ATOMIC_LOAD_OP(Name, Type, Prefix) \ case wasm::kExpr##Name: { \ Node* index = CheckBoundsAndAlignment( \ wasm::ValueTypes::MemSize(MachineType::Type()), inputs[0], offset, \ position); \ node = graph()->NewNode( \ mcgraph()->machine()->Prefix##AtomicLoad(MachineType::Type()), \ MemBuffer(offset), index, Effect(), Control()); \ break; \ } ATOMIC_LOAD_LIST(BUILD_ATOMIC_LOAD_OP) #undef BUILD_ATOMIC_LOAD_OP #define BUILD_ATOMIC_STORE_OP(Name, Type, Rep, Prefix) \ case wasm::kExpr##Name: { \ Node* index = CheckBoundsAndAlignment( \ wasm::ValueTypes::MemSize(MachineType::Type()), inputs[0], offset, \ position); \ node = graph()->NewNode( \ mcgraph()->machine()->Prefix##AtomicStore(MachineRepresentation::Rep), \ MemBuffer(offset), index, inputs[1], Effect(), Control()); \ break; \ } ATOMIC_STORE_LIST(BUILD_ATOMIC_STORE_OP) #undef BUILD_ATOMIC_STORE_OP case wasm::kExprAtomicWake: { Node* index = CheckBoundsAndAlignment( wasm::ValueTypes::MemSize(MachineType::Uint32()), inputs[0], offset, position); // Now that we've bounds-checked, compute the effective address. Node* address = graph()->NewNode(mcgraph()->machine()->Int32Add(), Uint32Constant(offset), index); WasmAtomicWakeDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmAtomicWake, RelocInfo::WASM_STUB_CALL); node = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, address, inputs[1], Effect(), Control()); break; } case wasm::kExprI32AtomicWait: { Node* index = CheckBoundsAndAlignment( wasm::ValueTypes::MemSize(MachineType::Uint32()), inputs[0], offset, position); // Now that we've bounds-checked, compute the effective address. Node* address = graph()->NewNode(mcgraph()->machine()->Int32Add(), Uint32Constant(offset), index); Node* timeout; if (mcgraph()->machine()->Is32()) { timeout = BuildF64SConvertI64(inputs[2]); } else { timeout = graph()->NewNode(mcgraph()->machine()->RoundInt64ToFloat64(), inputs[2]); } WasmI32AtomicWaitDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmI32AtomicWait, RelocInfo::WASM_STUB_CALL); node = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, address, inputs[1], timeout, Effect(), Control()); break; } case wasm::kExprI64AtomicWait: { Node* index = CheckBoundsAndAlignment( wasm::ValueTypes::MemSize(MachineType::Uint32()), inputs[0], offset, position); // Now that we've bounds-checked, compute the effective address. Node* address = graph()->NewNode(mcgraph()->machine()->Int32Add(), Uint32Constant(offset), index); Node* timeout; if (mcgraph()->machine()->Is32()) { timeout = BuildF64SConvertI64(inputs[2]); } else { timeout = graph()->NewNode(mcgraph()->machine()->RoundInt64ToFloat64(), inputs[2]); } Node* expected_value_low = graph()->NewNode( mcgraph()->machine()->TruncateInt64ToInt32(), inputs[1]); Node* tmp = graph()->NewNode(mcgraph()->machine()->Word64Shr(), inputs[1], Int64Constant(32)); Node* expected_value_high = graph()->NewNode(mcgraph()->machine()->TruncateInt64ToInt32(), tmp); WasmI64AtomicWaitDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmI64AtomicWait, RelocInfo::WASM_STUB_CALL); node = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, address, expected_value_high, expected_value_low, timeout, Effect(), Control()); break; } default: FATAL_UNSUPPORTED_OPCODE(opcode); } return SetEffect(node); } #undef ATOMIC_BINOP_LIST #undef ATOMIC_CMP_EXCHG_LIST #undef ATOMIC_LOAD_LIST #undef ATOMIC_STORE_LIST Node* WasmGraphBuilder::CheckDataSegmentIsPassiveAndNotDropped( uint32_t data_segment_index, wasm::WasmCodePosition position) { // The data segment index must be in bounds since it is required by // validation. DCHECK_LT(data_segment_index, env_->module->num_declared_data_segments); Node* dropped_data_segments = LOAD_INSTANCE_FIELD(DroppedDataSegments, MachineType::Pointer()); Node* is_segment_dropped = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Uint8()), dropped_data_segments, mcgraph()->IntPtrConstant(data_segment_index), Effect(), Control())); TrapIfTrue(wasm::kTrapDataSegmentDropped, is_segment_dropped, position); return dropped_data_segments; } Node* WasmGraphBuilder::MemoryInit(uint32_t data_segment_index, Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { CheckDataSegmentIsPassiveAndNotDropped(data_segment_index, position); dst = BoundsCheckMemRange(dst, size, position); MachineOperatorBuilder* m = mcgraph()->machine(); Node* seg_index = Uint32Constant(data_segment_index); { // Load segment size from WasmInstanceObject::data_segment_sizes. Node* seg_size_array = LOAD_INSTANCE_FIELD(DataSegmentSizes, MachineType::Pointer()); STATIC_ASSERT(wasm::kV8MaxWasmDataSegments <= kMaxUInt32 >> 2); Node* scaled_index = Uint32ToUintptr( graph()->NewNode(m->Word32Shl(), seg_index, Int32Constant(2))); Node* seg_size = SetEffect(graph()->NewNode(m->Load(MachineType::Uint32()), seg_size_array, scaled_index, Effect(), Control())); // Bounds check the src index against the segment size. BoundsCheckRange(src, size, seg_size, position); } { // Load segment's base pointer from WasmInstanceObject::data_segment_starts. Node* seg_start_array = LOAD_INSTANCE_FIELD(DataSegmentStarts, MachineType::Pointer()); STATIC_ASSERT(wasm::kV8MaxWasmDataSegments <= kMaxUInt32 >> kPointerSizeLog2); Node* scaled_index = Uint32ToUintptr(graph()->NewNode( m->Word32Shl(), seg_index, Int32Constant(kPointerSizeLog2))); Node* seg_start = SetEffect( graph()->NewNode(m->Load(MachineType::Pointer()), seg_start_array, scaled_index, Effect(), Control())); // Convert src index to pointer. src = graph()->NewNode(m->IntAdd(), seg_start, Uint32ToUintptr(src)); } Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant( ExternalReference::wasm_memory_copy())); MachineType sig_types[] = {MachineType::Pointer(), MachineType::Pointer(), MachineType::Uint32()}; MachineSignature sig(0, 3, sig_types); return BuildCCall(&sig, function, dst, src, size); } Node* WasmGraphBuilder::MemoryDrop(uint32_t data_segment_index, wasm::WasmCodePosition position) { Node* dropped_data_segments = CheckDataSegmentIsPassiveAndNotDropped(data_segment_index, position); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(MachineRepresentation::kWord8, kNoWriteBarrier)); return SetEffect( graph()->NewNode(store_op, dropped_data_segments, mcgraph()->IntPtrConstant(data_segment_index), mcgraph()->Int32Constant(1), Effect(), Control())); } Node* WasmGraphBuilder::MemoryCopy(Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { dst = BoundsCheckMemRange(dst, size, position); src = BoundsCheckMemRange(src, size, position); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant( ExternalReference::wasm_memory_copy())); MachineType sig_types[] = {MachineType::Pointer(), MachineType::Pointer(), MachineType::Uint32()}; MachineSignature sig(0, 3, sig_types); return BuildCCall(&sig, function, dst, src, size); } Node* WasmGraphBuilder::MemoryFill(Node* dst, Node* value, Node* size, wasm::WasmCodePosition position) { dst = BoundsCheckMemRange(dst, size, position); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant( ExternalReference::wasm_memory_fill())); MachineType sig_types[] = {MachineType::Pointer(), MachineType::Uint32(), MachineType::Uint32()}; MachineSignature sig(0, 3, sig_types); return BuildCCall(&sig, function, dst, value, size); } Node* WasmGraphBuilder::CheckElemSegmentIsPassiveAndNotDropped( uint32_t elem_segment_index, wasm::WasmCodePosition position) { // The elem segment index must be in bounds since it is required by // validation. DCHECK_LT(elem_segment_index, env_->module->elem_segments.size()); Node* dropped_elem_segments = LOAD_INSTANCE_FIELD(DroppedElemSegments, MachineType::Pointer()); Node* is_segment_dropped = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Uint8()), dropped_elem_segments, mcgraph()->IntPtrConstant(elem_segment_index), Effect(), Control())); TrapIfTrue(wasm::kTrapElemSegmentDropped, is_segment_dropped, position); return dropped_elem_segments; } Node* WasmGraphBuilder::TableInit(uint32_t table_index, uint32_t elem_segment_index, Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { // TODO(titzer): bounds check table indexes against maximum table size. Node* args[] = { // -- graph()->NewNode(mcgraph()->common()->NumberConstant(table_index)), graph()->NewNode(mcgraph()->common()->NumberConstant(elem_segment_index)), BuildChangeUint31ToSmi(dst), // -- BuildChangeUint31ToSmi(src), // -- BuildChangeUint31ToSmi(size) // -- }; Node* result = BuildCallToRuntime(Runtime::kWasmTableInit, args, arraysize(args)); return result; } Node* WasmGraphBuilder::TableDrop(uint32_t elem_segment_index, wasm::WasmCodePosition position) { Node* dropped_elem_segments = CheckElemSegmentIsPassiveAndNotDropped(elem_segment_index, position); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(MachineRepresentation::kWord8, kNoWriteBarrier)); return SetEffect( graph()->NewNode(store_op, dropped_elem_segments, mcgraph()->IntPtrConstant(elem_segment_index), mcgraph()->Int32Constant(1), Effect(), Control())); } Node* WasmGraphBuilder::TableCopy(Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { // TODO(titzer): bounds check table indexes against maximum table size. Node* args[] = { BuildChangeUint31ToSmi(dst), // -- BuildChangeUint31ToSmi(src), // -- BuildChangeUint31ToSmi(size) // -- }; Node* result = BuildCallToRuntime(Runtime::kWasmTableCopy, args, arraysize(args)); return result; } class WasmDecorator final : public GraphDecorator { public: explicit WasmDecorator(NodeOriginTable* origins, wasm::Decoder* decoder) : origins_(origins), decoder_(decoder) {} void Decorate(Node* node) final { origins_->SetNodeOrigin( node, NodeOrigin("wasm graph creation", "n/a", NodeOrigin::kWasmBytecode, decoder_->position())); } private: compiler::NodeOriginTable* origins_; wasm::Decoder* decoder_; }; void WasmGraphBuilder::AddBytecodePositionDecorator( NodeOriginTable* node_origins, wasm::Decoder* decoder) { DCHECK_NULL(decorator_); decorator_ = new (graph()->zone()) WasmDecorator(node_origins, decoder); graph()->AddDecorator(decorator_); } void WasmGraphBuilder::RemoveBytecodePositionDecorator() { DCHECK_NOT_NULL(decorator_); graph()->RemoveDecorator(decorator_); decorator_ = nullptr; } namespace { bool must_record_function_compilation(Isolate* isolate) { return isolate->logger()->is_listening_to_code_events() || isolate->is_profiling(); } PRINTF_FORMAT(4, 5) void RecordFunctionCompilation(CodeEventListener::LogEventsAndTags tag, Isolate* isolate, Handle<Code> code, const char* format, ...) { DCHECK(must_record_function_compilation(isolate)); ScopedVector<char> buffer(128); va_list arguments; va_start(arguments, format); int len = VSNPrintF(buffer, format, arguments); CHECK_LT(0, len); va_end(arguments); Handle<String> name_str = isolate->factory()->NewStringFromAsciiChecked(buffer.start()); PROFILE(isolate, CodeCreateEvent(tag, AbstractCode::cast(*code), *name_str)); } class WasmWrapperGraphBuilder : public WasmGraphBuilder { public: WasmWrapperGraphBuilder(Zone* zone, JSGraph* jsgraph, wasm::FunctionSig* sig, compiler::SourcePositionTable* spt, StubCallMode stub_mode, wasm::WasmFeatures features) : WasmGraphBuilder(nullptr, zone, jsgraph, sig, spt), isolate_(jsgraph->isolate()), jsgraph_(jsgraph), stub_mode_(stub_mode), enabled_features_(features) {} Node* BuildAllocateHeapNumberWithValue(Node* value, Node* control) { MachineOperatorBuilder* machine = mcgraph()->machine(); CommonOperatorBuilder* common = mcgraph()->common(); Node* target = (stub_mode_ == StubCallMode::kCallWasmRuntimeStub) ? mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmAllocateHeapNumber, RelocInfo::WASM_STUB_CALL) : jsgraph()->HeapConstant( BUILTIN_CODE(isolate_, AllocateHeapNumber)); if (!allocate_heap_number_operator_.is_set()) { auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), AllocateHeapNumberDescriptor(), 0, CallDescriptor::kNoFlags, Operator::kNoThrow, stub_mode_); allocate_heap_number_operator_.set(common->Call(call_descriptor)); } Node* heap_number = graph()->NewNode(allocate_heap_number_operator_.get(), target, Effect(), control); SetEffect( graph()->NewNode(machine->Store(StoreRepresentation( MachineRepresentation::kFloat64, kNoWriteBarrier)), heap_number, BuildHeapNumberValueIndexConstant(), value, heap_number, control)); return heap_number; } Node* BuildChangeSmiToFloat64(Node* value) { return graph()->NewNode(mcgraph()->machine()->ChangeInt32ToFloat64(), BuildChangeSmiToInt32(value)); } Node* BuildTestHeapObject(Node* value) { return graph()->NewNode(mcgraph()->machine()->WordAnd(), value, mcgraph()->IntPtrConstant(kHeapObjectTag)); } Node* BuildLoadHeapNumberValue(Node* value) { return SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Float64()), value, BuildHeapNumberValueIndexConstant(), Effect(), Control())); } Node* BuildHeapNumberValueIndexConstant() { return mcgraph()->IntPtrConstant(HeapNumber::kValueOffset - kHeapObjectTag); } Node* BuildChangeInt32ToTagged(Node* value) { MachineOperatorBuilder* machine = mcgraph()->machine(); CommonOperatorBuilder* common = mcgraph()->common(); if (SmiValuesAre32Bits()) { return BuildChangeInt32ToSmi(value); } DCHECK(SmiValuesAre31Bits()); Node* effect = Effect(); Node* control = Control(); Node* add = graph()->NewNode(machine->Int32AddWithOverflow(), value, value, graph()->start()); Node* ovf = graph()->NewNode(common->Projection(1), add, graph()->start()); Node* branch = graph()->NewNode(common->Branch(BranchHint::kFalse), ovf, control); Node* if_true = graph()->NewNode(common->IfTrue(), branch); Node* vtrue = BuildAllocateHeapNumberWithValue( graph()->NewNode(machine->ChangeInt32ToFloat64(), value), if_true); Node* etrue = Effect(); Node* if_false = graph()->NewNode(common->IfFalse(), branch); Node* vfalse = graph()->NewNode(common->Projection(0), add, if_false); vfalse = BuildChangeInt32ToIntPtr(vfalse); Node* merge = SetControl(graph()->NewNode(common->Merge(2), if_true, if_false)); SetEffect(graph()->NewNode(common->EffectPhi(2), etrue, effect, merge)); return graph()->NewNode(common->Phi(MachineRepresentation::kTagged, 2), vtrue, vfalse, merge); } Node* BuildChangeFloat64ToTagged(Node* value) { MachineOperatorBuilder* machine = mcgraph()->machine(); CommonOperatorBuilder* common = mcgraph()->common(); // Check several conditions: // i32? // ├─ true: zero? // │ ├─ true: negative? // │ │ ├─ true: box // │ │ └─ false: potentially Smi // │ └─ false: potentially Smi // └─ false: box // For potential Smi values, depending on whether Smis are 31 or 32 bit, we // still need to check whether the value fits in a Smi. Node* effect = Effect(); Node* control = Control(); Node* value32 = graph()->NewNode(machine->RoundFloat64ToInt32(), value); Node* check_i32 = graph()->NewNode( machine->Float64Equal(), value, graph()->NewNode(machine->ChangeInt32ToFloat64(), value32)); Node* branch_i32 = graph()->NewNode(common->Branch(), check_i32, control); Node* if_i32 = graph()->NewNode(common->IfTrue(), branch_i32); Node* if_not_i32 = graph()->NewNode(common->IfFalse(), branch_i32); // We only need to check for -0 if the {value} can potentially contain -0. Node* check_zero = graph()->NewNode(machine->Word32Equal(), value32, mcgraph()->Int32Constant(0)); Node* branch_zero = graph()->NewNode(common->Branch(BranchHint::kFalse), check_zero, if_i32); Node* if_zero = graph()->NewNode(common->IfTrue(), branch_zero); Node* if_not_zero = graph()->NewNode(common->IfFalse(), branch_zero); // In case of 0, we need to check the high bits for the IEEE -0 pattern. Node* check_negative = graph()->NewNode( machine->Int32LessThan(), graph()->NewNode(machine->Float64ExtractHighWord32(), value), mcgraph()->Int32Constant(0)); Node* branch_negative = graph()->NewNode(common->Branch(BranchHint::kFalse), check_negative, if_zero); Node* if_negative = graph()->NewNode(common->IfTrue(), branch_negative); Node* if_not_negative = graph()->NewNode(common->IfFalse(), branch_negative); // We need to create a box for negative 0. Node* if_smi = graph()->NewNode(common->Merge(2), if_not_zero, if_not_negative); Node* if_box = graph()->NewNode(common->Merge(2), if_not_i32, if_negative); // On 64-bit machines we can just wrap the 32-bit integer in a smi, for // 32-bit machines we need to deal with potential overflow and fallback to // boxing. Node* vsmi; if (SmiValuesAre32Bits()) { vsmi = BuildChangeInt32ToSmi(value32); } else { DCHECK(SmiValuesAre31Bits()); Node* smi_tag = graph()->NewNode(machine->Int32AddWithOverflow(), value32, value32, if_smi); Node* check_ovf = graph()->NewNode(common->Projection(1), smi_tag, if_smi); Node* branch_ovf = graph()->NewNode(common->Branch(BranchHint::kFalse), check_ovf, if_smi); Node* if_ovf = graph()->NewNode(common->IfTrue(), branch_ovf); if_box = graph()->NewNode(common->Merge(2), if_ovf, if_box); if_smi = graph()->NewNode(common->IfFalse(), branch_ovf); vsmi = graph()->NewNode(common->Projection(0), smi_tag, if_smi); vsmi = BuildChangeInt32ToIntPtr(vsmi); } // Allocate the box for the {value}. Node* vbox = BuildAllocateHeapNumberWithValue(value, if_box); Node* ebox = Effect(); Node* merge = SetControl(graph()->NewNode(common->Merge(2), if_smi, if_box)); SetEffect(graph()->NewNode(common->EffectPhi(2), effect, ebox, merge)); return graph()->NewNode(common->Phi(MachineRepresentation::kTagged, 2), vsmi, vbox, merge); } int AddArgumentNodes(Node** args, int pos, int param_count, wasm::FunctionSig* sig) { // Convert wasm numbers to JS values. for (int i = 0; i < param_count; ++i) { Node* param = Param(i + 1); // Start from index 1 to drop the instance_node. args[pos++] = ToJS(param, sig->GetParam(i)); } return pos; } Node* BuildJavaScriptToNumber(Node* node, Node* js_context) { auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), TypeConversionDescriptor{}, 0, CallDescriptor::kNoFlags, Operator::kNoProperties, stub_mode_); Node* stub_code = (stub_mode_ == StubCallMode::kCallWasmRuntimeStub) ? mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmToNumber, RelocInfo::WASM_STUB_CALL) : jsgraph()->HeapConstant(BUILTIN_CODE(isolate_, ToNumber)); Node* result = SetEffect( graph()->NewNode(mcgraph()->common()->Call(call_descriptor), stub_code, node, js_context, Effect(), Control())); SetSourcePosition(result, 1); return result; } Node* BuildChangeTaggedToFloat64(Node* value) { MachineOperatorBuilder* machine = mcgraph()->machine(); CommonOperatorBuilder* common = mcgraph()->common(); // Implement the following decision tree: // heap object? // ├─ true: undefined? // │ ├─ true: f64 const // │ └─ false: load heap number value // └─ false: smi to float64 Node* check_heap_object = BuildTestHeapObject(value); Diamond is_heap_object(graph(), common, check_heap_object, BranchHint::kFalse); is_heap_object.Chain(Control()); SetControl(is_heap_object.if_true); Node* orig_effect = Effect(); Node* undefined_node = LOAD_INSTANCE_FIELD(UndefinedValue, MachineType::TaggedPointer()); Node* check_undefined = graph()->NewNode(machine->WordEqual(), value, undefined_node); Node* effect_tagged = Effect(); Diamond is_undefined(graph(), common, check_undefined, BranchHint::kFalse); is_undefined.Nest(is_heap_object, true); SetControl(is_undefined.if_false); Node* vheap_number = BuildLoadHeapNumberValue(value); Node* effect_undefined = Effect(); SetControl(is_undefined.merge); Node* vundefined = mcgraph()->Float64Constant(std::numeric_limits<double>::quiet_NaN()); Node* vtagged = is_undefined.Phi(MachineRepresentation::kFloat64, vundefined, vheap_number); effect_tagged = is_undefined.EffectPhi(effect_tagged, effect_undefined); // If input is Smi: just convert to float64. Node* vfrom_smi = BuildChangeSmiToFloat64(value); SetControl(is_heap_object.merge); SetEffect(is_heap_object.EffectPhi(effect_tagged, orig_effect)); return is_heap_object.Phi(MachineRepresentation::kFloat64, vtagged, vfrom_smi); } Node* ToJS(Node* node, wasm::ValueType type) { switch (type) { case wasm::kWasmI32: return BuildChangeInt32ToTagged(node); case wasm::kWasmS128: UNREACHABLE(); case wasm::kWasmI64: { DCHECK(enabled_features_.bigint); return BuildChangeInt64ToBigInt(node); } case wasm::kWasmF32: node = graph()->NewNode(mcgraph()->machine()->ChangeFloat32ToFloat64(), node); return BuildChangeFloat64ToTagged(node); case wasm::kWasmF64: return BuildChangeFloat64ToTagged(node); case wasm::kWasmAnyRef: return node; default: UNREACHABLE(); } } Node* BuildChangeInt64ToBigInt(Node* input) { BigIntToWasmI64Descriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), // zone interface_descriptor, // descriptor interface_descriptor.GetStackParameterCount(), // stack parameter count CallDescriptor::kNoFlags, // flags Operator::kNoProperties, // properties stub_mode_); // stub call mode Node* target = (stub_mode_ == StubCallMode::kCallWasmRuntimeStub) ? mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kBigIntToWasmI64, RelocInfo::WASM_STUB_CALL) : jsgraph()->HeapConstant(BUILTIN_CODE(isolate_, I64ToBigInt)); return SetEffect( SetControl(graph()->NewNode(mcgraph()->common()->Call(call_descriptor), target, input, Effect(), Control()))); } Node* BuildChangeBigIntToInt64(Node* input, Node* context) { BigIntToI64Descriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), // zone interface_descriptor, // descriptor interface_descriptor.GetStackParameterCount(), // stack parameter count CallDescriptor::kNoFlags, // flags Operator::kNoProperties, // properties stub_mode_); // stub call mode Node* target = (stub_mode_ == StubCallMode::kCallWasmRuntimeStub) ? mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmBigIntToI64, RelocInfo::WASM_STUB_CALL) : jsgraph()->HeapConstant(BUILTIN_CODE(isolate_, BigIntToI64)); return SetEffect(SetControl( graph()->NewNode(mcgraph()->common()->Call(call_descriptor), target, input, context, Effect(), Control()))); } Node* FromJS(Node* node, Node* js_context, wasm::ValueType type) { DCHECK_NE(wasm::kWasmStmt, type); // The parameter is of type AnyRef, we take it as is. if (type == wasm::kWasmAnyRef) { return node; } Node* num = nullptr; if (type != wasm::kWasmI64) { // Do a JavaScript ToNumber. num = BuildJavaScriptToNumber(node, js_context); // Change representation. num = BuildChangeTaggedToFloat64(num); } switch (type) { case wasm::kWasmI32: { num = graph()->NewNode(mcgraph()->machine()->TruncateFloat64ToWord32(), num); break; } case wasm::kWasmI64: { DCHECK(enabled_features_.bigint); num = BuildChangeBigIntToInt64(node, js_context); break; } case wasm::kWasmF32: num = graph()->NewNode(mcgraph()->machine()->TruncateFloat64ToFloat32(), num); break; case wasm::kWasmF64: break; case wasm::kWasmS128: UNREACHABLE(); default: UNREACHABLE(); } DCHECK_NOT_NULL(num); return num; } void BuildModifyThreadInWasmFlag(bool new_value) { if (!trap_handler::IsTrapHandlerEnabled()) return; Node* isolate_root = LOAD_INSTANCE_FIELD(IsolateRoot, MachineType::Pointer()); Node* thread_in_wasm_flag_address = LOAD_RAW(isolate_root, Isolate::thread_in_wasm_flag_address_offset(), MachineType::Pointer()); if (FLAG_debug_code) { Node* flag_value = SetEffect( graph()->NewNode(mcgraph()->machine()->Load(MachineType::Pointer()), thread_in_wasm_flag_address, mcgraph()->Int32Constant(0), Effect(), Control())); Node* check = graph()->NewNode(mcgraph()->machine()->Word32Equal(), flag_value, mcgraph()->Int32Constant(new_value ? 0 : 1)); Diamond flag_check(graph(), mcgraph()->common(), check, BranchHint::kTrue); flag_check.Chain(Control()); Node* message_id = jsgraph()->SmiConstant(static_cast<int32_t>( new_value ? AbortReason::kUnexpectedThreadInWasmSet : AbortReason::kUnexpectedThreadInWasmUnset)); Node* effect = Effect(); BuildCallToRuntimeWithContext(Runtime::kAbort, NoContextConstant(), &message_id, 1, &effect, flag_check.if_false); SetEffect(flag_check.EffectPhi(Effect(), effect)); SetControl(flag_check.merge); } SetEffect(graph()->NewNode( mcgraph()->machine()->Store(StoreRepresentation( MachineRepresentation::kWord32, kNoWriteBarrier)), thread_in_wasm_flag_address, mcgraph()->Int32Constant(0), mcgraph()->Int32Constant(new_value ? 1 : 0), Effect(), Control())); } Node* BuildLoadFunctionDataFromExportedFunction(Node* closure) { Node* shared = SetEffect(graph()->NewNode( jsgraph()->machine()->Load(MachineType::AnyTagged()), closure, jsgraph()->Int32Constant( wasm::ObjectAccess::SharedFunctionInfoOffsetInTaggedJSFunction()), Effect(), Control())); return SetEffect(graph()->NewNode( jsgraph()->machine()->Load(MachineType::AnyTagged()), shared, jsgraph()->Int32Constant(SharedFunctionInfo::kFunctionDataOffset - kHeapObjectTag), Effect(), Control())); } Node* BuildLoadInstanceFromExportedFunctionData(Node* function_data) { return SetEffect(graph()->NewNode( jsgraph()->machine()->Load(MachineType::AnyTagged()), function_data, jsgraph()->Int32Constant(WasmExportedFunctionData::kInstanceOffset - kHeapObjectTag), Effect(), Control())); } Node* BuildLoadFunctionIndexFromExportedFunctionData(Node* function_data) { Node* function_index_smi = SetEffect(graph()->NewNode( jsgraph()->machine()->Load(MachineType::AnyTagged()), function_data, jsgraph()->Int32Constant( WasmExportedFunctionData::kFunctionIndexOffset - kHeapObjectTag), Effect(), Control())); Node* function_index = BuildChangeSmiToInt32(function_index_smi); return function_index; } Node* BuildLoadJumpTableOffsetFromExportedFunctionData(Node* function_data) { Node* jump_table_offset_smi = SetEffect(graph()->NewNode( jsgraph()->machine()->Load(MachineType::AnyTagged()), function_data, jsgraph()->Int32Constant( WasmExportedFunctionData::kJumpTableOffsetOffset - kHeapObjectTag), Effect(), Control())); Node* jump_table_offset = BuildChangeSmiToInt32(jump_table_offset_smi); return jump_table_offset; } void BuildJSToWasmWrapper(bool is_import) { const int wasm_count = static_cast<int>(sig_->parameter_count()); // Build the start and the JS parameter nodes. SetEffect(SetControl(Start(wasm_count + 5))); // Create the js_closure and js_context parameters. Node* js_closure = graph()->NewNode(jsgraph()->common()->Parameter( Linkage::kJSCallClosureParamIndex, "%closure"), graph()->start()); Node* js_context = graph()->NewNode( mcgraph()->common()->Parameter( Linkage::GetJSCallContextParamIndex(wasm_count + 1), "%context"), graph()->start()); // Create the instance_node node to pass as parameter. It is loaded from // an actual reference to an instance or a placeholder reference, // called {WasmExportedFunction} via the {WasmExportedFunctionData} // structure. Node* function_data = BuildLoadFunctionDataFromExportedFunction(js_closure); instance_node_.set( BuildLoadInstanceFromExportedFunctionData(function_data)); if (!wasm::IsJSCompatibleSignature(sig_, enabled_features_.bigint)) { // Throw a TypeError. Use the js_context of the calling javascript // function (passed as a parameter), such that the generated code is // js_context independent. BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, js_context, nullptr, 0, effect_, Control()); Return(jsgraph()->SmiConstant(0)); return; } const int args_count = wasm_count + 1; // +1 for wasm_code. Node** args = Buffer(args_count); Node** rets; // Convert JS parameters to wasm numbers. for (int i = 0; i < wasm_count; ++i) { Node* param = Param(i + 1); Node* wasm_param = FromJS(param, js_context, sig_->GetParam(i)); args[i + 1] = wasm_param; } // Set the ThreadInWasm flag before we do the actual call. BuildModifyThreadInWasmFlag(true); if (is_import) { // Call to an imported function. // Load function index from {WasmExportedFunctionData}. Node* function_index = BuildLoadFunctionIndexFromExportedFunctionData(function_data); BuildImportCall(sig_, args, &rets, wasm::kNoCodePosition, function_index); } else { // Call to a wasm function defined in this module. // The call target is the jump table slot for that function. Node* jump_table_start = LOAD_INSTANCE_FIELD(JumpTableStart, MachineType::Pointer()); Node* jump_table_offset = BuildLoadJumpTableOffsetFromExportedFunctionData(function_data); Node* jump_table_slot = graph()->NewNode( mcgraph()->machine()->IntAdd(), jump_table_start, jump_table_offset); args[0] = jump_table_slot; BuildWasmCall(sig_, args, &rets, wasm::kNoCodePosition, nullptr, kNoRetpoline); } // Clear the ThreadInWasm flag. BuildModifyThreadInWasmFlag(false); Node* jsval = sig_->return_count() == 0 ? jsgraph()->UndefinedConstant() : ToJS(rets[0], sig_->GetReturn()); Return(jsval); } bool BuildWasmImportCallWrapper(WasmImportCallKind kind) { int wasm_count = static_cast<int>(sig_->parameter_count()); // Build the start and the parameter nodes. SetEffect(SetControl(Start(wasm_count + 4))); instance_node_.set(Param(wasm::kWasmInstanceParameterIndex)); Node* native_context = LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer()); if (kind == WasmImportCallKind::kRuntimeTypeError) { // ======================================================================= // === Runtime TypeError ================================================= // ======================================================================= BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, native_context, nullptr, 0, effect_, Control()); // We don't need to return a value here, as the runtime call will not // return anyway (the c entry stub will trigger stack unwinding). ReturnVoid(); return false; } // The callable is passed as the last parameter, after WASM arguments. Node* callable_node = Param(wasm_count + 1); Node* undefined_node = LOAD_INSTANCE_FIELD(UndefinedValue, MachineType::TaggedPointer()); Node* call = nullptr; bool sloppy_receiver = true; // Clear the ThreadInWasm flag. BuildModifyThreadInWasmFlag(false); switch (kind) { // ======================================================================= // === JS Functions with matching arity ================================== // ======================================================================= case WasmImportCallKind::kJSFunctionArityMatch: sloppy_receiver = false; V8_FALLTHROUGH; // fallthru case WasmImportCallKind::kJSFunctionArityMatchSloppy: { Node** args = Buffer(wasm_count + 9); int pos = 0; Node* function_context = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::TaggedPointer()), callable_node, mcgraph()->Int32Constant( wasm::ObjectAccess::ContextOffsetInTaggedJSFunction()), Effect(), Control())); args[pos++] = callable_node; // target callable. // Receiver. if (sloppy_receiver) { Node* global_proxy = LOAD_FIXED_ARRAY_SLOT_PTR( native_context, Context::GLOBAL_PROXY_INDEX); args[pos++] = global_proxy; } else { args[pos++] = undefined_node; } auto call_descriptor = Linkage::GetJSCallDescriptor( graph()->zone(), false, wasm_count + 1, CallDescriptor::kNoFlags); // Convert wasm numbers to JS values. pos = AddArgumentNodes(args, pos, wasm_count, sig_); args[pos++] = undefined_node; // new target args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count args[pos++] = function_context; args[pos++] = Effect(); args[pos++] = Control(); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args); break; } // ======================================================================= // === JS Functions with arguments adapter =============================== // ======================================================================= case WasmImportCallKind::kJSFunctionArityMismatch: sloppy_receiver = false; V8_FALLTHROUGH; // fallthru case WasmImportCallKind::kJSFunctionArityMismatchSloppy: { Node** args = Buffer(wasm_count + 9); int pos = 0; Node* function_context = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::TaggedPointer()), callable_node, mcgraph()->Int32Constant( wasm::ObjectAccess::ContextOffsetInTaggedJSFunction()), Effect(), Control())); args[pos++] = BuildLoadBuiltinFromInstance(Builtins::kArgumentsAdaptorTrampoline); args[pos++] = callable_node; // target callable args[pos++] = undefined_node; // new target args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count // Load shared function info, and then the formal parameter count. Node* shared_function_info = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::TaggedPointer()), callable_node, mcgraph()->Int32Constant( wasm::ObjectAccess:: SharedFunctionInfoOffsetInTaggedJSFunction()), Effect(), Control())); Node* formal_param_count = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Uint16()), shared_function_info, mcgraph()->Int32Constant( wasm::ObjectAccess:: FormalParameterCountOffsetInSharedFunctionInfo()), Effect(), Control())); args[pos++] = formal_param_count; // Receiver. if (sloppy_receiver) { Node* global_proxy = LOAD_FIXED_ARRAY_SLOT_PTR( native_context, Context::GLOBAL_PROXY_INDEX); args[pos++] = global_proxy; } else { args[pos++] = undefined_node; } #ifdef V8_TARGET_ARCH_IA32 // TODO(v8:6666): Remove kAllowCallThroughSlot and use a pc-relative // call instead once builtins are embedded in every build configuration. CallDescriptor::Flags flags = CallDescriptor::kAllowCallThroughSlot; #else CallDescriptor::Flags flags = CallDescriptor::kNoFlags; #endif auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), ArgumentsAdaptorDescriptor{}, 1 + wasm_count, flags, Operator::kNoProperties); // Convert wasm numbers to JS values. pos = AddArgumentNodes(args, pos, wasm_count, sig_); args[pos++] = function_context; args[pos++] = Effect(); args[pos++] = Control(); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args); break; } // ======================================================================= // === General case of unknown callable ================================== // ======================================================================= case WasmImportCallKind::kUseCallBuiltin: { Node** args = Buffer(wasm_count + 9); int pos = 0; args[pos++] = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmCallJavaScript, RelocInfo::WASM_STUB_CALL); args[pos++] = callable_node; args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count args[pos++] = undefined_node; // receiver auto call_descriptor = Linkage::GetStubCallDescriptor( graph()->zone(), CallTrampolineDescriptor{}, wasm_count + 1, CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); // Convert wasm numbers to JS values. pos = AddArgumentNodes(args, pos, wasm_count, sig_); // The native_context is sufficient here, because all kind of callables // which depend on the context provide their own context. The context // here is only needed if the target is a constructor to throw a // TypeError, if the target is a native function, or if the target is a // callable JSObject, which can only be constructed by the runtime. args[pos++] = native_context; args[pos++] = Effect(); args[pos++] = Control(); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args); break; } default: UNREACHABLE(); } DCHECK_NOT_NULL(call); SetEffect(call); SetSourcePosition(call, 0); // Convert the return value back. Node* val = sig_->return_count() == 0 ? mcgraph()->Int32Constant(0) : FromJS(call, native_context, sig_->GetReturn()); // Set the ThreadInWasm flag again. BuildModifyThreadInWasmFlag(true); Return(val); return true; } void BuildWasmInterpreterEntry(uint32_t func_index) { int param_count = static_cast<int>(sig_->parameter_count()); // Build the start and the parameter nodes. SetEffect(SetControl(Start(param_count + 3))); // Create the instance_node from the passed parameter. instance_node_.set(Param(wasm::kWasmInstanceParameterIndex)); // Compute size for the argument buffer. int args_size_bytes = 0; for (wasm::ValueType type : sig_->parameters()) { args_size_bytes += wasm::ValueTypes::ElementSizeInBytes(type); } // The return value is also passed via this buffer: DCHECK_GE(wasm::kV8MaxWasmFunctionReturns, sig_->return_count()); // TODO(wasm): Handle multi-value returns. DCHECK_EQ(1, wasm::kV8MaxWasmFunctionReturns); int return_size_bytes = sig_->return_count() == 0 ? 0 : wasm::ValueTypes::ElementSizeInBytes(sig_->GetReturn()); // Get a stack slot for the arguments. Node* arg_buffer = args_size_bytes == 0 && return_size_bytes == 0 ? mcgraph()->IntPtrConstant(0) : graph()->NewNode(mcgraph()->machine()->StackSlot( std::max(args_size_bytes, return_size_bytes), 8)); // Now store all our arguments to the buffer. int offset = 0; for (int i = 0; i < param_count; ++i) { wasm::ValueType type = sig_->GetParam(i); // Start from the parameter with index 1 to drop the instance_node. SetEffect(graph()->NewNode(GetSafeStoreOperator(offset, type), arg_buffer, Int32Constant(offset), Param(i + 1), Effect(), Control())); offset += wasm::ValueTypes::ElementSizeInBytes(type); } DCHECK_EQ(args_size_bytes, offset); // We are passing the raw arg_buffer here. To the GC and other parts, it // looks like a Smi (lowest bit not set). In the runtime function however, // don't call Smi::value on it, but just cast it to a byte pointer. Node* parameters[] = {jsgraph()->SmiConstant(func_index), arg_buffer}; BuildCallToRuntime(Runtime::kWasmRunInterpreter, parameters, arraysize(parameters)); // Read back the return value. if (sig_->return_count() == 0) { Return(Int32Constant(0)); } else { // TODO(wasm): Implement multi-return. DCHECK_EQ(1, sig_->return_count()); MachineType load_rep = wasm::ValueTypes::MachineTypeFor(sig_->GetReturn()); Node* val = SetEffect( graph()->NewNode(mcgraph()->machine()->Load(load_rep), arg_buffer, Int32Constant(0), Effect(), Control())); Return(val); } if (ContainsInt64(sig_)) LowerInt64(); } void BuildCWasmEntry() { // Build the start and the JS parameter nodes. SetEffect(SetControl(Start(CWasmEntryParameters::kNumParameters + 5))); // Create parameter nodes (offset by 1 for the receiver parameter). Node* code_entry = Param(CWasmEntryParameters::kCodeEntry + 1); Node* object_ref_node = Param(CWasmEntryParameters::kObjectRef + 1); Node* arg_buffer = Param(CWasmEntryParameters::kArgumentsBuffer + 1); int wasm_arg_count = static_cast<int>(sig_->parameter_count()); int arg_count = wasm_arg_count + 4; // code, object_ref_node, control, effect Node** args = Buffer(arg_count); int pos = 0; args[pos++] = code_entry; args[pos++] = object_ref_node; int offset = 0; for (wasm::ValueType type : sig_->parameters()) { Node* arg_load = SetEffect( graph()->NewNode(GetSafeLoadOperator(offset, type), arg_buffer, Int32Constant(offset), Effect(), Control())); args[pos++] = arg_load; offset += wasm::ValueTypes::ElementSizeInBytes(type); } args[pos++] = Effect(); args[pos++] = Control(); DCHECK_EQ(arg_count, pos); // Call the wasm code. auto call_descriptor = GetWasmCallDescriptor(mcgraph()->zone(), sig_); Node* call = SetEffect(graph()->NewNode( mcgraph()->common()->Call(call_descriptor), arg_count, args)); // Store the return value. DCHECK_GE(1, sig_->return_count()); if (sig_->return_count() == 1) { StoreRepresentation store_rep( wasm::ValueTypes::MachineRepresentationFor(sig_->GetReturn()), kNoWriteBarrier); SetEffect(graph()->NewNode(mcgraph()->machine()->Store(store_rep), arg_buffer, Int32Constant(0), call, Effect(), Control())); } Return(jsgraph()->SmiConstant(0)); if (mcgraph()->machine()->Is32() && ContainsInt64(sig_)) { MachineRepresentation sig_reps[] = { MachineRepresentation::kWord32, // return value MachineRepresentation::kTagged, // receiver MachineRepresentation::kTagged, // arg0 (code) MachineRepresentation::kTagged // arg1 (buffer) }; Signature<MachineRepresentation> c_entry_sig(1, 2, sig_reps); Int64Lowering r(mcgraph()->graph(), mcgraph()->machine(), mcgraph()->common(), mcgraph()->zone(), &c_entry_sig); r.LowerGraph(); } } JSGraph* jsgraph() { return jsgraph_; } private: Isolate* const isolate_; JSGraph* jsgraph_; StubCallMode stub_mode_; SetOncePointer<const Operator> allocate_heap_number_operator_; wasm::WasmFeatures enabled_features_; }; void AppendSignature(char* buffer, size_t max_name_len, wasm::FunctionSig* sig) { size_t name_len = strlen(buffer); auto append_name_char = [&](char c) { if (name_len + 1 < max_name_len) buffer[name_len++] = c; }; for (wasm::ValueType t : sig->parameters()) { append_name_char(wasm::ValueTypes::ShortNameOf(t)); } append_name_char(':'); for (wasm::ValueType t : sig->returns()) { append_name_char(wasm::ValueTypes::ShortNameOf(t)); } buffer[name_len] = '\0'; } } // namespace MaybeHandle<Code> CompileJSToWasmWrapper(Isolate* isolate, wasm::FunctionSig* sig, bool is_import) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm"), "CompileJSToWasmWrapper"); //---------------------------------------------------------------------------- // Create the Graph. //---------------------------------------------------------------------------- Zone zone(isolate->allocator(), ZONE_NAME); Graph graph(&zone); CommonOperatorBuilder common(&zone); MachineOperatorBuilder machine( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); JSGraph jsgraph(isolate, &graph, &common, nullptr, nullptr, &machine); Node* control = nullptr; Node* effect = nullptr; WasmWrapperGraphBuilder builder(&zone, &jsgraph, sig, nullptr, StubCallMode::kCallCodeObject, wasm::WasmFeaturesFromIsolate(isolate)); builder.set_control_ptr(&control); builder.set_effect_ptr(&effect); builder.BuildJSToWasmWrapper(is_import); //---------------------------------------------------------------------------- // Run the compilation pipeline. //---------------------------------------------------------------------------- static constexpr size_t kMaxNameLen = 128; char debug_name[kMaxNameLen] = "js_to_wasm:"; AppendSignature(debug_name, kMaxNameLen, sig); // Schedule and compile to machine code. int params = static_cast<int>(sig->parameter_count()); CallDescriptor* incoming = Linkage::GetJSCallDescriptor( &zone, false, params + 1, CallDescriptor::kNoFlags); MaybeHandle<Code> maybe_code = Pipeline::GenerateCodeForWasmHeapStub( isolate, incoming, &graph, Code::JS_TO_WASM_FUNCTION, debug_name, WasmAssemblerOptions()); Handle<Code> code; if (!maybe_code.ToHandle(&code)) { return maybe_code; } #ifdef ENABLE_DISASSEMBLER if (FLAG_print_opt_code) { CodeTracer::Scope tracing_scope(isolate->GetCodeTracer()); OFStream os(tracing_scope.file()); code->Disassemble(debug_name, os); } #endif if (must_record_function_compilation(isolate)) { RecordFunctionCompilation(CodeEventListener::STUB_TAG, isolate, code, "%s", debug_name); } return code; } WasmImportCallKind GetWasmImportCallKind(Handle<JSReceiver> target, wasm::FunctionSig* expected_sig, bool has_bigint_feature) { if (WasmExportedFunction::IsWasmExportedFunction(*target)) { auto imported_function = WasmExportedFunction::cast(*target); wasm::FunctionSig* imported_sig = imported_function->instance() ->module() ->functions[imported_function->function_index()] .sig; if (*imported_sig != *expected_sig) { return WasmImportCallKind::kLinkError; } return WasmImportCallKind::kWasmToWasm; } // Assuming we are calling to JS, check whether this would be a runtime error. if (!wasm::IsJSCompatibleSignature(expected_sig, has_bigint_feature)) { return WasmImportCallKind::kRuntimeTypeError; } // For JavaScript calls, determine whether the target has an arity match // and whether it has a sloppy receiver. if (target->IsJSFunction()) { Handle<JSFunction> function = Handle<JSFunction>::cast(target); SharedFunctionInfo shared = function->shared(); // Check for math intrinsics. #define COMPARE_SIG_FOR_BUILTIN(name) \ { \ wasm::FunctionSig* sig = wasm::WasmOpcodes::Signature(wasm::kExpr##name); \ if (!sig) sig = wasm::WasmOpcodes::AsmjsSignature(wasm::kExpr##name); \ DCHECK_NOT_NULL(sig); \ if (*expected_sig == *sig) return WasmImportCallKind::k##name; \ } #define COMPARE_SIG_FOR_BUILTIN_F64(name) \ case Builtins::kMath##name: \ COMPARE_SIG_FOR_BUILTIN(F64##name); \ break; #define COMPARE_SIG_FOR_BUILTIN_F32_F64(name) \ case Builtins::kMath##name: \ COMPARE_SIG_FOR_BUILTIN(F64##name); \ COMPARE_SIG_FOR_BUILTIN(F32##name); \ break; if (FLAG_wasm_math_intrinsics && shared->HasBuiltinId()) { switch (shared->builtin_id()) { COMPARE_SIG_FOR_BUILTIN_F64(Acos); COMPARE_SIG_FOR_BUILTIN_F64(Asin); COMPARE_SIG_FOR_BUILTIN_F64(Atan); COMPARE_SIG_FOR_BUILTIN_F64(Cos); COMPARE_SIG_FOR_BUILTIN_F64(Sin); COMPARE_SIG_FOR_BUILTIN_F64(Tan); COMPARE_SIG_FOR_BUILTIN_F64(Exp); COMPARE_SIG_FOR_BUILTIN_F64(Log); COMPARE_SIG_FOR_BUILTIN_F64(Atan2); //=========================================================== // TODO(8505): Math.pow for wasm does not match JS. // COMPARE_SIG_FOR_BUILTIN_F64(Pow); //=========================================================== COMPARE_SIG_FOR_BUILTIN_F32_F64(Min); COMPARE_SIG_FOR_BUILTIN_F32_F64(Max); COMPARE_SIG_FOR_BUILTIN_F32_F64(Abs); COMPARE_SIG_FOR_BUILTIN_F32_F64(Ceil); COMPARE_SIG_FOR_BUILTIN_F32_F64(Floor); COMPARE_SIG_FOR_BUILTIN_F32_F64(Sqrt); case Builtins::kMathFround: COMPARE_SIG_FOR_BUILTIN(F32ConvertF64); break; default: break; } } #undef COMPARE_SIG_FOR_BUILTIN #undef COMPARE_SIG_FOR_BUILTIN_F64 #undef COMPARE_SIG_FOR_BUILTIN_F32_F64 if (IsClassConstructor(shared->kind())) { // Class constructor will throw anyway. return WasmImportCallKind::kUseCallBuiltin; } bool sloppy = is_sloppy(shared->language_mode()) && !shared->native(); if (shared->internal_formal_parameter_count() == expected_sig->parameter_count()) { return sloppy ? WasmImportCallKind::kJSFunctionArityMatchSloppy : WasmImportCallKind::kJSFunctionArityMatch; } return sloppy ? WasmImportCallKind::kJSFunctionArityMismatchSloppy : WasmImportCallKind::kJSFunctionArityMismatch; } // Unknown case. Use the call builtin. return WasmImportCallKind::kUseCallBuiltin; } wasm::WasmOpcode GetMathIntrinsicOpcode(WasmImportCallKind kind, const char** name_ptr) { #define CASE(name) \ case WasmImportCallKind::k##name: \ *name_ptr = "WasmMathIntrinsic:" #name; \ return wasm::kExpr##name switch (kind) { CASE(F64Acos); CASE(F64Asin); CASE(F64Atan); CASE(F64Cos); CASE(F64Sin); CASE(F64Tan); CASE(F64Exp); CASE(F64Log); CASE(F64Atan2); CASE(F64Pow); CASE(F64Ceil); CASE(F64Floor); CASE(F64Sqrt); CASE(F64Min); CASE(F64Max); CASE(F64Abs); CASE(F32Min); CASE(F32Max); CASE(F32Abs); CASE(F32Ceil); CASE(F32Floor); CASE(F32Sqrt); CASE(F32ConvertF64); default: UNREACHABLE(); return wasm::kExprUnreachable; } #undef CASE } wasm::WasmCode* CompileWasmMathIntrinsic(wasm::WasmEngine* wasm_engine, wasm::NativeModule* native_module, WasmImportCallKind kind, wasm::FunctionSig* sig) { DCHECK_EQ(1, sig->return_count()); TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm"), "CompileWasmMathIntrinsic"); Zone zone(wasm_engine->allocator(), ZONE_NAME); // Compile a WASM function with a single bytecode and let TurboFan // generate either inlined machine code or a call to a helper. SourcePositionTable* source_positions = nullptr; MachineGraph* mcgraph = new (&zone) MachineGraph( new (&zone) Graph(&zone), new (&zone) CommonOperatorBuilder(&zone), new (&zone) MachineOperatorBuilder( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements())); wasm::CompilationEnv env( native_module->module(), wasm::UseTrapHandler::kNoTrapHandler, wasm::RuntimeExceptionSupport::kNoRuntimeExceptionSupport, wasm::kAllWasmFeatures, wasm::LowerSimd::kNoLowerSimd); WasmGraphBuilder builder(&env, mcgraph->zone(), mcgraph, sig, source_positions); // Set up the graph start. Node* start = builder.Start(static_cast<int>(sig->parameter_count() + 1 + 1)); Node* effect = start; Node* control = start; builder.set_effect_ptr(&effect); builder.set_control_ptr(&control); builder.set_instance_node(builder.Param(wasm::kWasmInstanceParameterIndex)); // Generate either a unop or a binop. Node* result = nullptr; const char* debug_name = "WasmMathIntrinsic"; auto opcode = GetMathIntrinsicOpcode(kind, &debug_name); switch (sig->parameter_count()) { case 1: result = builder.Unop(opcode, builder.Param(1)); break; case 2: result = builder.Binop(opcode, builder.Param(1), builder.Param(2)); break; default: UNREACHABLE(); break; } builder.Return(result); // Run the compiler pipeline to generate machine code. auto call_descriptor = GetWasmCallDescriptor(&zone, sig); if (mcgraph->machine()->Is32()) { call_descriptor = GetI32WasmCallDescriptor(&zone, call_descriptor); } wasm::WasmCode* wasm_code = Pipeline::GenerateCodeForWasmNativeStub( wasm_engine, call_descriptor, mcgraph, Code::WASM_FUNCTION, wasm::WasmCode::kFunction, debug_name, WasmStubAssemblerOptions(), native_module, source_positions); CHECK_NOT_NULL(wasm_code); // TODO(titzer): add counters for math intrinsic code size / allocation return wasm_code; } wasm::WasmCode* CompileWasmImportCallWrapper(wasm::WasmEngine* wasm_engine, wasm::NativeModule* native_module, WasmImportCallKind kind, wasm::FunctionSig* sig, bool source_positions) { DCHECK_NE(WasmImportCallKind::kLinkError, kind); DCHECK_NE(WasmImportCallKind::kWasmToWasm, kind); // Check for math intrinsics first. if (FLAG_wasm_math_intrinsics && kind >= WasmImportCallKind::kFirstMathIntrinsic && kind <= WasmImportCallKind::kLastMathIntrinsic) { return CompileWasmMathIntrinsic(wasm_engine, native_module, kind, sig); } TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm"), "CompileWasmImportCallWrapper"); //---------------------------------------------------------------------------- // Create the Graph //---------------------------------------------------------------------------- Zone zone(wasm_engine->allocator(), ZONE_NAME); Graph graph(&zone); CommonOperatorBuilder common(&zone); MachineOperatorBuilder machine( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); JSGraph jsgraph(nullptr, &graph, &common, nullptr, nullptr, &machine); Node* control = nullptr; Node* effect = nullptr; SourcePositionTable* source_position_table = source_positions ? new (&zone) SourcePositionTable(&graph) : nullptr; WasmWrapperGraphBuilder builder(&zone, &jsgraph, sig, source_position_table, StubCallMode::kCallWasmRuntimeStub, native_module->enabled_features()); builder.set_control_ptr(&control); builder.set_effect_ptr(&effect); builder.BuildWasmImportCallWrapper(kind); const char* func_name = "wasm-to-js"; // Schedule and compile to machine code. CallDescriptor* incoming = GetWasmCallDescriptor(&zone, sig, WasmGraphBuilder::kNoRetpoline, WasmGraphBuilder::kExtraCallableParam); if (machine.Is32()) { incoming = GetI32WasmCallDescriptor(&zone, incoming); } wasm::WasmCode* wasm_code = Pipeline::GenerateCodeForWasmNativeStub( wasm_engine, incoming, &jsgraph, Code::WASM_TO_JS_FUNCTION, wasm::WasmCode::kWasmToJsWrapper, func_name, WasmStubAssemblerOptions(), native_module, source_position_table); CHECK_NOT_NULL(wasm_code); return wasm_code; } wasm::WasmCode* CompileWasmInterpreterEntry(wasm::WasmEngine* wasm_engine, wasm::NativeModule* native_module, uint32_t func_index, wasm::FunctionSig* sig) { //---------------------------------------------------------------------------- // Create the Graph //---------------------------------------------------------------------------- Zone zone(wasm_engine->allocator(), ZONE_NAME); Graph graph(&zone); CommonOperatorBuilder common(&zone); MachineOperatorBuilder machine( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); JSGraph jsgraph(nullptr, &graph, &common, nullptr, nullptr, &machine); Node* control = nullptr; Node* effect = nullptr; WasmWrapperGraphBuilder builder(&zone, &jsgraph, sig, nullptr, StubCallMode::kCallWasmRuntimeStub, native_module->enabled_features()); builder.set_control_ptr(&control); builder.set_effect_ptr(&effect); builder.BuildWasmInterpreterEntry(func_index); // Schedule and compile to machine code. CallDescriptor* incoming = GetWasmCallDescriptor(&zone, sig); if (machine.Is32()) { incoming = GetI32WasmCallDescriptor(&zone, incoming); } EmbeddedVector<char, 32> func_name; func_name.Truncate( SNPrintF(func_name, "wasm-interpreter-entry#%d", func_index)); wasm::WasmCode* wasm_code = Pipeline::GenerateCodeForWasmNativeStub( wasm_engine, incoming, &jsgraph, Code::WASM_INTERPRETER_ENTRY, wasm::WasmCode::kInterpreterEntry, func_name.start(), WasmStubAssemblerOptions(), native_module); CHECK_NOT_NULL(wasm_code); return wasm_code; } MaybeHandle<Code> CompileCWasmEntry(Isolate* isolate, wasm::FunctionSig* sig) { Zone zone(isolate->allocator(), ZONE_NAME); Graph graph(&zone); CommonOperatorBuilder common(&zone); MachineOperatorBuilder machine( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); JSGraph jsgraph(isolate, &graph, &common, nullptr, nullptr, &machine); Node* control = nullptr; Node* effect = nullptr; WasmWrapperGraphBuilder builder(&zone, &jsgraph, sig, nullptr, StubCallMode::kCallCodeObject, wasm::WasmFeaturesFromIsolate(isolate)); builder.set_control_ptr(&control); builder.set_effect_ptr(&effect); builder.BuildCWasmEntry(); // Schedule and compile to machine code. CallDescriptor* incoming = Linkage::GetJSCallDescriptor( &zone, false, CWasmEntryParameters::kNumParameters + 1, CallDescriptor::kNoFlags); // Build a name in the form "c-wasm-entry:<params>:<returns>". static constexpr size_t kMaxNameLen = 128; char debug_name[kMaxNameLen] = "c-wasm-entry:"; AppendSignature(debug_name, kMaxNameLen, sig); MaybeHandle<Code> maybe_code = Pipeline::GenerateCodeForWasmHeapStub( isolate, incoming, &graph, Code::C_WASM_ENTRY, debug_name, AssemblerOptions::Default(isolate)); Handle<Code> code; if (!maybe_code.ToHandle(&code)) { return maybe_code; } #ifdef ENABLE_DISASSEMBLER if (FLAG_print_opt_code) { CodeTracer::Scope tracing_scope(isolate->GetCodeTracer()); OFStream os(tracing_scope.file()); code->Disassemble(debug_name, os); } #endif return code; } TurbofanWasmCompilationUnit::TurbofanWasmCompilationUnit( wasm::WasmCompilationUnit* wasm_unit) : wasm_unit_(wasm_unit) {} // Clears unique_ptrs, but (part of) the type is forward declared in the header. TurbofanWasmCompilationUnit::~TurbofanWasmCompilationUnit() = default; bool TurbofanWasmCompilationUnit::BuildGraphForWasmFunction( wasm::CompilationEnv* env, wasm::NativeModule* native_module, const wasm::FunctionBody& func_body, wasm::WasmFeatures* detected, double* decode_ms, MachineGraph* mcgraph, NodeOriginTable* node_origins, SourcePositionTable* source_positions) { base::ElapsedTimer decode_timer; if (FLAG_trace_wasm_decode_time) { decode_timer.Start(); } // Create a TF graph during decoding. WasmGraphBuilder builder(env, mcgraph->zone(), mcgraph, func_body.sig, source_positions); wasm::VoidResult graph_construction_result = wasm::BuildTFGraph( wasm_unit_->wasm_engine_->allocator(), env->enabled_features, env->module, &builder, detected, func_body, node_origins); if (graph_construction_result.failed()) { if (FLAG_trace_wasm_compiler) { StdoutStream{} << "Compilation failed: " << graph_construction_result.error().message() << std::endl; } native_module->compilation_state()->SetError( wasm_unit_->func_index_, std::move(graph_construction_result).error()); return false; } builder.LowerInt64(); if (builder.has_simd() && (!CpuFeatures::SupportsWasmSimd128() || env->lower_simd)) { SimdScalarLowering(mcgraph, CreateMachineSignature(mcgraph->zone(), func_body.sig)) .LowerGraph(); } if (wasm_unit_->func_index_ >= FLAG_trace_wasm_ast_start && wasm_unit_->func_index_ < FLAG_trace_wasm_ast_end) { PrintRawWasmCode(wasm_unit_->wasm_engine_->allocator(), func_body, env->module, wasm::kPrintLocals); } if (FLAG_trace_wasm_decode_time) { *decode_ms = decode_timer.Elapsed().InMillisecondsF(); } return true; } namespace { Vector<const char> GetDebugName(Zone* zone, int index) { // TODO(herhut): Use name from module if available. constexpr int kBufferLength = 24; EmbeddedVector<char, kBufferLength> name_vector; int name_len = SNPrintF(name_vector, "wasm-function#%d", index); DCHECK(name_len > 0 && name_len < name_vector.length()); char* index_name = zone->NewArray<char>(name_len); memcpy(index_name, name_vector.start(), name_len); return Vector<const char>(index_name, name_len); } } // namespace void TurbofanWasmCompilationUnit::ExecuteCompilation( wasm::CompilationEnv* env, wasm::NativeModule* native_module, const wasm::FunctionBody& func_body, Counters* counters, wasm::WasmFeatures* detected) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm"), "ExecuteTurbofanCompilation"); double decode_ms = 0; size_t node_count = 0; Zone zone(wasm_unit_->wasm_engine_->allocator(), ZONE_NAME); MachineGraph* mcgraph = new (&zone) MachineGraph( new (&zone) Graph(&zone), new (&zone) CommonOperatorBuilder(&zone), new (&zone) MachineOperatorBuilder( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements())); OptimizedCompilationInfo info(GetDebugName(&zone, wasm_unit_->func_index_), &zone, Code::WASM_FUNCTION); if (env->runtime_exception_support) { info.SetWasmRuntimeExceptionSupport(); } if (info.trace_turbo_json_enabled()) { TurboCfgFile tcf; tcf << AsC1VCompilation(&info); } NodeOriginTable* node_origins = info.trace_turbo_json_enabled() ? new (&zone) NodeOriginTable(mcgraph->graph()) : nullptr; SourcePositionTable* source_positions = new (mcgraph->zone()) SourcePositionTable(mcgraph->graph()); if (!BuildGraphForWasmFunction(env, native_module, func_body, detected, &decode_ms, mcgraph, node_origins, source_positions)) { // Compilation failed. return; } if (node_origins) { node_origins->AddDecorator(); } base::ElapsedTimer pipeline_timer; if (FLAG_trace_wasm_decode_time) { node_count = mcgraph->graph()->NodeCount(); pipeline_timer.Start(); } // Run the compiler pipeline to generate machine code. auto call_descriptor = GetWasmCallDescriptor(&zone, func_body.sig); if (mcgraph->machine()->Is32()) { call_descriptor = GetI32WasmCallDescriptor(&zone, call_descriptor); } if (wasm::WasmCode* wasm_code = Pipeline::GenerateCodeForWasmFunction( &info, wasm_unit_->wasm_engine_, mcgraph, call_descriptor, source_positions, node_origins, func_body, native_module, wasm_unit_->func_index_)) { wasm_unit_->SetResult(wasm_code, counters); } if (FLAG_trace_wasm_decode_time) { double pipeline_ms = pipeline_timer.Elapsed().InMillisecondsF(); PrintF( "wasm-compilation phase 1 ok: %u bytes, %0.3f ms decode, %zu nodes, " "%0.3f ms pipeline\n", static_cast<unsigned>(func_body.end - func_body.start), decode_ms, node_count, pipeline_ms); } // TODO(bradnelson): Improve histogram handling of size_t. counters->wasm_compile_function_peak_memory_bytes()->AddSample( static_cast<int>(mcgraph->graph()->zone()->allocation_size())); } namespace { // Helper for allocating either an GP or FP reg, or the next stack slot. class LinkageLocationAllocator { public: template <size_t kNumGpRegs, size_t kNumFpRegs> constexpr LinkageLocationAllocator(const Register (&gp)[kNumGpRegs], const DoubleRegister (&fp)[kNumFpRegs]) : allocator_(wasm::LinkageAllocator(gp, fp)) {} LinkageLocation Next(MachineRepresentation rep) { MachineType type = MachineType::TypeForRepresentation(rep); if (IsFloatingPoint(rep)) { if (allocator_.CanAllocateFP(rep)) { int reg_code = allocator_.NextFpReg(rep); return LinkageLocation::ForRegister(reg_code, type); } } else if (allocator_.CanAllocateGP()) { int reg_code = allocator_.NextGpReg(); return LinkageLocation::ForRegister(reg_code, type); } // Cannot use register; use stack slot. int index = -1 - allocator_.NextStackSlot(rep); return LinkageLocation::ForCallerFrameSlot(index, type); } void SetStackOffset(int offset) { allocator_.SetStackOffset(offset); } int NumStackSlots() const { return allocator_.NumStackSlots(); } private: wasm::LinkageAllocator allocator_; }; } // namespace // General code uses the above configuration data. CallDescriptor* GetWasmCallDescriptor( Zone* zone, wasm::FunctionSig* fsig, WasmGraphBuilder::UseRetpoline use_retpoline, WasmGraphBuilder::ExtraCallableParam extra_callable_param) { // The extra here is to accomodate the instance object as first parameter // and, in the case of an import wrapper, the additional callable. int extra_params = extra_callable_param ? 2 : 1; LocationSignature::Builder locations(zone, fsig->return_count(), fsig->parameter_count() + extra_params); // Add register and/or stack parameter(s). LinkageLocationAllocator params(wasm::kGpParamRegisters, wasm::kFpParamRegisters); // The instance object. locations.AddParam(params.Next(MachineRepresentation::kTaggedPointer)); const size_t param_offset = 1; // Actual params start here. // Parameters are separated into two groups (first all untagged, then all // tagged parameters). This allows for easy iteration of tagged parameters // during frame iteration. const size_t parameter_count = fsig->parameter_count(); for (size_t i = 0; i < parameter_count; i++) { MachineRepresentation param = wasm::ValueTypes::MachineRepresentationFor(fsig->GetParam(i)); // Skip tagged parameters (e.g. any-ref). if (IsAnyTagged(param)) continue; auto l = params.Next(param); locations.AddParamAt(i + param_offset, l); } for (size_t i = 0; i < parameter_count; i++) { MachineRepresentation param = wasm::ValueTypes::MachineRepresentationFor(fsig->GetParam(i)); // Skip untagged parameters. if (!IsAnyTagged(param)) continue; auto l = params.Next(param); locations.AddParamAt(i + param_offset, l); } // Import call wrappers have an additional (implicit) parameter, the callable. // For consistency with JS, we use the JSFunction register. if (extra_callable_param) { locations.AddParam(LinkageLocation::ForRegister( kJSFunctionRegister.code(), MachineType::TaggedPointer())); } // Add return location(s). LinkageLocationAllocator rets(wasm::kGpReturnRegisters, wasm::kFpReturnRegisters); int parameter_slots = params.NumStackSlots(); if (kPadArguments) parameter_slots = RoundUp(parameter_slots, 2); rets.SetStackOffset(parameter_slots); const int return_count = static_cast<int>(locations.return_count_); for (int i = 0; i < return_count; i++) { MachineRepresentation ret = wasm::ValueTypes::MachineRepresentationFor(fsig->GetReturn(i)); auto l = rets.Next(ret); locations.AddReturn(l); } const RegList kCalleeSaveRegisters = 0; const RegList kCalleeSaveFPRegisters = 0; // The target for wasm calls is always a code object. MachineType target_type = MachineType::Pointer(); LinkageLocation target_loc = LinkageLocation::ForAnyRegister(target_type); CallDescriptor::Kind kind = extra_callable_param ? CallDescriptor::kCallWasmImportWrapper : CallDescriptor::kCallWasmFunction; CallDescriptor::Flags flags = use_retpoline ? CallDescriptor::kRetpoline : CallDescriptor::kNoFlags; return new (zone) CallDescriptor( // -- kind, // kind target_type, // target MachineType target_loc, // target location locations.Build(), // location_sig parameter_slots, // stack_parameter_count compiler::Operator::kNoProperties, // properties kCalleeSaveRegisters, // callee-saved registers kCalleeSaveFPRegisters, // callee-saved fp regs flags, // flags "wasm-call", // debug name 0, // allocatable registers rets.NumStackSlots() - parameter_slots); // stack_return_count } namespace { CallDescriptor* ReplaceTypeInCallDescriptorWith( Zone* zone, CallDescriptor* call_descriptor, size_t num_replacements, MachineType input_type, MachineRepresentation output_type) { size_t parameter_count = call_descriptor->ParameterCount(); size_t return_count = call_descriptor->ReturnCount(); for (size_t i = 0; i < call_descriptor->ParameterCount(); i++) { if (call_descriptor->GetParameterType(i) == input_type) { parameter_count += num_replacements - 1; } } for (size_t i = 0; i < call_descriptor->ReturnCount(); i++) { if (call_descriptor->GetReturnType(i) == input_type) { return_count += num_replacements - 1; } } if (parameter_count == call_descriptor->ParameterCount() && return_count == call_descriptor->ReturnCount()) { return call_descriptor; } LocationSignature::Builder locations(zone, return_count, parameter_count); LinkageLocationAllocator params(wasm::kGpParamRegisters, wasm::kFpParamRegisters); for (size_t i = 0; i < call_descriptor->ParameterCount(); i++) { if (call_descriptor->GetParameterType(i) == input_type) { for (size_t j = 0; j < num_replacements; j++) { locations.AddParam(params.Next(output_type)); } } else { locations.AddParam( params.Next(call_descriptor->GetParameterType(i).representation())); } } LinkageLocationAllocator rets(wasm::kGpReturnRegisters, wasm::kFpReturnRegisters); rets.SetStackOffset(params.NumStackSlots()); for (size_t i = 0; i < call_descriptor->ReturnCount(); i++) { if (call_descriptor->GetReturnType(i) == input_type) { for (size_t j = 0; j < num_replacements; j++) { locations.AddReturn(rets.Next(output_type)); } } else { locations.AddReturn( rets.Next(call_descriptor->GetReturnType(i).representation())); } } return new (zone) CallDescriptor( // -- call_descriptor->kind(), // kind call_descriptor->GetInputType(0), // target MachineType call_descriptor->GetInputLocation(0), // target location locations.Build(), // location_sig params.NumStackSlots(), // stack_parameter_count call_descriptor->properties(), // properties call_descriptor->CalleeSavedRegisters(), // callee-saved registers call_descriptor->CalleeSavedFPRegisters(), // callee-saved fp regs call_descriptor->flags(), // flags call_descriptor->debug_name(), // debug name call_descriptor->AllocatableRegisters(), // allocatable registers rets.NumStackSlots() - params.NumStackSlots()); // stack_return_count } } // namespace CallDescriptor* GetI32WasmCallDescriptor(Zone* zone, CallDescriptor* call_descriptor) { return ReplaceTypeInCallDescriptorWith(zone, call_descriptor, 2, MachineType::Int64(), MachineRepresentation::kWord32); } CallDescriptor* GetI32WasmCallDescriptorForSimd( Zone* zone, CallDescriptor* call_descriptor) { return ReplaceTypeInCallDescriptorWith(zone, call_descriptor, 4, MachineType::Simd128(), MachineRepresentation::kWord32); } AssemblerOptions WasmAssemblerOptions() { AssemblerOptions options; // Relocation info required to serialize {WasmCode} for proper functions. options.record_reloc_info_for_serialization = true; options.enable_root_array_delta_access = false; return options; } AssemblerOptions WasmStubAssemblerOptions() { AssemblerOptions options; // Relocation info not necessary because stubs are not serialized. options.record_reloc_info_for_serialization = false; options.enable_root_array_delta_access = false; return options; } #undef WASM_64 #undef FATAL_UNSUPPORTED_OPCODE #undef WASM_INSTANCE_OBJECT_SIZE #undef WASM_INSTANCE_OBJECT_OFFSET #undef LOAD_RAW #undef LOAD_INSTANCE_FIELD #undef LOAD_TAGGED_POINTER #undef LOAD_TAGGED_ANY #undef LOAD_FIXED_ARRAY_SLOT #undef LOAD_FIXED_ARRAY_SLOT_SMI #undef LOAD_FIXED_ARRAY_SLOT_PTR #undef LOAD_FIXED_ARRAY_SLOT_ANY #undef STORE_FIXED_ARRAY_SLOT_SMI #undef STORE_FIXED_ARRAY_SLOT_ANY } // namespace compiler } // namespace internal } // namespace v8
// Copyright (c) 2017 VMware, Inc. All Rights Reserved. #include <rethink/ref_string.h> #include <rethink/shared_string.h> #include <catch.hpp> using namespace rethink; using namespace rethink::detail; using namespace std; TEST_CASE("Empty shared string is empty", "[shared_string]") { shared_string s; CHECK(string_size(s) == 0); } TEST_CASE("shared_string is_transferable", "[shared_string]") { CHECK(rethink::is_transferable_v<shared_string &&> == true); CHECK(rethink::is_transferable_v<shared_string> == false); CHECK(rethink::is_transferable_v<shared_string &> == false); CHECK(rethink::is_transferable_v<shared_string const &> == false); CHECK(rethink::is_transferable_v<shared_string *> == false); } TEST_CASE("shared_string is_shareable", "[shared_string]") { CHECK(rethink::is_shareable_v<shared_string &&> == true); CHECK(rethink::is_shareable_v<shared_string> == true); CHECK(rethink::is_shareable_v<shared_string &> == true); CHECK(rethink::is_shareable_v<shared_string const &> == true); CHECK(rethink::is_shareable_v<shared_string *> == false); } TEST_CASE("Shared string value ops", "[shared_string]") { size_t start = ctrl_block::instance_count(); SECTION("Shared strings init from ref_string") { ref_string r = "foo"; shared_string s(r); CHECK(string_size(s) == 3); CHECK(s.size() == 3); CHECK(strncmp(string_data(s), r.data(), s.size()) == 0); CHECK(strncmp(s.data(), r.data(), s.size()) == 0); CHECK(ctrl_block::instance_count() == start + 1); } SECTION("Shared strings assigned from ref_string") { shared_string s; ref_string r = "foo"; s = r; CHECK(string_size(s) == 3); CHECK(s.size() == 3); CHECK(strncmp(string_data(s), r.data(), s.size()) == 0); CHECK(strncmp(s.data(), r.data(), s.size()) == 0); CHECK(ctrl_block::instance_count() == start + 1); } SECTION("Shared string copied") { shared_string from = ref_string("foo"); shared_string s(from); CHECK(from.size() == 3); CHECK(s.size() == 3); CHECK(strncmp(s.data(), "foo", s.size()) == 0); CHECK(ctrl_block::instance_count() == start + 1); } SECTION("Shared string assigned") { shared_string from = ref_string("foo"); shared_string s; s = from; CHECK(from.size() == 3); CHECK(s.size() == 3); CHECK(strncmp(s.data(), "foo", s.size()) == 0); CHECK(ctrl_block::instance_count() == start + 1); } SECTION("Shared string move copied") { shared_string from = ref_string("foo"); shared_string s(move(from)); CHECK(from.size() == 0); CHECK(s.size() == 3); CHECK(strncmp(s.data(), "foo", s.size()) == 0); CHECK(ctrl_block::instance_count() == start + 1); } SECTION("Shared string move assigned") { shared_string from = ref_string("foo"); shared_string s; s = move(from); CHECK(from.size() == 0); CHECK(s.size() == 3); CHECK(strncmp(s.data(), "foo", s.size()) == 0); CHECK(ctrl_block::instance_count() == start + 1); } CHECK(ctrl_block::instance_count() == start); } TEST_CASE("Shared string share storage", "[shared_string]") { size_t start = ctrl_block::instance_count(); { shared_string one = ref_string("foo"); CHECK(ctrl_block::instance_count() == start + 1); { shared_string two = one; CHECK(ctrl_block::instance_count() == start + 1); } CHECK(ctrl_block::instance_count() == start + 1); } CHECK(ctrl_block::instance_count() == start); }
/*========================================================================= 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 <iostream> #include <itkDCMTKImageIO.h> #include <itkImageFileReader.h> #include <itkMetaDataDictionary.h> int main (int narg, char* arg[]) { if( narg<3 ) { std::cerr << "Usage: " << arg[0] << " <dicom1 dicom2 ... dicomN> <output>\n"; return -1; } std::vector<std::string> fileNames; for( int i=1; i<narg-1; i++){ std::cout << "Inserting: " << arg[i] << std::endl; fileNames.push_back ( arg[i] ); } const char* output = arg[narg-1]; itk::DCMTKImageIO::Pointer io = itk::DCMTKImageIO::New(); io->SetFileNames ( fileNames ); try { io->ReadImageInformation(); } catch (itk::ExceptionObject &e) { std::cerr << e; return -1; } //itk::MetaDataDictionary& dicomDictionary = io->GetMetaDataDictionary(); const itk::DCMTKImageIO::StringVectorType vecx = io->GetMetaDataValueVectorString ("(0019,10bb)"); const itk::DCMTKImageIO::StringVectorType vecy = io->GetMetaDataValueVectorString ("(0019,10bc)"); const itk::DCMTKImageIO::StringVectorType vecz = io->GetMetaDataValueVectorString ("(0019,10bd)"); std::vector< std::vector<double> > gradients; for (unsigned int i=0; i<vecx.size(); i++) { std::vector<double> vec (3); vec[0] = atof (vecx[i].c_str()); vec[1] = atof (vecy[i].c_str()); vec[2] = atof (vecz[i].c_str()); //std::cout << vecx[i] << " " << vecy[i] << " " << vecz[i] << std::endl; gradients.push_back (vec); } std::vector< std::vector<double> >::iterator new_end = std::unique (gradients.begin(), gradients.end()); std::vector< std::vector<double> >::iterator it = gradients.begin(); std::ofstream buf (output); while (it!=new_end) { buf << (*it)[0] << " " << (*it)[1] << " " << (*it)[2] << "\n"; ++it; } return 0; }
// Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // Preprocessed version of "boost/mpl/aux_/lambda_no_ctps.hpp" header // -- DO NOT modify by hand! namespace lslboost { namespace mpl { namespace aux { template< bool C1 = false, bool C2 = false, bool C3 = false, bool C4 = false , bool C5 = false > struct lambda_or : true_ { }; template<> struct lambda_or< false,false,false,false,false > : false_ { }; template< typename Arity > struct lambda_impl { template< typename T, typename Tag, typename Protect > struct result_ { typedef T type; typedef is_placeholder<T> is_le; }; }; template<> struct lambda_impl< int_<1> > { template< typename F, typename Tag, typename Protect > struct result_ { typedef lambda< typename F::arg1, Tag, false_ > l1; typedef typename l1::is_le is_le1; typedef aux::lambda_or< BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le1)::value > is_le; typedef bind1< typename F::rebind , typename l1::type > bind_; typedef typename if_< is_le , if_< Protect, mpl::protect<bind_>, bind_ > , identity<F> >::type type_; typedef typename type_::type type; }; }; template<> struct lambda_impl< int_<2> > { template< typename F, typename Tag, typename Protect > struct result_ { typedef lambda< typename F::arg1, Tag, false_ > l1; typedef lambda< typename F::arg2, Tag, false_ > l2; typedef typename l1::is_le is_le1; typedef typename l2::is_le is_le2; typedef aux::lambda_or< BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le1)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le2)::value > is_le; typedef bind2< typename F::rebind , typename l1::type, typename l2::type > bind_; typedef typename if_< is_le , if_< Protect, mpl::protect<bind_>, bind_ > , identity<F> >::type type_; typedef typename type_::type type; }; }; template<> struct lambda_impl< int_<3> > { template< typename F, typename Tag, typename Protect > struct result_ { typedef lambda< typename F::arg1, Tag, false_ > l1; typedef lambda< typename F::arg2, Tag, false_ > l2; typedef lambda< typename F::arg3, Tag, false_ > l3; typedef typename l1::is_le is_le1; typedef typename l2::is_le is_le2; typedef typename l3::is_le is_le3; typedef aux::lambda_or< BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le1)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le2)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le3)::value > is_le; typedef bind3< typename F::rebind , typename l1::type, typename l2::type, typename l3::type > bind_; typedef typename if_< is_le , if_< Protect, mpl::protect<bind_>, bind_ > , identity<F> >::type type_; typedef typename type_::type type; }; }; template<> struct lambda_impl< int_<4> > { template< typename F, typename Tag, typename Protect > struct result_ { typedef lambda< typename F::arg1, Tag, false_ > l1; typedef lambda< typename F::arg2, Tag, false_ > l2; typedef lambda< typename F::arg3, Tag, false_ > l3; typedef lambda< typename F::arg4, Tag, false_ > l4; typedef typename l1::is_le is_le1; typedef typename l2::is_le is_le2; typedef typename l3::is_le is_le3; typedef typename l4::is_le is_le4; typedef aux::lambda_or< BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le1)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le2)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le3)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le4)::value > is_le; typedef bind4< typename F::rebind , typename l1::type, typename l2::type, typename l3::type , typename l4::type > bind_; typedef typename if_< is_le , if_< Protect, mpl::protect<bind_>, bind_ > , identity<F> >::type type_; typedef typename type_::type type; }; }; template<> struct lambda_impl< int_<5> > { template< typename F, typename Tag, typename Protect > struct result_ { typedef lambda< typename F::arg1, Tag, false_ > l1; typedef lambda< typename F::arg2, Tag, false_ > l2; typedef lambda< typename F::arg3, Tag, false_ > l3; typedef lambda< typename F::arg4, Tag, false_ > l4; typedef lambda< typename F::arg5, Tag, false_ > l5; typedef typename l1::is_le is_le1; typedef typename l2::is_le is_le2; typedef typename l3::is_le is_le3; typedef typename l4::is_le is_le4; typedef typename l5::is_le is_le5; typedef aux::lambda_or< BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le1)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le2)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le3)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le4)::value, BOOST_MPL_AUX_MSVC_VALUE_WKND(is_le5)::value > is_le; typedef bind5< typename F::rebind , typename l1::type, typename l2::type, typename l3::type , typename l4::type, typename l5::type > bind_; typedef typename if_< is_le , if_< Protect, mpl::protect<bind_>, bind_ > , identity<F> >::type type_; typedef typename type_::type type; }; }; } // namespace aux template< typename T , typename Tag , typename Protect > struct lambda { /// Metafunction forwarding confuses MSVC 6.x typedef typename aux::template_arity<T>::type arity_; typedef typename aux::lambda_impl<arity_> ::template result_< T,Tag,Protect > l_; typedef typename l_::type type; typedef typename l_::is_le is_le; BOOST_MPL_AUX_LAMBDA_SUPPORT(3, lambda, (T, Tag, Protect)) }; BOOST_MPL_AUX_NA_SPEC2(1, 3, lambda) template< typename T > struct is_lambda_expression : lambda<T>::is_le { }; }}
#include "LoopListScene.h" USING_NS_CC; void LoopListScene::continueInit() { UIPackage::addPackage("UI/LoopList"); UIConfig::horizontalScrollBar = ""; UIConfig::verticalScrollBar = ""; _view = UIPackage::createObject("LoopList", "Main")->as<GComponent>(); _groot->addChild(_view); _list = _view->getChild("list")->as<GList>(); _list->itemRenderer = CC_CALLBACK_2(LoopListScene::renderListItem, this); _list->setVirtualAndLoop(); _list->setNumItems(5); _list->addEventListener(UIEventType::Scroll, CC_CALLBACK_1(LoopListScene::doSpecialEffect, this)); doSpecialEffect(nullptr); } void LoopListScene::renderListItem(int index, GObject* obj) { obj->setPivot(0.5f, 0.5f); obj->setIcon("ui://LoopList/n" + std::to_string(index + 1)); } void LoopListScene::doSpecialEffect(EventContext*) { //change the scale according to the distance to middle float midX = _list->getScrollPane()->getPosX() + _list->getViewWidth() / 2; int cnt = _list->numChildren(); for (int i = 0; i < cnt; i++) { GObject* obj = _list->getChildAt(i); float dist = std::abs(midX - obj->getX() - obj->getWidth() / 2); if (dist > obj->getWidth()) //no intersection obj->setScale(1, 1); else { float ss = 1 + (1 - dist / obj->getWidth()) * 0.24f; obj->setScale(ss, ss); } } _view->getChild("n3")->setText(std::to_string((_list->getFirstChildInView() + 1) % _list->getNumItems())); }
// Copyright 2014 The Chromium OS 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 "login_manager/device_identifier_generator.h" #include <stdint.h> #include <stdlib.h> #include <map> #include <set> #include <string> #include <base/bind.h> #include <base/callback_helpers.h> #include <base/files/file_util.h> #include <base/files/scoped_temp_dir.h> #include <base/time/time.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "login_manager/login_metrics.h" #include "login_manager/mock_metrics.h" #include "login_manager/system_utils_impl.h" using testing::_; using testing::SaveArg; namespace login_manager { namespace { // A SystemUtils implementation that mocks time. class FakeSystemUtils : public SystemUtilsImpl { public: FakeSystemUtils() : time_(0) {} FakeSystemUtils(const FakeSystemUtils&) = delete; FakeSystemUtils& operator=(const FakeSystemUtils&) = delete; ~FakeSystemUtils() override {} time_t time(time_t* t) override { if (t) *t = time_; return time_; } void forward_time(time_t offset) { time_ += offset; } private: // Current time. time_t time_; }; } // namespace class DeviceIdentifierGeneratorTest : public ::testing::Test { public: DeviceIdentifierGeneratorTest() : generator_(&system_utils_, &metrics_), state_keys_received_(false), last_state_key_generation_status_( LoginMetrics::STATE_KEY_STATUS_MISSING_IDENTIFIERS) { EXPECT_CALL(metrics_, SendStateKeyGenerationStatus(_)) .WillRepeatedly(SaveArg<0>(&last_state_key_generation_status_)); } DeviceIdentifierGeneratorTest(const DeviceIdentifierGeneratorTest&) = delete; DeviceIdentifierGeneratorTest& operator=( const DeviceIdentifierGeneratorTest&) = delete; ~DeviceIdentifierGeneratorTest() override {} // Installs mock data for the required parameters. void InitMachineInfo() { std::map<std::string, std::string> params; params["serial_number"] = "fake-machine-serial-number"; params["root_disk_serial_number"] = "fake-disk-serial-number"; params["stable_device_secret_DO_NOT_SHARE"] = "11223344556677889900aabbccddeeff11223344556677889900aabbccddeeff"; ASSERT_TRUE(generator_.InitMachineInfo(params)); } void CompletionHandler(const std::vector<std::vector<uint8_t>>& state_keys) { state_keys_received_ = true; state_keys_ = state_keys; } void RequestStateKeys(bool expect_immediate_callback) { state_keys_received_ = false; state_keys_.clear(); generator_.RequestStateKeys( base::Bind(&DeviceIdentifierGeneratorTest::CompletionHandler, base::Unretained(this))); EXPECT_EQ(expect_immediate_callback, state_keys_received_); } void CompletionPsmDeviceKeyHandler(const std::string& derived_secret) { psm_device_secret_received_ = true; psm_derived_secret_ = derived_secret; } void RequestPsmDeviceActiveSecret(bool expect_immediate_callback) { psm_device_secret_received_ = false; generator_.RequestPsmDeviceActiveSecret(base::Bind( &DeviceIdentifierGeneratorTest::CompletionPsmDeviceKeyHandler, base::Unretained(this))); EXPECT_EQ(expect_immediate_callback, psm_device_secret_received_); } FakeSystemUtils system_utils_; MockMetrics metrics_; DeviceIdentifierGenerator generator_; bool state_keys_received_; std::vector<std::vector<uint8_t>> state_keys_; bool psm_device_secret_received_; std::string psm_derived_secret_; LoginMetrics::StateKeyGenerationStatus last_state_key_generation_status_; }; TEST_F(DeviceIdentifierGeneratorTest, RequestStateKeys) { InitMachineInfo(); RequestStateKeys(true); EXPECT_EQ(LoginMetrics::STATE_KEY_STATUS_GENERATION_METHOD_HMAC_DEVICE_SECRET, last_state_key_generation_status_); ASSERT_EQ(DeviceIdentifierGenerator::kDeviceStateKeyFutureQuanta, state_keys_.size()); } TEST_F(DeviceIdentifierGeneratorTest, RequestPsmDeviceActiveSecretSuccessAfterInitMachineInfo) { InitMachineInfo(); RequestPsmDeviceActiveSecret(true); EXPECT_TRUE(psm_device_secret_received_); } TEST_F(DeviceIdentifierGeneratorTest, RequestPsmDeviceActiveSecretSuccessBeforeInitMachineInfo) { // No callback as long as machine info has not been provided. RequestPsmDeviceActiveSecret(false); InitMachineInfo(); EXPECT_TRUE(psm_device_secret_received_); // Sending machine info twice is harmless and doesn't fire callbacks. psm_device_secret_received_ = false; InitMachineInfo(); EXPECT_FALSE(psm_device_secret_received_); } TEST_F(DeviceIdentifierGeneratorTest, RequestStateKeysLegacy) { std::map<std::string, std::string> params; params["serial_number"] = "fake-machine-serial-number"; params["root_disk_serial_number"] = "fake-disk-serial-number"; ASSERT_TRUE(generator_.InitMachineInfo(params)); RequestStateKeys(true); EXPECT_EQ(LoginMetrics::STATE_KEY_STATUS_GENERATION_METHOD_IDENTIFIER_HASH, last_state_key_generation_status_); ASSERT_EQ(DeviceIdentifierGenerator::kDeviceStateKeyFutureQuanta, state_keys_.size()); } TEST_F(DeviceIdentifierGeneratorTest, TimedStateKeys) { InitMachineInfo(); system_utils_.forward_time(base::Days(100).InSeconds()); // The correct number of state keys gets returned. RequestStateKeys(true); EXPECT_EQ(LoginMetrics::STATE_KEY_STATUS_GENERATION_METHOD_HMAC_DEVICE_SECRET, last_state_key_generation_status_); ASSERT_EQ(DeviceIdentifierGenerator::kDeviceStateKeyFutureQuanta, state_keys_.size()); std::vector<std::vector<uint8_t>> initial_state_keys = state_keys_; // All state keys are different. std::set<std::vector<uint8_t>> state_key_set(state_keys_.begin(), state_keys_.end()); EXPECT_EQ(DeviceIdentifierGenerator::kDeviceStateKeyFutureQuanta, state_key_set.size()); // Moving forward just a little yields the same keys. system_utils_.forward_time(base::Days(1).InSeconds()); RequestStateKeys(true); EXPECT_EQ(LoginMetrics::STATE_KEY_STATUS_GENERATION_METHOD_HMAC_DEVICE_SECRET, last_state_key_generation_status_); EXPECT_EQ(initial_state_keys, state_keys_); // Jumping to a future quantum results in the state keys rolling forward. int64_t step = 1 << DeviceIdentifierGenerator::kDeviceStateKeyTimeQuantumPower; system_utils_.forward_time(2 * step); RequestStateKeys(true); EXPECT_EQ(LoginMetrics::STATE_KEY_STATUS_GENERATION_METHOD_HMAC_DEVICE_SECRET, last_state_key_generation_status_); ASSERT_EQ(DeviceIdentifierGenerator::kDeviceStateKeyFutureQuanta, state_keys_.size()); EXPECT_TRUE(std::equal(initial_state_keys.begin() + 2, initial_state_keys.end(), state_keys_.begin())); } TEST_F(DeviceIdentifierGeneratorTest, PendingMachineInfo) { // No callback as long as machine info has not been provided. RequestStateKeys(false); // Supplying machine info fires callbacks. InitMachineInfo(); EXPECT_TRUE(state_keys_received_); EXPECT_EQ(DeviceIdentifierGenerator::kDeviceStateKeyFutureQuanta, state_keys_.size()); // Sending machine info twice is harmless and doesn't fire callbacks. state_keys_received_ = false; InitMachineInfo(); EXPECT_FALSE(state_keys_received_); } TEST_F(DeviceIdentifierGeneratorTest, PendingMachineInfoFailure) { // No callback as long as machine info has not been provided. RequestStateKeys(false); // Supplying machine info fires callbacks even if info is missing. std::map<std::string, std::string> empty; EXPECT_FALSE(generator_.InitMachineInfo(empty)); EXPECT_TRUE(state_keys_received_); EXPECT_EQ(0, state_keys_.size()); // Later requests get answered immediately. RequestStateKeys(true); EXPECT_EQ(LoginMetrics::STATE_KEY_STATUS_MISSING_IDENTIFIERS, last_state_key_generation_status_); EXPECT_EQ(0, state_keys_.size()); } TEST_F(DeviceIdentifierGeneratorTest, ParseMachineInfoSuccess) { std::map<std::string, std::string> params; EXPECT_TRUE(DeviceIdentifierGenerator::ParseMachineInfo( "\"serial_number\"=\"fake-machine-serial-number\"\n" "# This is a comment.\n" "\"root_disk_serial_number\"=\"fake disk-serial-number\"\n" "\"serial_number\"=\"key_collision\"\n" "\"stable_device_secret_DO_NOT_SHARE\"=" "\"11223344556677889900aabbccddeeff11223344556677889900aabbccddeeff\"\n", &params)); EXPECT_EQ(3, params.size()); EXPECT_EQ("fake-machine-serial-number", params["serial_number"]); EXPECT_EQ("fake disk-serial-number", params["root_disk_serial_number"]); } TEST_F(DeviceIdentifierGeneratorTest, ParseMachineInfoFailure) { std::map<std::string, std::string> params; EXPECT_FALSE(DeviceIdentifierGenerator::ParseMachineInfo("bad!", &params)); } } // namespace login_manager
#include <iostream> #include <cassert> #include <vector> #include <tuple> #include <algorithm> #include <zlib.h> #include <string> #include <chrono> //third-party lib #include "mummer/sparseSA.hpp" #include "kseq/kseq.h" #include "prettyprint/prettyprint.hpp" //own includes #include "parseCmdArgs.hpp" #include "algo.hpp" #undef VERBOSE #define VERBOSE 0 int main(int argc, char **argv) { chainx::Parameters parameters; chainx::parseandSave_chainx(argc, argv, parameters); std::vector<std::string> queries; //one or multiple sequences std::vector<std::string> query_ids; std::vector<std::string> target; //single sequence std::vector<std::string> target_ids; chainx::readSequences(parameters.qfile, queries, query_ids); chainx::readSequences(parameters.tfile, target, target_ids); int queryLenSum = 0; for (auto &q: queries) queryLenSum += q.length(); std::cerr << "INFO, chainx::main, read " << queries.size() << " queries, " << queryLenSum << " residues\n"; if (!parameters.all2all) std::cerr << "INFO, chainx::main, read target, " << target[0].length() << " residues\n"; //Start timer auto tStart = std::chrono::system_clock::now(); std::cerr << "\nINFO, chainx::main, timer set\n"; std::vector<std::tuple<int, int, int>> fwd_matches; //lambda function auto append_matches = [&](const mummer::mummer::match_t& m) { fwd_matches.emplace_back(m.ref, m.query, m.len); }; //0-based coordinates if (!parameters.all2all) { //Compute anchors mummer::mummer::sparseSA sa (mummer::mummer::sparseSA::create_auto(target[0].data(), target[0].length(), parameters.minLen, true)); std::chrono::duration<double> wctduration = (std::chrono::system_clock::now() - tStart); std::cerr << "INFO, chainx::main, suffix array computed in " << wctduration.count() << " seconds\n"; for (int i = 0; i < queries.size(); i++) { std::cerr << "\nINFO, chainx::main, timer reset\n"; tStart = std::chrono::system_clock::now(); fwd_matches.clear(); if (parameters.matchType == "MEM") sa.findMEM_each(queries[i].data(), queries[i].length(), parameters.minLen, false, append_matches); else if (parameters.matchType == "MUM") sa.findMUM_each(queries[i].data(), queries[i].length(), parameters.minLen, false, append_matches); else std::cerr << "ERROR, chainx::main, incorrect anchor type specified" << "\n"; wctduration = (std::chrono::system_clock::now() - tStart); if (VERBOSE && parameters.matchType == "MEM") std::cerr << "INFO, chainx::main, MEMs identified (" << wctduration.count() << " seconds elapsed)\n"; if (VERBOSE && parameters.matchType == "MUM") std::cerr << "INFO, chainx::main, MUMs identified (" << wctduration.count() << " seconds elapsed)\n"; //place dummy MEMs and then sort fwd_matches.emplace_back(-1,-1,1); fwd_matches.emplace_back(target[0].length(), queries[i].length(), 1); std::sort (fwd_matches.begin(), fwd_matches.end(), [](const std::tuple<int,int,int>& a, const std::tuple<int,int,int>& b) -> bool { return std::get<0>(a) < std::get<0>(b); }); std::size_t sum_anchor_len = 0; for (auto &e: fwd_matches) sum_anchor_len += std::get<2>(e); std::cerr << "INFO, chainx::main, count of anchors (including dummy) = " << fwd_matches.size() << ", average length = " << sum_anchor_len * 1.0 / fwd_matches.size() << "\n"; if (VERBOSE) std::cerr << "List of sorted anchors = " << fwd_matches << "\n"; //compute anchor-restricted edit distance std::cerr << "INFO, chainx::main, query #" << i << " (" << queries[i].length() << " residues), "; if (parameters.mode == "g") { if (parameters.naive) std::cout << "distance = " << chainx::DP_global(fwd_matches) << "\n"; else std::cout << "distance = " << chainx::compute_global(fwd_matches) << "\n"; } else if (parameters.mode == "sg") { if (parameters.naive) std::cout << "distance = " << chainx::DP_semiglobal(fwd_matches) << "\n"; else std::cout << "distance = " << chainx::compute_semiglobal(fwd_matches) << "\n"; } else std::cerr << "ERROR, chainx::main, incorrect mode specified" << "\n"; wctduration = (std::chrono::system_clock::now() - tStart); std::cerr << "INFO, chainx::main, distance computation finished (" << wctduration.count() << " seconds elapsed)\n"; } } else { std::vector<std::vector<int>> costs (queries.size()); for(std::size_t i = 0; i < queries.size(); i++) costs[i] = std::vector<int>(queries.size(), -1); for (std::size_t i = 0; i < queries.size(); i++) { //build SA of queries[i] mummer::mummer::sparseSA sa = mummer::mummer::sparseSA::create_auto(queries[i].data(), queries[i].length(), parameters.minLen, true); for (std::size_t j = 0; j < i; j++) { //compute costs[i][j] && costs[j][i] fwd_matches.clear(); if (parameters.matchType == "MEM") sa.findMEM_each(queries[j].data(), queries[j].length(), parameters.minLen, false, append_matches); else if (parameters.matchType == "MUM") sa.findMUM_each(queries[j].data(), queries[j].length(), parameters.minLen, false, append_matches); else { std::cerr << "ERROR, chainx::main, incorrect anchor type specified" << "\n"; exit(1); } //place dummy MEMs and then sort fwd_matches.emplace_back(-1,-1,1); fwd_matches.emplace_back(queries[i].length(), queries[j].length(), 1); std::sort (fwd_matches.begin(), fwd_matches.end(), [](const std::tuple<int,int,int>& a, const std::tuple<int,int,int>& b) -> bool { return std::get<0>(a) < std::get<0>(b); }); if (parameters.naive) costs[j][i] = costs[i][j] = chainx::DP_global(fwd_matches); else costs[j][i] = costs[i][j] = chainx::compute_global(fwd_matches); } costs[i][i] = 0; } std::cerr << "\nINFO, chainx::main, printing distance matrix to stdout\n"; //phylip-formatted output { std::cout << queries.size() << "\n"; for (std::size_t i = 0; i < queries.size(); i++) { std::cout << query_ids[i]; for (std::size_t j = 0; j < queries.size(); j++) { std::cout << " " << costs[i][j]; } std::cout << "\n"; } } std::chrono::duration<double> wctduration = (std::chrono::system_clock::now() - tStart); std::cerr << "INFO, chainx::main, all-to-all distance computation took " << wctduration.count() << " seconds\n"; } return 0; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 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 "txdb.h" #include "chainparams.h" #include "hash.h" #include "random.h" #include "pow.h" #include "uint256.h" #include "util.h" #include "ui_interface.h" #include "init.h" #include <stdint.h> #include <boost/thread.hpp> static const char DB_COIN = 'C'; static const char DB_COINS = 'c'; static const char DB_BLOCK_FILES = 'f'; static const char DB_TXINDEX = 't'; static const char DB_BLOCK_INDEX = 'b'; static const char DB_BEST_BLOCK = 'B'; static const char DB_HEAD_BLOCKS = 'H'; static const char DB_FLAG = 'F'; static const char DB_REINDEX_FLAG = 'R'; static const char DB_LAST_BLOCK = 'l'; namespace { struct CoinEntry { COutPoint* outpoint; char key; CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {} template<typename Stream> void Serialize(Stream &s) const { s << key; s << outpoint->hash; s << VARINT(outpoint->n); } template<typename Stream> void Unserialize(Stream& s) { s >> key; s >> outpoint->hash; s >> VARINT(outpoint->n); } }; } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true) { } bool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const { return db.Read(CoinEntry(&outpoint), coin); } bool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const { return db.Exists(CoinEntry(&outpoint)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read(DB_BEST_BLOCK, hashBestChain)) return uint256(); return hashBestChain; } std::vector<uint256> CCoinsViewDB::GetHeadBlocks() const { std::vector<uint256> vhashHeadBlocks; if (!db.Read(DB_HEAD_BLOCKS, vhashHeadBlocks)) { return std::vector<uint256>(); } return vhashHeadBlocks; } bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { CDBBatch batch(db); size_t count = 0; size_t changed = 0; size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize); int crash_simulate = gArgs.GetArg("-dbcrashratio", 0); assert(!hashBlock.IsNull()); uint256 old_tip = GetBestBlock(); if (old_tip.IsNull()) { // We may be in the middle of replaying. std::vector<uint256> old_heads = GetHeadBlocks(); if (old_heads.size() == 2) { assert(old_heads[0] == hashBlock); old_tip = old_heads[1]; } } // In the first batch, mark the database as being in the middle of a // transition from old_tip to hashBlock. // A vector is used for future extensibility, as we may want to support // interrupting after partial writes from multiple independent reorgs. batch.Erase(DB_BEST_BLOCK); batch.Write(DB_HEAD_BLOCKS, std::vector<uint256>{hashBlock, old_tip}); for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { CoinEntry entry(&it->first); if (it->second.coin.IsSpent()) batch.Erase(entry); else batch.Write(entry, it->second.coin); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); if (batch.SizeEstimate() > batch_size) { LogPrint(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0)); db.WriteBatch(batch); batch.Clear(); if (crash_simulate) { static FastRandomContext rng; if (rng.randrange(crash_simulate) == 0) { LogPrintf("Simulating a crash. Goodbye.\n"); _Exit(0); } } } } // In the last batch, mark the database as consistent with hashBlock again. batch.Erase(DB_HEAD_BLOCKS); batch.Write(DB_BEST_BLOCK, hashBlock); LogPrint(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0)); bool ret = db.WriteBatch(batch); LogPrint(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return ret; } size_t CCoinsViewDB::EstimateSize() const { return db.EstimateSize(DB_COIN, (char)(DB_COIN+1)); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(std::make_pair(DB_BLOCK_FILES, nFile), info); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write(DB_REINDEX_FLAG, '1'); else return Erase(DB_REINDEX_FLAG); } bool CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists(DB_REINDEX_FLAG); return true; } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read(DB_LAST_BLOCK, nFile); } CCoinsViewCursor *CCoinsViewDB::Cursor() const { CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper&>(db).NewIterator(), GetBestBlock()); /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ i->pcursor->Seek(DB_COIN); // Cache key of first record if (i->pcursor->Valid()) { CoinEntry entry(&i->keyTmp.second); i->pcursor->GetKey(entry); i->keyTmp.first = entry.key; } else { i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false } return i; } bool CCoinsViewDBCursor::GetKey(COutPoint &key) const { // Return cached key if (keyTmp.first == DB_COIN) { key = keyTmp.second; return true; } return false; } bool CCoinsViewDBCursor::GetValue(Coin &coin) const { return pcursor->GetValue(coin); } unsigned int CCoinsViewDBCursor::GetValueSize() const { return pcursor->GetValueSize(); } bool CCoinsViewDBCursor::Valid() const { return keyTmp.first == DB_COIN; } void CCoinsViewDBCursor::Next() { pcursor->Next(); CoinEntry entry(&keyTmp.second); if (!pcursor->Valid() || !pcursor->GetKey(entry)) { keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false } else { keyTmp.first = entry.key; } } bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) { CDBBatch batch(*this); for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) { batch.Write(std::make_pair(DB_BLOCK_FILES, it->first), *it->second); } batch.Write(DB_LAST_BLOCK, nLastFile); for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) { batch.Write(std::make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it)); } return WriteBatch(batch, true); } bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(std::make_pair(DB_TXINDEX, txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CDBBatch batch(*this); for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++) batch.Write(std::make_pair(DB_TXINDEX, it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair(DB_FLAG, name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256())); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, uint256> key; if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) { CDiskBlockIndex diskindex; if (pcursor->GetValue(diskindex)) { // Construct block index object CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = insertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; // worldcoin: Disable PoW Sanity check while loading block index from disk. // We use the sha256 hash for the block index for performance reasons, which is recorded for later use. // CheckProofOfWork() uses the scrypt hash which is discarded after a block is accepted. // While it is technically feasible to verify the PoW, doing so takes several minutes as it // requires recomputing every PoW hash during every worldcoin startup. // We opt instead to simply trust the data that is on your local disk. //if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams)) // return error("%s: CheckProofOfWork failed: %s", __func__, pindexNew->ToString()); pcursor->Next(); } else { return error("%s: failed to read value", __func__); } } else { break; } } return true; } namespace { //! Legacy class to deserialize pre-pertxout database entries without reindex. class CCoins { public: //! whether transaction is a coinbase bool fCoinBase; //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped std::vector<CTxOut> vout; //! at which height this transaction was included in the active block chain int nHeight; //! empty constructor CCoins() : fCoinBase(false), vout(0), nHeight(0) { } template<typename Stream> void Unserialize(Stream &s) { unsigned int nCode = 0; // version int nVersionDummy; ::Unserialize(s, VARINT(nVersionDummy)); // header code ::Unserialize(s, VARINT(nCode)); fCoinBase = nCode & 1; std::vector<bool> vAvail(2, false); vAvail[0] = (nCode & 2) != 0; vAvail[1] = (nCode & 4) != 0; unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1); // spentness bitmask while (nMaskCode > 0) { unsigned char chAvail = 0; ::Unserialize(s, chAvail); for (unsigned int p = 0; p < 8; p++) { bool f = (chAvail & (1 << p)) != 0; vAvail.push_back(f); } if (chAvail != 0) nMaskCode--; } // txouts themself vout.assign(vAvail.size(), CTxOut()); for (unsigned int i = 0; i < vAvail.size(); i++) { if (vAvail[i]) ::Unserialize(s, REF(CTxOutCompressor(vout[i]))); } // coinbase height ::Unserialize(s, VARINT(nHeight)); } }; } /** Upgrade the database from older formats. * * Currently implemented: from the per-tx utxo model (0.8..0.14.x) to per-txout. */ bool CCoinsViewDB::Upgrade() { std::unique_ptr<CDBIterator> pcursor(db.NewIterator()); pcursor->Seek(std::make_pair(DB_COINS, uint256())); if (!pcursor->Valid()) { return true; } int64_t count = 0; LogPrintf("Upgrading utxo-set database...\n"); LogPrintf("[0%%]..."); size_t batch_size = 1 << 24; CDBBatch batch(db); uiInterface.SetProgressBreakAction(StartShutdown); int reportDone = 0; std::pair<unsigned char, uint256> key; std::pair<unsigned char, uint256> prev_key = {DB_COINS, uint256()}; while (pcursor->Valid()) { boost::this_thread::interruption_point(); if (ShutdownRequested()) { break; } if (pcursor->GetKey(key) && key.first == DB_COINS) { if (count++ % 256 == 0) { uint32_t high = 0x100 * *key.second.begin() + *(key.second.begin() + 1); int percentageDone = (int)(high * 100.0 / 65536.0 + 0.5); uiInterface.ShowProgress(_("Upgrading UTXO database") + "\n"+ _("(press q to shutdown and continue later)") + "\n", percentageDone); if (reportDone < percentageDone/10) { // report max. every 10% step LogPrintf("[%d%%]...", percentageDone); reportDone = percentageDone/10; } } CCoins old_coins; if (!pcursor->GetValue(old_coins)) { return error("%s: cannot parse CCoins record", __func__); } COutPoint outpoint(key.second, 0); for (size_t i = 0; i < old_coins.vout.size(); ++i) { if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) { Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase); outpoint.n = i; CoinEntry entry(&outpoint); batch.Write(entry, newcoin); } } batch.Erase(key); if (batch.SizeEstimate() > batch_size) { db.WriteBatch(batch); batch.Clear(); db.CompactRange(prev_key, key); prev_key = key; } pcursor->Next(); } else { break; } } db.WriteBatch(batch); db.CompactRange({DB_COINS, uint256()}, key); uiInterface.SetProgressBreakAction(std::function<void(void)>()); LogPrintf("[%s].\n", ShutdownRequested() ? "CANCELLED" : "DONE"); return !ShutdownRequested(); }
#include<bits/stdc++.h> #include<stdint.h> using namespace std; #define IOS {cin.tie(0);ios_base::sync_with_stdio(false);} #define N 25 struct point{ int x,y; }in[N]; int n; int ans[N]; double dis[N][N]; double dp[N][1<<N]; int x[N],y[N]; inline double chk(int l,int r,double now){ if(l != 0) now += dis[ans[r]][ans[l-1]] - dis[ans[l]][ans[l-1]]; if(r != n-1) now += dis[ans[l]][ans[r+1]] - dis[ans[r]][ans[r+1]]; return now; } int main() { mt19937 rd(time(NULL)); srand(time(NULL)); //IOS; int T,t; double mn,z; cin >> T; while(T--){ cin >> n; cout << n << ' '; for(int i=0;i<n;i++) cin >> in[i].x >> in[i].y,ans[i] = i; for(int i=0;i<n;i++) for(int j=0;j<n;j++) dis[i][j] = hypot(in[i].x-in[j].x,in[i].y-in[j].y); if(n <= 20){ cout << "H"; for(int i=0;i<n;i++){ fill(dp[i],dp[i]+(1<<n),1e20); dp[i][1<<i] = 0; } for(int s=1;s<1<<n;s++) if(s != __lg(s)) for(int i=0;i<n;i++) if(s&(1<<i)) { for(int j=0;j<n;j++) if(s&(1<<j) && j != i){ dp[i][s] = min(dp[i][s],dp[j][s^(1<<i)] + dis[i][j]); } } double d = 1e20; for(int i=0;i<n;i++){ d = min(d,dp[i][(1<<n)-1]); } cout << fixed << setprecision(2) << d << '\n'; continue; } random_shuffle(ans,ans+n); mn = 0; for(int i=1;i<n;i++) mn += dis[ans[i]][ans[i-1]]; t = 1.3*pow(n,5)+.5; for(int i=0;i<t;i++){ int l = rd()%n, r = rd()%n; if(l == r) r = (r+1)%n; if(l > r) swap(l,r); z = chk(l,r,mn); if(mn > z) mn = z,reverse(ans+l,ans+r+1); } cout << fixed << setprecision(2) << mn << '\n'; } return 0; }
/* * Copyright (C) 2010 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 "java_nio_ByteOrder.h" #include "JNIHelp.h" #include "JniConstants.h" //static jboolean ByteOrder_isLittleEndian(JNIEnv*, jclass) { JNIEXPORT jboolean JNICALL Java_java_nio_ByteOrder_isLittleEndian(JNIEnv*, jclass) { int i = 1; return *reinterpret_cast<jbyte*> (&i) == 1; } /* by jshwang static JNINativeMethod gMethods[] = { NATIVE_METHOD(ByteOrder, isLittleEndian, "()Z"), }; int register_java_nio_ByteOrder(JNIEnv* env) { return jniRegisterNativeMethods(env, "java/nio/ByteOrder", gMethods, NELEM(gMethods)); } */ int register_java_nio_ByteOrder(JNIEnv*) { return JNI_OK; }
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "test/core/end2end/fixtures/proxy.h" #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include "src/core/lib/gpr/useful.h" #include "src/core/lib/gprpp/host_port.h" #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/gprpp/thd.h" #include "test/core/util/port.h" struct grpc_end2end_proxy { grpc_end2end_proxy() : cq(nullptr), server(nullptr), client(nullptr), shutdown(false), new_call(nullptr) { memset(&new_call_details, 0, sizeof(new_call_details)); memset(&new_call_metadata, 0, sizeof(new_call_metadata)); } grpc_core::Thread thd; grpc_core::UniquePtr<char> proxy_port; grpc_core::UniquePtr<char> server_port; grpc_completion_queue* cq; grpc_server* server; grpc_channel* client; int shutdown; /* requested call */ grpc_call* new_call; grpc_call_details new_call_details; grpc_metadata_array new_call_metadata; }; typedef struct { void (*func)(void* arg, int success); void* arg; } closure; typedef struct { gpr_refcount refs; grpc_end2end_proxy* proxy; grpc_call* c2p; grpc_call* p2s; grpc_metadata_array c2p_initial_metadata; grpc_metadata_array p2s_initial_metadata; grpc_byte_buffer* c2p_msg; grpc_byte_buffer* p2s_msg; grpc_metadata_array p2s_trailing_metadata; grpc_status_code p2s_status; grpc_slice p2s_status_details; int c2p_server_cancelled; } proxy_call; static void thread_main(void* arg); static void request_call(grpc_end2end_proxy* proxy); grpc_end2end_proxy* grpc_end2end_proxy_create(const grpc_end2end_proxy_def* def, grpc_channel_args* client_args, grpc_channel_args* server_args) { int proxy_port = grpc_pick_unused_port_or_die(); int server_port = grpc_pick_unused_port_or_die(); grpc_end2end_proxy* proxy = new grpc_end2end_proxy(); grpc_core::JoinHostPort(&proxy->proxy_port, "localhost", proxy_port); grpc_core::JoinHostPort(&proxy->server_port, "localhost", server_port); gpr_log(GPR_DEBUG, "PROXY ADDR:%s BACKEND:%s", proxy->proxy_port.get(), proxy->server_port.get()); proxy->cq = grpc_completion_queue_create_for_next(nullptr); proxy->server = def->create_server(proxy->proxy_port.get(), server_args); proxy->client = def->create_client(proxy->server_port.get(), client_args); grpc_server_register_completion_queue(proxy->server, proxy->cq, nullptr); grpc_server_start(proxy->server); grpc_call_details_init(&proxy->new_call_details); proxy->thd = grpc_core::Thread("grpc_end2end_proxy", thread_main, proxy); proxy->thd.Start(); request_call(proxy); return proxy; } static closure* new_closure(void (*func)(void* arg, int success), void* arg) { closure* cl = static_cast<closure*>(gpr_malloc(sizeof(*cl))); cl->func = func; cl->arg = arg; return cl; } static void shutdown_complete(void* arg, int /*success*/) { grpc_end2end_proxy* proxy = static_cast<grpc_end2end_proxy*>(arg); proxy->shutdown = 1; grpc_completion_queue_shutdown(proxy->cq); } void grpc_end2end_proxy_destroy(grpc_end2end_proxy* proxy) { grpc_server_shutdown_and_notify(proxy->server, proxy->cq, new_closure(shutdown_complete, proxy)); proxy->thd.Join(); grpc_server_destroy(proxy->server); grpc_channel_destroy(proxy->client); grpc_completion_queue_destroy(proxy->cq); grpc_call_details_destroy(&proxy->new_call_details); delete proxy; } static void unrefpc(proxy_call* pc, const char* /*reason*/) { if (gpr_unref(&pc->refs)) { grpc_call_unref(pc->c2p); grpc_call_unref(pc->p2s); grpc_metadata_array_destroy(&pc->c2p_initial_metadata); grpc_metadata_array_destroy(&pc->p2s_initial_metadata); grpc_metadata_array_destroy(&pc->p2s_trailing_metadata); grpc_slice_unref(pc->p2s_status_details); gpr_free(pc); } } static void refpc(proxy_call* pc, const char* /*reason*/) { gpr_ref(&pc->refs); } static void on_c2p_sent_initial_metadata(void* arg, int /*success*/) { proxy_call* pc = static_cast<proxy_call*>(arg); unrefpc(pc, "on_c2p_sent_initial_metadata"); } static void on_p2s_recv_initial_metadata(void* arg, int /*success*/) { proxy_call* pc = static_cast<proxy_call*>(arg); grpc_op op; grpc_call_error err; memset(&op, 0, sizeof(op)); if (!pc->proxy->shutdown) { op.op = GRPC_OP_SEND_INITIAL_METADATA; op.flags = 0; op.reserved = nullptr; op.data.send_initial_metadata.count = pc->p2s_initial_metadata.count; op.data.send_initial_metadata.metadata = pc->p2s_initial_metadata.metadata; refpc(pc, "on_c2p_sent_initial_metadata"); err = grpc_call_start_batch(pc->c2p, &op, 1, new_closure(on_c2p_sent_initial_metadata, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); } unrefpc(pc, "on_p2s_recv_initial_metadata"); } static void on_p2s_sent_initial_metadata(void* arg, int /*success*/) { proxy_call* pc = static_cast<proxy_call*>(arg); unrefpc(pc, "on_p2s_sent_initial_metadata"); } static void on_c2p_recv_msg(void* arg, int success); static void on_p2s_sent_message(void* arg, int success) { proxy_call* pc = static_cast<proxy_call*>(arg); grpc_op op; grpc_call_error err; grpc_byte_buffer_destroy(pc->c2p_msg); if (!pc->proxy->shutdown && success) { op.op = GRPC_OP_RECV_MESSAGE; op.flags = 0; op.reserved = nullptr; op.data.recv_message.recv_message = &pc->c2p_msg; refpc(pc, "on_c2p_recv_msg"); err = grpc_call_start_batch(pc->c2p, &op, 1, new_closure(on_c2p_recv_msg, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); } unrefpc(pc, "on_p2s_sent_message"); } static void on_p2s_sent_close(void* arg, int /*success*/) { proxy_call* pc = static_cast<proxy_call*>(arg); unrefpc(pc, "on_p2s_sent_close"); } static void on_c2p_recv_msg(void* arg, int success) { proxy_call* pc = static_cast<proxy_call*>(arg); grpc_op op; grpc_call_error err; if (!pc->proxy->shutdown && success) { if (pc->c2p_msg != nullptr) { op.op = GRPC_OP_SEND_MESSAGE; op.flags = 0; op.reserved = nullptr; op.data.send_message.send_message = pc->c2p_msg; refpc(pc, "on_p2s_sent_message"); err = grpc_call_start_batch( pc->p2s, &op, 1, new_closure(on_p2s_sent_message, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); } else { op.op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; op.flags = 0; op.reserved = nullptr; refpc(pc, "on_p2s_sent_close"); err = grpc_call_start_batch(pc->p2s, &op, 1, new_closure(on_p2s_sent_close, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); } } else { if (pc->c2p_msg != nullptr) { grpc_byte_buffer_destroy(pc->c2p_msg); } } unrefpc(pc, "on_c2p_recv_msg"); } static void on_p2s_recv_msg(void* arg, int success); static void on_c2p_sent_message(void* arg, int success) { proxy_call* pc = static_cast<proxy_call*>(arg); grpc_op op; grpc_call_error err; grpc_byte_buffer_destroy(pc->p2s_msg); if (!pc->proxy->shutdown && success) { op.op = GRPC_OP_RECV_MESSAGE; op.flags = 0; op.reserved = nullptr; op.data.recv_message.recv_message = &pc->p2s_msg; refpc(pc, "on_p2s_recv_msg"); err = grpc_call_start_batch(pc->p2s, &op, 1, new_closure(on_p2s_recv_msg, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); } unrefpc(pc, "on_c2p_sent_message"); } static void on_p2s_recv_msg(void* arg, int success) { proxy_call* pc = static_cast<proxy_call*>(arg); grpc_op op; grpc_call_error err; if (!pc->proxy->shutdown && success && pc->p2s_msg) { op.op = GRPC_OP_SEND_MESSAGE; op.flags = 0; op.reserved = nullptr; op.data.send_message.send_message = pc->p2s_msg; refpc(pc, "on_c2p_sent_message"); err = grpc_call_start_batch(pc->c2p, &op, 1, new_closure(on_c2p_sent_message, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); } else { grpc_byte_buffer_destroy(pc->p2s_msg); } unrefpc(pc, "on_p2s_recv_msg"); } static void on_c2p_sent_status(void* arg, int /*success*/) { proxy_call* pc = static_cast<proxy_call*>(arg); unrefpc(pc, "on_c2p_sent_status"); } static void on_p2s_status(void* arg, int success) { proxy_call* pc = static_cast<proxy_call*>(arg); grpc_op op; grpc_call_error err; if (!pc->proxy->shutdown) { GPR_ASSERT(success); op.op = GRPC_OP_SEND_STATUS_FROM_SERVER; op.flags = 0; op.reserved = nullptr; op.data.send_status_from_server.trailing_metadata_count = pc->p2s_trailing_metadata.count; op.data.send_status_from_server.trailing_metadata = pc->p2s_trailing_metadata.metadata; op.data.send_status_from_server.status = pc->p2s_status; op.data.send_status_from_server.status_details = &pc->p2s_status_details; refpc(pc, "on_c2p_sent_status"); err = grpc_call_start_batch(pc->c2p, &op, 1, new_closure(on_c2p_sent_status, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); } unrefpc(pc, "on_p2s_status"); } static void on_c2p_closed(void* arg, int /*success*/) { proxy_call* pc = static_cast<proxy_call*>(arg); unrefpc(pc, "on_c2p_closed"); } static void on_new_call(void* arg, int success) { grpc_end2end_proxy* proxy = static_cast<grpc_end2end_proxy*>(arg); grpc_call_error err; if (success) { grpc_op op; memset(&op, 0, sizeof(op)); proxy_call* pc = static_cast<proxy_call*>(gpr_malloc(sizeof(*pc))); memset(pc, 0, sizeof(*pc)); pc->proxy = proxy; GPR_SWAP(grpc_metadata_array, pc->c2p_initial_metadata, proxy->new_call_metadata); pc->c2p = proxy->new_call; pc->p2s = grpc_channel_create_call( proxy->client, pc->c2p, GRPC_PROPAGATE_DEFAULTS, proxy->cq, proxy->new_call_details.method, &proxy->new_call_details.host, proxy->new_call_details.deadline, nullptr); gpr_ref_init(&pc->refs, 1); op.reserved = nullptr; op.op = GRPC_OP_RECV_INITIAL_METADATA; op.flags = 0; op.data.recv_initial_metadata.recv_initial_metadata = &pc->p2s_initial_metadata; refpc(pc, "on_p2s_recv_initial_metadata"); err = grpc_call_start_batch(pc->p2s, &op, 1, new_closure(on_p2s_recv_initial_metadata, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); op.op = GRPC_OP_SEND_INITIAL_METADATA; op.flags = proxy->new_call_details.flags; op.data.send_initial_metadata.count = pc->c2p_initial_metadata.count; op.data.send_initial_metadata.metadata = pc->c2p_initial_metadata.metadata; refpc(pc, "on_p2s_sent_initial_metadata"); err = grpc_call_start_batch(pc->p2s, &op, 1, new_closure(on_p2s_sent_initial_metadata, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); op.op = GRPC_OP_RECV_MESSAGE; op.flags = 0; op.data.recv_message.recv_message = &pc->c2p_msg; refpc(pc, "on_c2p_recv_msg"); err = grpc_call_start_batch(pc->c2p, &op, 1, new_closure(on_c2p_recv_msg, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); op.op = GRPC_OP_RECV_MESSAGE; op.flags = 0; op.data.recv_message.recv_message = &pc->p2s_msg; refpc(pc, "on_p2s_recv_msg"); err = grpc_call_start_batch(pc->p2s, &op, 1, new_closure(on_p2s_recv_msg, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); op.op = GRPC_OP_RECV_STATUS_ON_CLIENT; op.flags = 0; op.data.recv_status_on_client.trailing_metadata = &pc->p2s_trailing_metadata; op.data.recv_status_on_client.status = &pc->p2s_status; op.data.recv_status_on_client.status_details = &pc->p2s_status_details; refpc(pc, "on_p2s_status"); err = grpc_call_start_batch(pc->p2s, &op, 1, new_closure(on_p2s_status, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); op.op = GRPC_OP_RECV_CLOSE_ON_SERVER; op.flags = 0; op.data.recv_close_on_server.cancelled = &pc->c2p_server_cancelled; refpc(pc, "on_c2p_closed"); err = grpc_call_start_batch(pc->c2p, &op, 1, new_closure(on_c2p_closed, pc), nullptr); GPR_ASSERT(err == GRPC_CALL_OK); request_call(proxy); grpc_call_details_destroy(&proxy->new_call_details); grpc_call_details_init(&proxy->new_call_details); unrefpc(pc, "init"); } else { GPR_ASSERT(proxy->new_call == nullptr); } } static void request_call(grpc_end2end_proxy* proxy) { proxy->new_call = nullptr; GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( proxy->server, &proxy->new_call, &proxy->new_call_details, &proxy->new_call_metadata, proxy->cq, proxy->cq, new_closure(on_new_call, proxy))); } static void thread_main(void* arg) { grpc_end2end_proxy* proxy = static_cast<grpc_end2end_proxy*>(arg); closure* cl; for (;;) { grpc_event ev = grpc_completion_queue_next( proxy->cq, gpr_inf_future(GPR_CLOCK_MONOTONIC), nullptr); switch (ev.type) { case GRPC_QUEUE_TIMEOUT: gpr_log(GPR_ERROR, "Should never reach here"); abort(); case GRPC_QUEUE_SHUTDOWN: return; case GRPC_OP_COMPLETE: cl = static_cast<closure*>(ev.tag); cl->func(cl->arg, ev.success); gpr_free(cl); break; } } } const char* grpc_end2end_proxy_get_client_target(grpc_end2end_proxy* proxy) { return proxy->proxy_port.get(); } const char* grpc_end2end_proxy_get_server_port(grpc_end2end_proxy* proxy) { return proxy->server_port.get(); }
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFileDialog> #include <QtCore> #include <QtGui> #include <QDebug> #include <QProcess> //#include <QProgressBar> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QString sourcefile = QFileDialog::getOpenFileName( this, "Select the PDF file that you wanna convert", "/home", "Source File (*.pdf)"); ui->sourceurl->setText(sourcefile); sourceurl = sourcefile; } void MainWindow::on_pushButton_3_clicked() { QString destfile = QFileDialog::getSaveFileName(this, tr("Save File"), "/home/", tr("Text Format (*.txt)")); ui->desturl->setText(destfile); desturl = destfile; } void MainWindow::on_pushButton_2_clicked() { QString convertcmd = "convert -density 300 "+sourceurl+" -depth 8 "+desturl+".tiff"; QProcess * exec = new QProcess(this); // connect(exec, SIGNAL(readyRead() ), this, SLOT( progress() ) ); exec->start(convertcmd); exec->waitForFinished(); exec->close(); qDebug()<<"TIFF Convert command done !"; QString tiffconv = "Converting..."; ui->status->setText(tiffconv); QString tesseractcmd = "tesseract "+desturl+".tiff "+desturl; exec->start(tesseractcmd); exec->waitForFinished(); exec->close(); qDebug() <<"Tesseract Command done !"; QString tessconv = "PDF to TXT conversion done !"; ui->status->setText(tessconv); exec->terminate(); delete exec; return; } //void MainWindow::progress() //{ // QProcess *pr = (QProcess*)sender(); // ui->progressBar->setValue( pr->readAll().toInt() ); //}
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "ConstructionWithInternalSource.hpp" #include "ConstructionWithInternalSource_Impl.hpp" #include "Model.hpp" #include "Material.hpp" #include "Material_Impl.hpp" #include "OpaqueMaterial.hpp" #include "ModelExtensibleGroup.hpp" #include "../utilities/core/Assert.hpp" #include <utilities/idd/OS_Construction_InternalSource_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> namespace openstudio { namespace model { namespace detail { ConstructionWithInternalSource_Impl::ConstructionWithInternalSource_Impl( const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : LayeredConstruction_Impl(idfObject, model, keepHandle) { OS_ASSERT(idfObject.iddObject().type() == ConstructionWithInternalSource::iddObjectType()); } ConstructionWithInternalSource_Impl::ConstructionWithInternalSource_Impl( const openstudio::detail::WorkspaceObject_Impl& other,Model_Impl* model,bool keepHandle) : LayeredConstruction_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == ConstructionWithInternalSource::iddObjectType()); } ConstructionWithInternalSource_Impl::ConstructionWithInternalSource_Impl( const ConstructionWithInternalSource_Impl& other,Model_Impl* model,bool keepHandle) : LayeredConstruction_Impl(other,model,keepHandle) {} const std::vector<std::string>& ConstructionWithInternalSource_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType ConstructionWithInternalSource_Impl::iddObjectType() const { return ConstructionWithInternalSource::iddObjectType(); } int ConstructionWithInternalSource_Impl::renderingColorIndex() const { return OS_Construction_InternalSourceFields::SurfaceRenderingName; } bool ConstructionWithInternalSource_Impl::eraseLayer(unsigned layerIndex) { if (this->numLayers() < 3){ return false; } bool result = LayeredConstruction_Impl::eraseLayer(layerIndex); if (result){ onNumLayersChanged(); } return result; } bool ConstructionWithInternalSource_Impl::setLayers(const std::vector<Material>& materials) { if (materials.size() < 2){ return false; } bool result = LayeredConstruction_Impl::setLayers(materials); if (result){ onNumLayersChanged(); } return result; } bool ConstructionWithInternalSource_Impl::setLayer(const ModelPartitionMaterial& modelPartitionMaterial) { return false; } int ConstructionWithInternalSource_Impl::sourcePresentAfterLayerNumber() const { boost::optional<int> value = getInt(OS_Construction_InternalSourceFields::SourcePresentAfterLayerNumber,true); OS_ASSERT(value); return value.get(); } bool ConstructionWithInternalSource_Impl::setSourcePresentAfterLayerNumber(int sourcePresentAfterLayerNumber) { if (sourcePresentAfterLayerNumber < 1 || sourcePresentAfterLayerNumber > (int)this->numLayers()){ return false; } bool result = setInt(OS_Construction_InternalSourceFields::SourcePresentAfterLayerNumber,sourcePresentAfterLayerNumber); return result; } int ConstructionWithInternalSource_Impl::temperatureCalculationRequestedAfterLayerNumber() const { boost::optional<int> value = getInt(OS_Construction_InternalSourceFields::TemperatureCalculationRequestedAfterLayerNumber,true); OS_ASSERT(value); return value.get(); } bool ConstructionWithInternalSource_Impl::setTemperatureCalculationRequestedAfterLayerNumber(int temperatureCalculationRequestedAfterLayerNumber) { if (temperatureCalculationRequestedAfterLayerNumber < 1 || temperatureCalculationRequestedAfterLayerNumber > (int)this->numLayers()){ return false; } bool result = setInt(OS_Construction_InternalSourceFields::TemperatureCalculationRequestedAfterLayerNumber,temperatureCalculationRequestedAfterLayerNumber); return result; } int ConstructionWithInternalSource_Impl::dimensionsForTheCTFCalculation() const { boost::optional<int> value = getInt(OS_Construction_InternalSourceFields::DimensionsfortheCTFCalculation,true); OS_ASSERT(value); return value.get(); } bool ConstructionWithInternalSource_Impl::setDimensionsForTheCTFCalculation(int dimensionsForTheCTFCalculation) { if (dimensionsForTheCTFCalculation < 1 || dimensionsForTheCTFCalculation > 2){ return false; } bool result = setInt(OS_Construction_InternalSourceFields::DimensionsfortheCTFCalculation,dimensionsForTheCTFCalculation); return result; } double ConstructionWithInternalSource_Impl::tubeSpacing() const { boost::optional<double> value = getDouble(OS_Construction_InternalSourceFields::TubeSpacing,true); OS_ASSERT(value); return value.get(); } Quantity ConstructionWithInternalSource_Impl::getTubeSpacing(bool returnIP) const { OSOptionalQuantity value = getQuantity(OS_Construction_InternalSourceFields::TubeSpacing,true,returnIP); OS_ASSERT(value.isSet()); return value.get(); } openstudio::Quantity ConstructionWithInternalSource_Impl::tubeSpacing_SI() const { return getTubeSpacing(false); } openstudio::Quantity ConstructionWithInternalSource_Impl::tubeSpacing_IP() const { return getTubeSpacing(true); } bool ConstructionWithInternalSource_Impl::setTubeSpacing(double tubeSpacing) { bool result = setDouble(OS_Construction_InternalSourceFields::TubeSpacing,tubeSpacing); return result; } bool ConstructionWithInternalSource_Impl::setTubeSpacing(const Quantity& tubeSpacing) { OptionalDouble value = getDoubleFromQuantity(OS_Construction_InternalSourceFields::TubeSpacing,tubeSpacing); if (!value) { return false; } return setTubeSpacing(value.get()); } ConstructionWithInternalSource ConstructionWithInternalSource_Impl::reverseConstructionWithInternalSource() const { MaterialVector reverseLayers(this->layers()); std::reverse(reverseLayers.begin(), reverseLayers.end()); int numLayers = (int)this->numLayers(); int reverseSourcePresentAfterLayerNumber = numLayers - this->sourcePresentAfterLayerNumber(); int reverseTemperatureCalculationRequestedAfterLayerNumber = numLayers - this->temperatureCalculationRequestedAfterLayerNumber(); int dimensionsForTheCTFCalculation = this->dimensionsForTheCTFCalculation(); double tubeSpacing = this->tubeSpacing(); Model model = this->model(); for (const ConstructionWithInternalSource& other : model.getConcreteModelObjects<ConstructionWithInternalSource>()) { if (other.sourcePresentAfterLayerNumber() != reverseSourcePresentAfterLayerNumber){ continue; } if (other.temperatureCalculationRequestedAfterLayerNumber() != reverseTemperatureCalculationRequestedAfterLayerNumber){ continue; } if (other.dimensionsForTheCTFCalculation() != dimensionsForTheCTFCalculation){ continue; } if (other.tubeSpacing() != tubeSpacing){ continue; } MaterialVector layers = other.layers(); if (layers.size() != reverseLayers.size()){ continue; } bool test = true; for (unsigned i = 0; i < layers.size(); ++i){ if (layers[i].handle() != reverseLayers[i].handle()){ test = false; break; // break out of loop over layers } } if (test){ return other; } } // TODO: this should also copy (and modify) standards information object // no match, make one ConstructionWithInternalSource result(model); result.setName(this->name().get() + " Reversed"); result.setSourcePresentAfterLayerNumber(reverseSourcePresentAfterLayerNumber); result.setTemperatureCalculationRequestedAfterLayerNumber(reverseTemperatureCalculationRequestedAfterLayerNumber); result.setDimensionsForTheCTFCalculation(dimensionsForTheCTFCalculation); result.setTubeSpacing(tubeSpacing); result.setLayers(reverseLayers); return result; } void ConstructionWithInternalSource_Impl::onNumLayersChanged() { int numLayers = (int)this->numLayers(); if (this->sourcePresentAfterLayerNumber() > numLayers-1){ bool test = setString(OS_Construction_InternalSourceFields::SourcePresentAfterLayerNumber, ""); OS_ASSERT(test); } if (this->temperatureCalculationRequestedAfterLayerNumber() > numLayers-1){ bool test = setString(OS_Construction_InternalSourceFields::TemperatureCalculationRequestedAfterLayerNumber, ""); OS_ASSERT(test); } } } // detail ConstructionWithInternalSource::ConstructionWithInternalSource(const Model& model) : LayeredConstruction(ConstructionWithInternalSource::iddObjectType(),model) { OS_ASSERT(getImpl<detail::ConstructionWithInternalSource_Impl>()); } ConstructionWithInternalSource::ConstructionWithInternalSource(const std::vector<OpaqueMaterial>& opaqueMaterials) : LayeredConstruction(ConstructionWithInternalSource::iddObjectType(), (opaqueMaterials.empty() ? openstudio::model::Model() : opaqueMaterials.at(0).model())) { if (opaqueMaterials.empty()){ // DLM: do not remove, this was only added to a temporary model //this->remove(); LOG_AND_THROW("Cannot create an internal source construction with empty layers"); }else if (opaqueMaterials.size() < 2){ this->remove(); LOG_AND_THROW("Cannot create an internal source construction with fewer than 2 layers"); } else if (opaqueMaterials.size() > 10){ this->remove(); LOG_AND_THROW("Cannot create an internal source construction with more than 10 layers"); } std::vector<Material> materials = castVector<Material>(opaqueMaterials); bool ok = setLayers(materials); OS_ASSERT(ok); } IddObjectType ConstructionWithInternalSource::iddObjectType() { IddObjectType result(IddObjectType::OS_Construction_InternalSource); return result; } int ConstructionWithInternalSource::sourcePresentAfterLayerNumber() const { return getImpl<detail::ConstructionWithInternalSource_Impl>()->sourcePresentAfterLayerNumber(); } bool ConstructionWithInternalSource::setSourcePresentAfterLayerNumber(int sourcePresentAfterLayerNumber) { return getImpl<detail::ConstructionWithInternalSource_Impl>()->setSourcePresentAfterLayerNumber(sourcePresentAfterLayerNumber); } int ConstructionWithInternalSource::temperatureCalculationRequestedAfterLayerNumber() const { return getImpl<detail::ConstructionWithInternalSource_Impl>()->temperatureCalculationRequestedAfterLayerNumber(); } bool ConstructionWithInternalSource::setTemperatureCalculationRequestedAfterLayerNumber(int temperatureCalculationRequestedAfterLayerNumber) { return getImpl<detail::ConstructionWithInternalSource_Impl>()->setTemperatureCalculationRequestedAfterLayerNumber(temperatureCalculationRequestedAfterLayerNumber); } int ConstructionWithInternalSource::dimensionsForTheCTFCalculation() const { return getImpl<detail::ConstructionWithInternalSource_Impl>()->dimensionsForTheCTFCalculation(); } bool ConstructionWithInternalSource::setDimensionsForTheCTFCalculation(int dimensionsForTheCTFCalculation) { return getImpl<detail::ConstructionWithInternalSource_Impl>()->setDimensionsForTheCTFCalculation(dimensionsForTheCTFCalculation); } double ConstructionWithInternalSource::tubeSpacing() const { return getImpl<detail::ConstructionWithInternalSource_Impl>()->tubeSpacing(); } bool ConstructionWithInternalSource::setTubeSpacing(double tubeSpacing) { return getImpl<detail::ConstructionWithInternalSource_Impl>()->setTubeSpacing(tubeSpacing); } ConstructionWithInternalSource ConstructionWithInternalSource::reverseConstructionWithInternalSource() const { return getImpl<detail::ConstructionWithInternalSource_Impl>()->reverseConstructionWithInternalSource(); } /// @cond ConstructionWithInternalSource::ConstructionWithInternalSource( std::shared_ptr<detail::ConstructionWithInternalSource_Impl> impl) : LayeredConstruction(impl) {} /// @endcond } // model } // openstudio
#include "FileUtils.h" #include "File.h" #include "FileReaderImpl.h" #include "FileWriterImpl.h" #include "FileImpl.h" #include "Engine.h" #include "Constant.h" #include <iostream> #include <string> void display(std::tuple<std::unordered_set<std::string>, std::unordered_set<std::string>, std::unordered_set<std::string>> result) { auto added_list = std::get<0>(result); auto changed_list = std::get<1>(result); auto removed_list = std::get<2>(result); std::cout << "Added\n"; for (const auto& add : added_list) { std::cout << add << "\n"; } std::cout << "====================\n"; std::cout << "Changed\n"; for (const auto& changed : changed_list) { std::cout << changed << "\n"; } std::cout << "====================\n"; std::cout << "Removed\n"; for (const auto& removed : removed_list) { std::cout << removed << "\n"; } std::cout << "====================\n"; } int main(int argc,char* argv[]) { if (argc != 3) { return 0; } std::string command = argv[1]; std::string path = argv[2]; if (path == "") { return 0; } FileDetection::Engine engine{}; if (command == "save") { engine.generate(path, FileDetection::get_special_folder_name()); } else if (command == "detect") { display(engine.detect(path, FileDetection::get_special_folder_name())); } return 0; }
#include "includesframe.h" #include "ui_includesframe.h" #include "Serialization/sourcecodebuilder.h" IncludesFrame::IncludesFrame(QWidget *parent) : QFrame(parent), ui(new Ui::IncludesFrame) { ui->setupUi(this); ui->textEdit->setText(SourceCodeBuilder::imports); this->setWindowTitle("Includes"); } IncludesFrame::~IncludesFrame() { delete ui; } void IncludesFrame::on_pushButton_clicked() { SourceCodeBuilder::imports = ui->textEdit->toPlainText(); this->close(); }
#include <algorithm> #include <functional> #include <string> #include <vector> using namespace std; class Solution { public: vector<string> findRelativeRanks(vector<int> &nums) { vector<pair<int, int>> v; //{score,index} int N = nums.size(); for (int i = 0; i < N; ++i) v.push_back({nums[i], i}); sort(v.begin(), v.end(), greater<pair<int, int>>()); vector<string> winner = {"Gold Medal", "Silver Medal", "Bronze Medal"}, res(N); for (int i = 0; i < min(3, N); ++i) res[v[i].second] = winner[i]; for (int i = 3; i < N; ++i) res[v[i].second] = to_string(i + 1); return res; } };
//------------------------------------------------------------------------------ // physics/hinge2joint.cc // (C) 2005 RadonLabs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "physics/hinge2joint.h" #include "debugrender/debugshaperenderer.h" namespace Physics { __ImplementClass(Physics::Hinge2Joint, 'PH2J', Physics::Joint); using namespace Math; using namespace Debug; //------------------------------------------------------------------------------ /** */ Hinge2Joint::Hinge2Joint() : Joint(Joint::Hinge2Joint), suspErp(0.2f), suspCfm(0.0f), axisParams(2) { this->axisParams[0].SetAxis(Math::vector(0.0f, 1.0f, 0.0f)); this->axisParams[1].SetAxis(Math::vector(0.0f, 0.0f, 1.0f)); } //------------------------------------------------------------------------------ /** */ Hinge2Joint::~Hinge2Joint() { // empty } //------------------------------------------------------------------------------ /** NOTE: it is important that rigid bodies are added (happens in Joint::Attach()) before joint transforms are set!!! */ void Hinge2Joint::Attach(dWorldID worldID, dJointGroupID groupID, const Math::matrix44& m) { // create ODE joint this->odeJointId = dJointCreateHinge2(worldID, groupID); // configure ODE joint int i; for (i = 0; i < 2; i++) { const JointAxis& curAxis = this->axisParams[i]; if (curAxis.IsLoStopEnabled()) { dJointSetHinge2Param(this->odeJointId, dParamLoStop + dParamGroup * i, curAxis.GetLoStop()); } if (curAxis.IsHiStopEnabled()) { dJointSetHinge2Param(this->odeJointId, dParamHiStop + dParamGroup * i, curAxis.GetHiStop()); } dJointSetHinge2Param(this->odeJointId, dParamVel + dParamGroup * i, curAxis.GetVelocity()); dJointSetHinge2Param(this->odeJointId, dParamFMax + dParamGroup * i, curAxis.GetFMax()); dJointSetHinge2Param(this->odeJointId, dParamFudgeFactor + dParamGroup * i, curAxis.GetFudgeFactor()); dJointSetHinge2Param(this->odeJointId, dParamBounce + dParamGroup * i, curAxis.GetBounce()); dJointSetHinge2Param(this->odeJointId, dParamCFM + dParamGroup * i, curAxis.GetCFM()); dJointSetHinge2Param(this->odeJointId, dParamStopERP + dParamGroup * i, curAxis.GetStopERP()); dJointSetHinge2Param(this->odeJointId, dParamStopCFM + dParamGroup * i, curAxis.GetStopCFM()); } dJointSetHinge2Param(this->odeJointId, dParamSuspensionERP, this->suspErp); dJointSetHinge2Param(this->odeJointId, dParamSuspensionCFM, this->suspCfm); // hand to parent class Joint::Attach(worldID, groupID, m); // configure ODE joint this->UpdateTransform(m); } //------------------------------------------------------------------------------ /** */ void Hinge2Joint::UpdateTransform(const Math::matrix44& m) { Math::vector p = matrix44::transform(this->GetAnchor(), m); dJointSetHinge2Anchor(this->odeJointId, p.x(), p.y(), p.z()); matrix44 m44(m.get_xaxis(), m.get_yaxis(), m.get_zaxis(), vector::nullvec()); Math::vector a0 = matrix44::transform(this->axisParams[0].GetAxis(), m44); Math::vector a1 = matrix44::transform(this->axisParams[1].GetAxis(), m44); dJointSetHinge2Axis1(this->odeJointId, a0.x(), a0.y(), a0.z()); dJointSetHinge2Axis2(this->odeJointId, a1.x(), a1.y(), a1.z()); } //------------------------------------------------------------------------------ /** */ void Hinge2Joint::RenderDebug() { if (this->IsAttached()) { // compute resulting model matrix Math::matrix44 m = Math::matrix44::identity(); dVector3 curAnchor; dJointGetHinge2Anchor(this->odeJointId, curAnchor); m.scale(Math::vector(0.1f, 0.1f, 0.1f)); m.translate(Math::vector(curAnchor[0], curAnchor[1], curAnchor[2])); DebugShapeRenderer::Instance()->DrawSphere(m, this->GetDebugVisualizationColor()); } } }; // namespace Physics
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "JSTestMediaQueryListListener.h" #include "ExceptionCode.h" #include "JSDOMBinding.h" #include "MediaQueryListListener.h" #include "TestMediaQueryListListener.h" #include <runtime/Error.h> #include <wtf/GetPtr.h> using namespace JSC; namespace WebCore { ASSERT_CLASS_FITS_IN_CELL(JSTestMediaQueryListListener); ASSERT_HAS_TRIVIAL_DESTRUCTOR(JSTestMediaQueryListListener); /* Hash table */ static const HashTableValue JSTestMediaQueryListListenerTableValues[] = { { "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestMediaQueryListListenerConstructor), (intptr_t)0, NoIntrinsic }, { 0, 0, 0, 0, NoIntrinsic } }; static const HashTable JSTestMediaQueryListListenerTable = { 2, 1, JSTestMediaQueryListListenerTableValues, 0 }; /* Hash table for constructor */ static const HashTableValue JSTestMediaQueryListListenerConstructorTableValues[] = { { 0, 0, 0, 0, NoIntrinsic } }; static const HashTable JSTestMediaQueryListListenerConstructorTable = { 1, 0, JSTestMediaQueryListListenerConstructorTableValues, 0 }; ASSERT_HAS_TRIVIAL_DESTRUCTOR(JSTestMediaQueryListListenerConstructor); const ClassInfo JSTestMediaQueryListListenerConstructor::s_info = { "TestMediaQueryListListenerConstructor", &Base::s_info, &JSTestMediaQueryListListenerConstructorTable, 0, CREATE_METHOD_TABLE(JSTestMediaQueryListListenerConstructor) }; JSTestMediaQueryListListenerConstructor::JSTestMediaQueryListListenerConstructor(Structure* structure, JSDOMGlobalObject* globalObject) : DOMConstructorObject(structure, globalObject) { } void JSTestMediaQueryListListenerConstructor::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject) { Base::finishCreation(exec->globalData()); ASSERT(inherits(&s_info)); putDirect(exec->globalData(), exec->propertyNames().prototype, JSTestMediaQueryListListenerPrototype::self(exec, globalObject), DontDelete | ReadOnly); } bool JSTestMediaQueryListListenerConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<JSTestMediaQueryListListenerConstructor, JSDOMWrapper>(exec, &JSTestMediaQueryListListenerConstructorTable, static_cast<JSTestMediaQueryListListenerConstructor*>(cell), propertyName, slot); } bool JSTestMediaQueryListListenerConstructor::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor<JSTestMediaQueryListListenerConstructor, JSDOMWrapper>(exec, &JSTestMediaQueryListListenerConstructorTable, static_cast<JSTestMediaQueryListListenerConstructor*>(object), propertyName, descriptor); } /* Hash table for prototype */ static const HashTableValue JSTestMediaQueryListListenerPrototypeTableValues[] = { { "method", DontDelete | JSC::Function, (intptr_t)static_cast<NativeFunction>(jsTestMediaQueryListListenerPrototypeFunctionMethod), (intptr_t)1, NoIntrinsic }, { 0, 0, 0, 0, NoIntrinsic } }; static const HashTable JSTestMediaQueryListListenerPrototypeTable = { 2, 1, JSTestMediaQueryListListenerPrototypeTableValues, 0 }; const ClassInfo JSTestMediaQueryListListenerPrototype::s_info = { "TestMediaQueryListListenerPrototype", &Base::s_info, &JSTestMediaQueryListListenerPrototypeTable, 0, CREATE_METHOD_TABLE(JSTestMediaQueryListListenerPrototype) }; JSObject* JSTestMediaQueryListListenerPrototype::self(ExecState* exec, JSGlobalObject* globalObject) { return getDOMPrototype<JSTestMediaQueryListListener>(exec, globalObject); } bool JSTestMediaQueryListListenerPrototype::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { JSTestMediaQueryListListenerPrototype* thisObject = jsCast<JSTestMediaQueryListListenerPrototype*>(cell); return getStaticFunctionSlot<JSObject>(exec, &JSTestMediaQueryListListenerPrototypeTable, thisObject, propertyName, slot); } bool JSTestMediaQueryListListenerPrototype::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { JSTestMediaQueryListListenerPrototype* thisObject = jsCast<JSTestMediaQueryListListenerPrototype*>(object); return getStaticFunctionDescriptor<JSObject>(exec, &JSTestMediaQueryListListenerPrototypeTable, thisObject, propertyName, descriptor); } const ClassInfo JSTestMediaQueryListListener::s_info = { "TestMediaQueryListListener", &Base::s_info, &JSTestMediaQueryListListenerTable, 0 , CREATE_METHOD_TABLE(JSTestMediaQueryListListener) }; JSTestMediaQueryListListener::JSTestMediaQueryListListener(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<TestMediaQueryListListener> impl) : JSDOMWrapper(structure, globalObject) , m_impl(impl.leakRef()) { } void JSTestMediaQueryListListener::finishCreation(JSGlobalData& globalData) { Base::finishCreation(globalData); ASSERT(inherits(&s_info)); } JSObject* JSTestMediaQueryListListener::createPrototype(ExecState* exec, JSGlobalObject* globalObject) { return JSTestMediaQueryListListenerPrototype::create(exec->globalData(), globalObject, JSTestMediaQueryListListenerPrototype::createStructure(globalObject->globalData(), globalObject, globalObject->objectPrototype())); } bool JSTestMediaQueryListListener::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { JSTestMediaQueryListListener* thisObject = jsCast<JSTestMediaQueryListListener*>(cell); ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info); return getStaticValueSlot<JSTestMediaQueryListListener, Base>(exec, &JSTestMediaQueryListListenerTable, thisObject, propertyName, slot); } bool JSTestMediaQueryListListener::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { JSTestMediaQueryListListener* thisObject = jsCast<JSTestMediaQueryListListener*>(object); ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info); return getStaticValueDescriptor<JSTestMediaQueryListListener, Base>(exec, &JSTestMediaQueryListListenerTable, thisObject, propertyName, descriptor); } JSValue jsTestMediaQueryListListenerConstructor(ExecState* exec, JSValue slotBase, const Identifier&) { JSTestMediaQueryListListener* domObject = static_cast<JSTestMediaQueryListListener*>(asObject(slotBase)); return JSTestMediaQueryListListener::getConstructor(exec, domObject->globalObject()); } JSValue JSTestMediaQueryListListener::getConstructor(ExecState* exec, JSGlobalObject* globalObject) { return getDOMConstructor<JSTestMediaQueryListListenerConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject)); } EncodedJSValue JSC_HOST_CALL jsTestMediaQueryListListenerPrototypeFunctionMethod(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestMediaQueryListListener::s_info)) return throwVMTypeError(exec); JSTestMediaQueryListListener* castedThis = static_cast<JSTestMediaQueryListListener*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestMediaQueryListListener::s_info); TestMediaQueryListListener* impl = static_cast<TestMediaQueryListListener*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); RefPtr<MediaQueryListListener> listener(MediaQueryListListener::create(ScriptValue(exec->globalData(), MAYBE_MISSING_PARAMETER(exec, 0, MissingIsUndefined)))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->method(listener); return JSValue::encode(jsUndefined()); } static inline bool isObservable(JSTestMediaQueryListListener* jsTestMediaQueryListListener) { if (jsTestMediaQueryListListener->hasCustomProperties()) return true; return false; } bool JSTestMediaQueryListListenerOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor) { JSTestMediaQueryListListener* jsTestMediaQueryListListener = static_cast<JSTestMediaQueryListListener*>(handle.get().asCell()); if (!isObservable(jsTestMediaQueryListListener)) return false; UNUSED_PARAM(visitor); return false; } void JSTestMediaQueryListListenerOwner::finalize(JSC::Handle<JSC::Unknown> handle, void* context) { JSTestMediaQueryListListener* jsTestMediaQueryListListener = static_cast<JSTestMediaQueryListListener*>(handle.get().asCell()); DOMWrapperWorld* world = static_cast<DOMWrapperWorld*>(context); uncacheWrapper(world, jsTestMediaQueryListListener->impl(), jsTestMediaQueryListListener); jsTestMediaQueryListListener->releaseImpl(); } JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, TestMediaQueryListListener* impl) { return wrap<JSTestMediaQueryListListener>(exec, globalObject, impl); } TestMediaQueryListListener* toTestMediaQueryListListener(JSC::JSValue value) { return value.inherits(&JSTestMediaQueryListListener::s_info) ? static_cast<JSTestMediaQueryListListener*>(asObject(value))->impl() : 0; } }
// -*- C++ -*- #include "ACEXML/common/Encoding.h" #include "ace/OS_NS_string.h" const ACEXML_Char* ACEXML_Encoding::encoding_names_[8] = { ACE_TEXT ("UCS-4BE"), ACE_TEXT ("UCS-4LE"), ACE_TEXT ("UCS-4_2143"), ACE_TEXT ("UCS-4_3412"), ACE_TEXT ("UTF-16"), ACE_TEXT ("UTF-16"), ACE_TEXT ("UTF-8"), ACE_TEXT ("Unsupported Encoding") }; const ACEXML_UTF8 ACEXML_Encoding::byte_order_mark_[][4] = { { '\x00', '\x00', '\xFE', '\xFF' }, // UCS-4, big-endian (1234 order) { '\xFF', '\xFE', '\x00', '\x00' }, // UCS-4, little-endian (4321 order) { '\x00', '\x00', '\xFF', '\xFE' }, // UCS-4, unusual octet order (2143) { '\xFE', '\xFF', '\x00', '\x00' }, // UCS-4, unusual octet order (3412) { '\xFE', '\xFF', '\xFF', '\xFF' }, // UTF-16, big-endian (3 & 4 != 0) { '\xFF', '\xFE', '\xFF', '\xFF' }, // UTF-16, little-endian ( 3 & 4 != 0) { '\xEF', '\xBB', '\xBF', '\xFF' } // UTF-8 }; const ACEXML_UTF8 ACEXML_Encoding::magic_values_[][4] = { { '\x00', '\x00', '\x00', '\x3c' }, // { '\x3c', '\x00', '\x00', '\x00' }, // UCS-4 and variants { '\x00', '\x00', '\x3c', '\x00' }, // { '\x00', '\x3c', '\x00', '\x00' }, // { '\x00', '\x3c', '\x00', '\x3f' }, // UTF-16BE { '\x3c', '\x00', '\x3f', '\x00' }, // UTF-16LE { '\x3c', '\x3f', '\x78', '\x6d' }, // UTF-8 }; const ACEXML_Char* ACEXML_Encoding::get_encoding (const char* input) { if ((ACE_OS::memcmp (&ACEXML_Encoding::byte_order_mark_[ACEXML_Encoding::UTF16BE][0], input, 2) == 0) && (input[2] != 0 || input[3] != 0)) // 3 & 4 should not be both zero return ACEXML_Encoding::encoding_names_[ACEXML_Encoding::UTF16BE]; else if ((ACE_OS::memcmp (&ACEXML_Encoding::byte_order_mark_[ACEXML_Encoding::UTF16LE][0], input, 2) == 0) && (input[2] != 0 || input[3] != 0)) // 3 & 4 should not be both zero return ACEXML_Encoding::encoding_names_[ACEXML_Encoding::UTF16LE]; else if (ACE_OS::memcmp (&ACEXML_Encoding::byte_order_mark_[ACEXML_Encoding::UTF8][0], input, 3) == 0) return ACEXML_Encoding::encoding_names_[ACEXML_Encoding::UTF8]; else if (ACE_OS::memcmp (&ACEXML_Encoding::magic_values_[ACEXML_Encoding::UTF16BE][0], input, 4) == 0) return ACEXML_Encoding::encoding_names_[ACEXML_Encoding::UTF16BE]; else if (ACE_OS::memcmp (&ACEXML_Encoding::magic_values_[ACEXML_Encoding::UTF16LE][0], input, 4) == 0) return ACEXML_Encoding::encoding_names_[ACEXML_Encoding::UTF16LE]; else if (ACE_OS::memcmp (&ACEXML_Encoding::magic_values_[ACEXML_Encoding::UTF8][0], input, 4) == 0) return ACEXML_Encoding::encoding_names_[ACEXML_Encoding::UTF8]; else { // ACE_ERROR ((LM_ERROR, "Unknown encoding. Assuming UTF-8\n")); return ACEXML_Encoding::encoding_names_[ACEXML_Encoding::UTF8]; } }
/* * SPDX-License-Identifier: Apache-2.0 */ //===----------------LRN.cpp - Lowering LRN Op----------------------=== // // // Copyright 2020 The IBM Research Authors. // // ============================================================================= // // This file lowers the ONNX LRN Operator to Krnl dialect. // //===----------------------------------------------------------------------===// #include "src/Conversion/ONNXToKrnl/ONNXToKrnlCommon.hpp" #include "src/Dialect/ONNX/ONNXShapeHelper.hpp" using namespace mlir; struct ONNXLRNOpLowering : public ConversionPattern { ONNXLRNOpLowering(MLIRContext *ctx) : ConversionPattern(mlir::ONNXLRNOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { ONNXLRNOpAdaptor operandAdaptor(operands); ONNXLRNOp lrnOp = llvm::cast<ONNXLRNOp>(op); auto loc = op->getLoc(); ONNXLRNOpShapeHelper shapeHelper(&lrnOp, &rewriter); auto shapecomputed = shapeHelper.Compute(operandAdaptor); (void)shapecomputed; assert(!failed(shapecomputed) && "expected to succeed"); auto resultOperand = lrnOp.Y(); auto outputMemRefType = convertToMemRefType(*op->result_type_begin()); auto outputMemRefShape = outputMemRefType.getShape(); auto elementType = outputMemRefType.getElementType(); int64_t outputRank = outputMemRefShape.size(); Value input = operandAdaptor.X(); float biasLit = lrnOp.bias().convertToFloat(); float alphaLit = lrnOp.alpha().convertToFloat(); float betaLit = lrnOp.beta().convertToFloat(); float sizeLit = (float)lrnOp.size(); auto f32Type = FloatType::getF32(rewriter.getContext()); Value biasValue = emitConstantOp(rewriter, loc, f32Type, biasLit); Value alphaDivSizeValue = emitConstantOp(rewriter, loc, f32Type, alphaLit / sizeLit); Value betaValue = emitConstantOp(rewriter, loc, f32Type, betaLit); Value alloc = insertAllocAndDeallocSimple( rewriter, op, outputMemRefType, loc, shapeHelper.dimsForOutput(0)); BuildKrnlLoop outputLoops(rewriter, loc, outputRank); outputLoops.createDefineOp(); outputLoops.pushAllBounds(shapeHelper.dimsForOutput(0)); outputLoops.createIterateOp(); rewriter.setInsertionPointToStart(outputLoops.getIterateBlock()); // Insert computation of square_sum. // square_sum[n, c, d1, ..., dk] = sum(X[n, i, d1, ..., dk] ^ 2), // where max(0, c - floor((size - 1) / 2)) <= i // and i<= min(C - 1, c + ceil((size - 1) / 2)). // Get a child IndexExpr context. IndexExprContext childContext(shapeHelper.context); // Compute the lower bound and upper bound for square_sum. const int loopIndexForC = 1; Value cValue = outputLoops.getInductionVar(loopIndexForC); IndexExpr cIE = childContext.createLoopInductionIndex(cValue); IndexExpr sizeIE = childContext.createDimIndexFromShapedType(input, loopIndexForC); SmallVector<IndexExpr, 2> lbMaxList; lbMaxList.emplace_back(childContext.createLiteralIndex(0)); lbMaxList.emplace_back( cIE - (sizeIE - 1).floorDiv(childContext.createLiteralIndex(2))); SmallVector<IndexExpr, 2> ubMinList; ubMinList.emplace_back(sizeIE); ubMinList.emplace_back( cIE + 1 + (sizeIE - 1).ceilDiv(childContext.createLiteralIndex(2))); // Initialize sum MemRefType scalarMemRefType = MemRefType::get({}, elementType, {}, 0); Value sumAlloc = rewriter.create<AllocOp>(loc, scalarMemRefType); rewriter.create<KrnlStoreOp>(loc, emitConstantOp(rewriter, loc, elementType, 0), sumAlloc, ArrayRef<Value>{}); // Create the sum reduction loop BuildKrnlLoop sumLoops(rewriter, loc, 1); sumLoops.createDefineOp(); sumLoops.pushBounds(lbMaxList, ubMinList); sumLoops.createIterateOp(); auto outputLoopBody = rewriter.saveInsertionPoint(); rewriter.setInsertionPointToStart(sumLoops.getIterateBlock()); // Compute quare-sum value SmallVector<Value, 4> loadIndices; for (int i = 0; i < outputRank; i++) { if (i == loopIndexForC) { Value loopVal = sumLoops.getInductionVar(0); loadIndices.emplace_back(loopVal); } else { Value loopVal = outputLoops.getInductionVar(i); loadIndices.emplace_back(loopVal); } } Value loadVal = rewriter.create<KrnlLoadOp>(loc, input, loadIndices); Value squareVal = rewriter.create<MulFOp>(loc, loadVal, loadVal); Value sumValue = rewriter.create<KrnlLoadOp>(loc, sumAlloc, ArrayRef<Value>{}); sumValue = rewriter.create<AddFOp>(loc, sumValue, squareVal); rewriter.create<KrnlStoreOp>(loc, sumValue, sumAlloc, ArrayRef<Value>{}); // Compute and store the output // y = x / ((bias + (alpha / nsize) * square_sum) ** beta) rewriter.restoreInsertionPoint(outputLoopBody); SmallVector<Value, 4> storeIndices; for (int i = 0; i < outputRank; ++i) { storeIndices.emplace_back(outputLoops.getInductionVar(i)); } Value xValue = rewriter.create<KrnlLoadOp>(loc, input, storeIndices); sumValue = rewriter.create<KrnlLoadOp>(loc, sumAlloc, ArrayRef<Value>{}); Value tempValue = rewriter.create<PowFOp>(loc, rewriter.create<AddFOp>(loc, biasValue, rewriter.create<MulFOp>(loc, alphaDivSizeValue, sumValue)), betaValue); Value resultValue = rewriter.create<DivFOp>(loc, xValue, tempValue); rewriter.create<KrnlStoreOp>(loc, resultValue, alloc, storeIndices); rewriter.replaceOp(op, alloc); return success(); } }; void populateLoweringONNXLRNOpPattern( OwningRewritePatternList &patterns, MLIRContext *ctx) { patterns.insert<ONNXLRNOpLowering>(ctx); }
#include "../../head.h" class Solution { public: int nthUglyNumber(int n) { // plagiarizing from https://leetcode.com/problems/ugly-number-ii/discuss/69364/My-16ms-C%2B%2B-DP-solution-with-short-explanation if (n < 4) { return n; } std::vector<int> minMulti(n, 0); minMulti[0] = 1; //n = 1, return 1 int cnt2 = 0, cnt3 = 0, cnt5 = 0; // cnt2 record that the least index that can multiply 2 // cnt3 record that the least index that can multiply 3 // cnt5 record that the least index that can multiply 5 for (int index = 2; index <= n; index++) { minMulti[index - 1] = std::min(minMulti[cnt2] * 2, std::min(minMulti[cnt3] * 3, minMulti[cnt5] *5)); // std::cout << "cnt2: " << cnt2 << "\tcnt3: " << cnt3 << "\tcnt5: " << cnt5 << "\n"; // std::cout << "Ugly Number: " <<minMulti[index - 1] << "\tindex: " << index << "\n"; if (minMulti[index - 1] == minMulti[cnt2] * 2) { cnt2++; } if (minMulti[index - 1] == minMulti[cnt3] * 3) { cnt3++; } if (minMulti[index - 1] == minMulti[cnt5] *5) { cnt5++; } } return minMulti[n - 1]; } };
#include "./trailer_scene_filter.h" #define LOG_TAG "TrailerSceneFilter" /* TrailerSceneFilter class */ TrailerSceneFilter::TrailerSceneFilter() { textureFromCache = NULL; texId = -1; } TrailerSceneFilter::TrailerSceneFilter(int index, int64_t sequenceIn, int64_t sequenceOut, char* filterName) : ModelFilter(index, sequenceIn, sequenceOut, filterName) { textureFromCache = NULL; texId = -1; } TrailerSceneFilter::~TrailerSceneFilter() { clear(); } //由于iOS的时间传递过来是由Timer生成的传过来,是不准确的,所以这里只要大于sequenceIn就是要执行的 bool TrailerSceneFilter::isAvailable(float pos, bool (*pfnDetectGPUSurpportedEffect)(void* context), void* context){ int64_t position = pos * 1000000; if (position >= sequenceIn) { return true; } else { return false; } } bool TrailerSceneFilter::onInit() { //根据放入mMapParamValue 中key为sceneVideoPath的ParamVal 构造解码器 texId = -1; ParamVal val; endTimeInSecs = (double)this->sequenceOut / (double)1000000; duration = (float)(sequenceIn - sequenceOut) / (float)1000000; bool suc = this->getFilterParamValue(string(TRAILER_SCENE_PARAM_ID_DURATION), val); if (suc) { fadeInDuration = val.u.fltVal; LOGI("fadeInDuration is %f", fadeInDuration); } return true; } void TrailerSceneFilter::onRenderPre(float pos) { //第一次进来的时候 进行创建纹理操作 if (-1 == texId) { int width = 480; ParamVal val; bool suc = this->getFilterParamValue(string(TRAILER_SCENE_PARAM_ID_WIDTH), val); if (suc) { width = val.u.intVal; LOGI("get success, width:%d", width); } else{ LOGI("get width failed use default value %d", width); } int height = 480; suc = this->getFilterParamValue(string(TRAILER_SCENE_PARAM_ID_HEIGHT), val); if (suc) { height = val.u.intVal; LOGI("get success, height:%d", height); } else{ LOGI("get height failed use default value %d", height); } byte* pixels; suc = this->getFilterParamValue(string(TRAILER_SCENE_PARAM_ID_PIXELS), val); if (suc) { pixels = (byte*)(val.u.arbData); LOGI("get trailer overlay pixels success"); //Create Texture textureFromCache = GPUTextureCache::GetInstance()->fetchTexture(width, height); if (textureFromCache) { textureFromCache->lock(); texId = textureFromCache->getTexId(); glBindTexture(GL_TEXTURE_2D, texId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); delete[] pixels; //put texId to ParamVal paramValue; paramValue.type = EffectParamTypeInt; paramValue.u.intVal = texId; this->setFilterParamValue(TRAILER_SCENE_PARAM_ID_TEXTURE_ID, paramValue); } } else{ LOGI("get trailer overlay pixels failed"); } } //calculate TRANSITION_SCENE_PARAM_ID_PROGRESS float progress = 0.0; float timeDiff = pos - endTimeInSecs; if(timeDiff > 0){ progress = 1.0; }else if (timeDiff > duration) { progress = (fabs(duration) - fabs(timeDiff)) / fadeInDuration; progress = progress > 1.0f ? 1.0f : progress; } ParamVal paramValue; paramValue.type = EffectParamTypeFloat; paramValue.u.fltVal = progress; this->setFilterParamValue(TRAILER_SCENE_PARAM_ID_PROGRESS, paramValue); } void TrailerSceneFilter::clear() { //TODO:删除文字的Pixels if (textureFromCache) textureFromCache->unLock(); }
/* * atomic.{cc,hh} -- atomic integers * Eddie Kohler * * Copyright (c) 2000 Mazu Networks, Inc. * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/glue.hh> #include <click/atomic.hh>
#include <SFML/Graphics.hpp> #include "Engine.h" int main() { Engine* engine = new Engine(640, 480, 32, 32); try{ engine->Start(); } catch (char* e) {} return EXIT_SUCCESS; }
<?hh // strict /** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/bsd-license.php * @link http://titon.io */ namespace Titon\Route; use Titon\Route\Exception\NoMatchException; use ReflectionFunction; /** * The CallbackRoute works in a similar fashion to the default Route with the only difference being * that a callback is used for dispatching instead of an action. * * @package Titon\Route */ class CallbackRoute extends Route { /** * The callback to execute during dispatch. * * @var \Titon\Route\RouteCallback */ protected RouteCallback $callback; /** * Store the tokenized URL to match and the callback to dispatch to. * * @param string $path * @param \Titon\Route\RouteCallback $callback */ public function __construct(string $path, RouteCallback $callback) { $this->callback = $callback; parent::__construct($path, 'CallbackRoute@noop'); } /** * {@inheritdoc} */ public function dispatch(): mixed { if (!$this->isMatched()) { throw new NoMatchException('Route cannot be dispatched unless it has been matched'); } $callback = new ReflectionFunction($this->getCallback()); return $callback->invokeArgs($this->getArguments($callback)); } /** * Return the callback function. * * @return \Titon\Route\RouteCallback */ public function getCallback(): RouteCallback { return $this->callback; } /** * Set the callback function. * * @param \Titon\Route\RouteCallback $callback * @return $this */ public function setCallback(RouteCallback $callback): this { $this->callback = $callback; return $this; } }
#include "target_converter.h" #include "binarize_target.h" #include <catboost/libs/data/loader.h> // for IsMissingValue #include <catboost/libs/helpers/exception.h> #include <library/cpp/threading/local_executor/local_executor.h> #include <util/generic/algorithm.h> #include <util/generic/array_ref.h> #include <util/generic/cast.h> #include <util/generic/hash.h> #include <util/generic/hash_set.h> #include <util/generic/string.h> #include <util/generic/variant.h> #include <util/generic/ymath.h> #include <util/string/cast.h> #include <util/string/escape.h> #include <util/system/compiler.h> #include <util/system/yassert.h> #include <cmath> namespace NCB { static float ConvertToFloatTarget(const TString& stringLabel) { if (IsMissingValue(stringLabel)) { return std::nan(""); } else { float floatLabel; CB_ENSURE( TryFromString(stringLabel, floatLabel), "Target value \"" << EscapeC(stringLabel) << "\" cannot be parsed as float" ); return floatLabel; } } static TVector<float> ConvertRawToFloatTarget( const TRawTarget& rawTarget, NPar::ILocalExecutor* localExecutor ) { TVector<float> result; if (const ITypedSequencePtr<float>* floatSequence = std::get_if<ITypedSequencePtr<float>>(&rawTarget)) { result.yresize((*floatSequence)->GetSize()); TArrayRef<float> resultRef = result; size_t i = 0; (*floatSequence)->ForEach( [resultRef, &i] (float value) { resultRef[i++] = value; } ); } else { TConstArrayRef<TString> stringLabels = Get<TVector<TString>>(rawTarget); result.yresize(stringLabels.size()); TArrayRef<float> resultRef = result; localExecutor->ExecRangeBlockedWithThrow( [stringLabels, resultRef] (int i) { resultRef[i] = ConvertToFloatTarget(stringLabels[i]); }, 0, SafeIntegerCast<int>(stringLabels.size()), /*batchSizeOrZeroForAutoBatchSize*/ 0, NPar::TLocalExecutor::WAIT_COMPLETE ); } return result; } class TCastFloatTargetConverter : public ITargetConverter { public: TCastFloatTargetConverter() = default; TVector<float> Process( ERawTargetType targetType, const TRawTarget& rawTarget, NPar::ILocalExecutor* localExecutor ) override { Y_UNUSED(targetType); return ConvertRawToFloatTarget(rawTarget, localExecutor); } ui32 GetClassCount() const override { /* * this target converter is unapplicable for multiclassification but can be used for * binary classification (e.g. loss_function == "CrossEntropy") */ return 2; } }; class TTargetBinarizer : public ITargetConverter { public: TTargetBinarizer(float targetBorder) : TargetBorder(targetBorder) {} TVector<float> Process( ERawTargetType targetType, const TRawTarget& rawTarget, NPar::ILocalExecutor* localExecutor ) override { Y_UNUSED(targetType); TVector<float> floatTarget = ConvertRawToFloatTarget(rawTarget, localExecutor); PrepareTargetBinary(floatTarget, TargetBorder, &floatTarget); return floatTarget; } ui32 GetClassCount() const override { return 2; } private: float TargetBorder; }; class TNumericClassTargetConverter : public ITargetConverter { public: TNumericClassTargetConverter(ui32 classCount) : ClassCount(static_cast<float>(classCount)) {} TVector<float> Process( ERawTargetType targetType, const TRawTarget& rawTarget, NPar::ILocalExecutor* localExecutor ) override { Y_UNUSED(targetType); TVector<float> result = ConvertRawToFloatTarget(rawTarget, localExecutor); TArrayRef<float> resultRef = result; localExecutor->ExecRangeBlockedWithThrow( [resultRef, this] (int i) { CheckIsValidClassIdx(resultRef[i]); }, 0, SafeIntegerCast<int>(result.size()), /*batchSizeOrZeroForAutoBatchSize*/ 0, NPar::TLocalExecutor::WAIT_COMPLETE ); return result; } ui32 GetClassCount() const override { return (ui32)ClassCount; } private: inline void CheckIsValidClassIdx(float classIdx) const { float intPart; CB_ENSURE( std::modf(classIdx, &intPart) == 0.0f, "Value in target (" << classIdx << ") is not expected class index" ); CB_ENSURE( classIdx >= 0.0f, "Value in target (" << classIdx << ") is not expected class index" ); CB_ENSURE( classIdx < ClassCount, "Value in target (" << classIdx << ") is greater than specified class count" ); } private: // type is float to avoid casting because target is a vector of floats float ClassCount; }; class TUseClassLabelsTargetConverter : public ITargetConverter { public: TUseClassLabelsTargetConverter(const TVector<NJson::TJsonValue>& inputClassLabels) { Y_VERIFY(!inputClassLabels.empty()); float classIdx = 0; switch (inputClassLabels[0].GetType()) { case NJson::JSON_INTEGER: ClassLabelType = ERawTargetType::Integer; for (const NJson::TJsonValue& classLabel : inputClassLabels) { FloatLabelToClass.emplace(static_cast<float>(classLabel.GetInteger()), classIdx++); } break; case NJson::JSON_DOUBLE: ClassLabelType = ERawTargetType::Float; for (const NJson::TJsonValue& classLabel : inputClassLabels) { FloatLabelToClass.emplace(static_cast<float>(classLabel.GetDouble()), classIdx++); } break; case NJson::JSON_STRING: ClassLabelType = ERawTargetType::String; for (const NJson::TJsonValue& classLabel : inputClassLabels) { StringLabelToClass.emplace(classLabel.GetString(), classIdx++); } break; default: CB_ENSURE_INTERNAL(false, "bad class label type: " << inputClassLabels[0].GetType()); } } TVector<float> Process( ERawTargetType targetType, const TRawTarget& rawTarget, NPar::ILocalExecutor* localExecutor ) override { Y_UNUSED(targetType); TVector<float> result; if (const ITypedSequencePtr<float>* typedSequence = std::get_if<ITypedSequencePtr<float>>(&rawTarget)) { UpdateFloatLabelToClass(); result.yresize((*typedSequence)->GetSize()); TArrayRef<float> resultRef = result; size_t i = 0; (*typedSequence)->ForEach( [this, resultRef, &i] (float srcLabel) { const auto it = FloatLabelToClass.find(srcLabel); CB_ENSURE(it != FloatLabelToClass.end(), "Unknown class label: \"" << srcLabel << '"'); resultRef[i++] = it->second; } ); } else { UpdateStringLabelToClass(); TConstArrayRef<TString> stringLabels = Get<TVector<TString>>(rawTarget); result.yresize(stringLabels.size()); TArrayRef<float> resultRef = result; localExecutor->ExecRangeBlockedWithThrow( [this, resultRef, stringLabels] (int i) { const auto it = StringLabelToClass.find(stringLabels[i]); CB_ENSURE( it != StringLabelToClass.end(), "Unknown class label: \"" << EscapeC(stringLabels[i]) << '"' ); resultRef[i] = it->second; }, 0, SafeIntegerCast<int>(stringLabels.size()), /*batchSizeOrZeroForAutoBatchSize*/ 0, NPar::TLocalExecutor::WAIT_COMPLETE ); } return result; } ui32 GetClassCount() const override { return SafeIntegerCast<ui32>(StringLabelToClass.size()); } private: void UpdateFloatLabelToClass() { if (FloatLabelToClass.empty()) { for (const auto& [stringLabel, classIdx] : StringLabelToClass) { float floatLabel; CB_ENSURE( TryFromString<float>(stringLabel, floatLabel), "Not all class names are numeric, but specified target data is" ); FloatLabelToClass.emplace(floatLabel, classIdx); } } } void UpdateStringLabelToClass() { if (StringLabelToClass.empty()) { if (ClassLabelType == ERawTargetType::Integer) { for (const auto& [floatLabel, classIdx] : FloatLabelToClass) { StringLabelToClass.emplace(ToString(static_cast<i64>(floatLabel)), classIdx); } } else { Y_VERIFY(ClassLabelType == ERawTargetType::Float); for (const auto& [floatLabel, classIdx] : FloatLabelToClass) { StringLabelToClass.emplace(ToString(floatLabel), classIdx); } } } } private: ERawTargetType ClassLabelType; // which map is used depends on source target data type // dst type is float to avoid casting because target is a vector of floats THashMap<TString, float> StringLabelToClass; THashMap<float, float> FloatLabelToClass; }; class TMakeClassLabelsTargetConverter : public ITargetConverter { public: TMakeClassLabelsTargetConverter(bool isMultiClass) : IsMultiClass(isMultiClass) , TargetType(ERawTargetType::None) // just some default {} TVector<float> Process( ERawTargetType targetType, const TRawTarget& rawTarget, NPar::ILocalExecutor* localExecutor ) override { CB_ENSURE_INTERNAL(targetType != ERawTargetType::None, "targetType=None is unexpected"); TargetType = targetType; TVector<float> result; Visit( [&] (const auto& value) { result = ProcessMakeClassLabelsImpl(value, localExecutor); }, rawTarget ); return result; } ui32 GetClassCount() const override { ui32 classCount; switch (TargetType) { case ERawTargetType::Integer: case ERawTargetType::Float: classCount = SafeIntegerCast<ui32>(FloatLabelToClass.size()); break; case ERawTargetType::String: classCount = SafeIntegerCast<ui32>(StringLabelToClass.size()); break; default: Y_UNREACHABLE(); } Y_ASSERT(classCount > 1); return classCount; } TMaybe<TVector<NJson::TJsonValue>> GetClassLabels() override { TVector<NJson::TJsonValue> result; switch (TargetType) { case ERawTargetType::Integer: result.yresize(FloatLabelToClass.ysize()); for (const auto& [floatLabel, classIdx] : FloatLabelToClass) { result[static_cast<size_t>(classIdx)].SetValue(static_cast<i64>(floatLabel)); } break; case ERawTargetType::Float: result.yresize(FloatLabelToClass.ysize()); for (const auto& [floatLabel, classIdx] : FloatLabelToClass) { result[static_cast<size_t>(classIdx)].SetValue(floatLabel); } break; case ERawTargetType::String: result.yresize(StringLabelToClass.ysize()); for (const auto& [stringLabel, classIdx] : StringLabelToClass) { result[static_cast<size_t>(classIdx)].SetValue(stringLabel); } break; default: CB_ENSURE_INTERNAL( false, "ITargetConverter::GetClassLabels() is called before calling Process()" ); } return MakeMaybe<TVector<NJson::TJsonValue>>(std::move(result)); } private: void CheckUniqueLabelsSize(size_t size) const { CB_ENSURE(size > 1, "Target contains only one unique value"); CB_ENSURE( IsMultiClass || (size == 2), "Target with classes must contain only 2 unique values for binary classification" ); } TVector<float> ProcessMakeClassLabelsImpl(const ITypedSequencePtr<float>& labels, NPar::ILocalExecutor* localExecutor) { CB_ENSURE_INTERNAL( (TargetType == ERawTargetType::Float) || (TargetType == ERawTargetType::Integer), "TargetType is " << TargetType << ", but labels is ITypedSequencePtr<float>" ); TVector<float> targets = ToVector(*labels); THashSet<float> uniqueLabelsSet; for (float value : targets) { CB_ENSURE(!std::isnan(value), "NaN values are not supported for target"); uniqueLabelsSet.insert(value); } CheckUniqueLabelsSize(uniqueLabelsSet.size()); TVector<float> uniqueLabels(uniqueLabelsSet.begin(), uniqueLabelsSet.end()); Sort(uniqueLabels); CB_ENSURE(FloatLabelToClass.empty(), "ProcessMakeClassLabels: label-to-class map must be empty before label converting."); float classIdx = 0; if (TargetType == ERawTargetType::Integer) { for (auto label: uniqueLabels) { float integralPart; CB_ENSURE_INTERNAL( std::modf(label, &integralPart) == 0.0f, "TargetType is specified as Integer but labels contain non-integer data" ); FloatLabelToClass.emplace(label, classIdx++); } } else { for (auto label: uniqueLabels) { FloatLabelToClass.emplace(label, classIdx++); } } TArrayRef<float> targetsRef = targets; NPar::ParallelFor( *localExecutor, 0, SafeIntegerCast<ui32>(targets.size()), [targetsRef, this] (int i) { targetsRef[i] = FloatLabelToClass[targetsRef[i]]; } ); return targets; } TVector<float> ProcessMakeClassLabelsImpl(TConstArrayRef<TString> labels, NPar::ILocalExecutor* localExecutor) { CB_ENSURE_INTERNAL( TargetType == ERawTargetType::String, "TargetType is " << TargetType << ", but labels is TVector<TString>" ); THashSet<TString> uniqueLabelsSet(labels.begin(), labels.end()); CheckUniqueLabelsSize(uniqueLabelsSet.size()); TVector<TString> uniqueLabels(uniqueLabelsSet.begin(), uniqueLabelsSet.end()); // Kind of heuristic for proper ordering class names if they all are numeric if (AllOf(uniqueLabels, [](const TString& label) -> bool { float tmp; return TryFromString<float>(label, tmp); })) { Sort(uniqueLabels, [](const TString& label1, const TString& label2) { return FromString<float>(label1) < FromString<float>(label2); }); } else { Sort(uniqueLabels); } CB_ENSURE(StringLabelToClass.empty(), "ProcessMakeClassLabels: label-to-class map must be empty before label converting."); float classIdx = 0; for (const auto& label: uniqueLabels) { StringLabelToClass.emplace(label, classIdx++); } TVector<float> targets; targets.yresize(labels.size()); TArrayRef<float> targetsRef = targets; NPar::ParallelFor( *localExecutor, 0, SafeIntegerCast<ui32>(targets.size()), [targetsRef, labels, this] (int i) { targetsRef[i] = StringLabelToClass[labels[i]]; } ); return targets; } private: bool IsMultiClass; ERawTargetType TargetType; // which map is used depends on source target data type // dst type is float to avoid casting because target is a vector of floats THashMap<TString, float> StringLabelToClass; THashMap<float, float> FloatLabelToClass; }; THolder<ITargetConverter> MakeTargetConverter(bool isRealTarget, bool isClass, bool isMultiClass, TMaybe<float> targetBorder, TMaybe<ui32> classCount, const TVector<NJson::TJsonValue>& inputClassLabels) { CB_ENSURE_INTERNAL(!isMultiClass || isClass, "isMultiClass is true, but isClass is false"); if (isRealTarget) { CB_ENSURE(!isMultiClass, "Converted real target is incompatible with Multiclass"); CB_ENSURE(!targetBorder.Defined(), "Converted real target is incompatible with targetBorder"); CB_ENSURE( !classCount.Defined() || (*classCount == 2), "Converted real target is incompatible with class count not equal to 2" ); CB_ENSURE( inputClassLabels.empty(), "Converted real target is incompatible with specifying class names" ); return MakeHolder<TCastFloatTargetConverter>(); } else { CB_ENSURE_INTERNAL(isClass, "isRealTarget is false, but isClass is false"); } if (targetBorder.Defined()) { CB_ENSURE( isClass && !isMultiClass, "targetBorder should be specified only for binary classification problems" ); CB_ENSURE( !classCount.Defined() || (*classCount == 2), "Specifying target border is incompatible with class count not equal to 2" ); CB_ENSURE( inputClassLabels.empty(), "Specifying target border is incompatible with specifying class labels" ); return MakeHolder<TTargetBinarizer>(*targetBorder); } if (!inputClassLabels.empty()) { CB_ENSURE( isClass, "classLabels should be specified only for classification problems" ); CB_ENSURE( isMultiClass || (inputClassLabels.size() == 2), "binary classification problem, but class labels count is not equal to 2" ); CB_ENSURE( !classCount.Defined() || (size_t(*classCount) == inputClassLabels.size()), "both classCount and classLabels specified and length of classLabels is not equal to classCount" ); return MakeHolder<TUseClassLabelsTargetConverter>(inputClassLabels); } if (classCount.Defined()) { CB_ENSURE( isClass, "classCount should be specified only for classification problems" ); return MakeHolder<TNumericClassTargetConverter>(*classCount); } return MakeHolder<TMakeClassLabelsTargetConverter>(isMultiClass); } } // NCB
/*! * Copyright 2017 by Contributors * \file count_descendant.cc * \brief Count number of descendants for each AST node */ #include "./builder.h" namespace treelite { namespace compiler { DMLC_REGISTRY_FILE_TAG(count_descendant); static int count(ASTNode* node) { if (dynamic_cast<CodeFolderNode*>(node)) { node->num_descendant_ast_node = 0; return 0; // descendants of CodeFolderNode are exempt from // ASTBuilder::BreakUpLargeTranslationUnits } int accum = 0; for (ASTNode* child : node->children) { accum += count(child) + 1; } node->num_descendant_ast_node = accum; return accum; } void ASTBuilder::CountDescendant() { count(this->main_node); } } // namespace compiler } // namespace treelite
#include <myth\graphics\camera.h> using namespace myth::graphics; using namespace glm; Camera::Camera() { viewmatrix = mat4(1.0f); projection = mat4(1.0f); cameraPosition = vec3(0.0f); cameraDirection = vec3(0.0,0.0,1.0); cameraUp = vec3(0.0,1.0,0.0); pitch = 0; Update(); } Camera::~Camera() { } mat4 Camera::ProjectionMatrix() const { return projection; } mat4 Camera::ViewMatrix() const { return viewmatrix; } mat4 Camera::ViewProjectionMatrix() const { return projection * viewmatrix; } void Camera::Update() { viewmatrix = glm::lookAt(cameraPosition,cameraPosition + cameraDirection,cameraUp); viewprojection = viewmatrix * projection; } void Camera::Perspective(float fieldofview,float aspectratio,float znear,float zfar) { projection = glm::perspective(fieldofview,aspectratio,znear,zfar); viewprojection = viewmatrix * projection; } void Camera::Yaw(float deg) { cameraDirection = glm::rotate(cameraDirection,deg,cameraUp); Update(); } void Camera::Pitch(float deg) { if (abs(pitch+deg) > 60) return; pitch += deg; vec3 cross = glm::cross(cameraDirection,cameraUp); cameraDirection = glm::rotate(cameraDirection,deg,cross); Update(); } void Camera::Roll(float deg) { cameraUp = glm::rotate(cameraUp,deg,cameraDirection); Update(); } void Camera::MoveForward(float amount) { cameraPosition += cameraDirection * amount; Update(); } void Camera::MoveSideways(float amount) { cameraPosition += glm::normalize(glm::cross(cameraDirection,cameraUp)) * amount; Update(); } void Camera::MoveUp(float amount) { cameraPosition += cameraUp * amount; Update(); } void Camera::SetPosition(vec3 position) { cameraPosition = position; Update(); } void Camera::SetDirection(vec3 direction) { cameraDirection = direction; Update(); } void Camera::SetUp(vec3 up) { cameraUp = up; Update(); }
 #include "Connectors.h" #include <boost/algorithm/string.hpp> #include "Window.h" #include "GraphicView.h" #include "VertexRepresentation.h" namespace charliesoft { const qreal Pi = 3.1415926; bool lineIntersect(QLineF& line1, double x1, double y1, double x2, double y2) { QLineF line; line.setP1(QPointF(x1, y1)); line.setP2(QPointF(x2, y2)); QPointF intersection; return line.intersect(line1, &intersection) == QLineF::BoundedIntersection; } LinkPath::LinkPath(LinkConnexionRepresentation* src, LinkConnexionRepresentation* dst, QGraphicsItem *parent, QGraphicsScene *scene) : QGraphicsLineItem(parent){ _src = src; _dst = dst; _selected = false; setFlag(QGraphicsItem::ItemIsSelectable, true); setPen(QPen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); setLine(QLineF(_dst->getWorldAnchor(), _src->getWorldAnchor())); }; QPainterPath LinkPath::shape() const { QPainterPath path = QGraphicsLineItem::shape(); path.addPolygon(_arrowHead); return path; } bool LinkPath::intersect(const QRect& rect) const { QLineF line; QPoint p1 = _src->getWorldAnchor(); QPoint p2 = _dst->getWorldAnchor(); if (rect.contains(p1.x(), p1.y()) || rect.contains(p2.x(), p2.y())) return true; line.setP1(QPointF(p1.x(), p1.y())); line.setP2(QPointF(p2.x(), p2.y())); return lineIntersect(line, rect.x(), rect.y(), rect.x() + rect.width(), rect.y()) || lineIntersect(line, rect.x(), rect.y(), rect.x(), rect.y() + rect.height()) || lineIntersect(line, rect.x(), rect.y() + rect.height(), rect.x() + rect.width(), rect.y() + rect.height()); } void LinkPath::draw(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { QPen myPen = pen(); QColor myColor; if (_selected) myColor = QColor(255, 0, 0); else myColor = Qt::black; myPen.setColor(myColor); qreal arrowSize = 10; painter->setPen(myPen); painter->setBrush(myColor); QLineF centerLine(_src->pos(), _dst->pos()); setLine(QLineF(_dst->getWorldAnchor(), _src->getWorldAnchor())); double angle = ::acos(line().dx() / line().length()); if (line().dy() >= 0) angle = (Pi * 2) - angle; QPointF arrowP1 = line().p1() + QPointF(sin(angle + Pi / 2.5) * arrowSize, cos(angle + Pi / 2.5) * arrowSize); QPointF arrowP2 = line().p1() + QPointF(sin(angle + Pi - Pi / 2.5) * arrowSize, cos(angle + Pi - Pi / 2.5) * arrowSize); _arrowHead.clear(); _arrowHead << line().p1() << arrowP1 << arrowP2; painter->drawLine(line()); painter->drawPolygon(_arrowHead); if (_selected) { painter->setPen(QPen(myColor, 1, Qt::DashLine)); QLineF myLine = line(); myLine.translate(0, 4.0); painter->drawLine(myLine); myLine.translate(0, -8.0); painter->drawLine(myLine); } } ConditionLinkRepresentation::ConditionLinkRepresentation(ConditionOfRendering* model, bool isLeftCond, QWidget *father) : LinkConnexionRepresentation(_STR(isLeftCond ? "CONDITION_BLOCK_LEFT" : "CONDITION_BLOCK_RIGHT"), isLeftCond, father), _model(model){ setObjectName("ParamRepresentation"); setToolTip("<FONT>" + _QT("CONDITION_BLOCK_HELP") + "</FONT>"); connect(this, SIGNAL(askSynchro()), (VertexRepresentation*)father->parentWidget(), SLOT(reshape())); } ParamRepresentation::ParamRepresentation(ParamRepresentation* other) : ParamRepresentation(other->_model, other->_param, other->_isInput, other->_father) { _defaultValue = other->_defaultValue; _isSubParam = other->_isSubParam; } ParamRepresentation::ParamRepresentation(Block* model, ParamDefinition* param, bool isInput, QWidget *father) : LinkConnexionRepresentation(param->_name, isInput, father), _model(model), _param(param), _paramType(_param->_type){ _defaultValue = _isSubParam = false; setObjectName("ParamRepresentation"); if (!param->_show) this->hide(); setToolTip("<FONT>" + _QT(param->_helper) + "</FONT>"); if (_vertex != NULL) connect(this, SIGNAL(askSynchro()), _vertex, SLOT(reshape())); }; SubGraphParamRepresentation::SubGraphParamRepresentation(SubBlock* model, const ParamDefinition* def, bool isInput, QWidget *father) : LinkConnexionRepresentation(def->_name, isInput, father), _model(model), _param(*def){ setObjectName("SubGraphParamRepresentation"); setToolTip("<FONT>" + _QT(def->_helper) + "</FONT>"); setAlignment(Qt::AlignCenter); } std::string ParamRepresentation::getParamHelper() const { size_t pos = _STR(_param->_helper).find_first_of('|'); if (pos == std::string::npos) return _param->_helper; else return _STR(_param->_helper).substr(0, pos); } std::vector<std::string> ParamRepresentation::getParamListChoice() const { std::vector<std::string> out; size_t pos = _STR(_param->_helper).find_first_of('|'); if (pos == std::string::npos) return out; std::string params = _STR(_param->_helper).substr(pos+1); boost::split(out, params, boost::is_any_of("^")); return out; } void ParamRepresentation::setVisibility(ParamVisibility visible) { if (_param->_show == visible) return;//Nothing to do... getParamValue()->isNeeded(visible != notUsed); _param->_show = visible; emit askSynchro(); } void ParamRepresentation::setSubParam(bool param1) { _isSubParam = param1;///\todo something is wrong here... if (_isSubParam) setText(_param->_helper.c_str()); else setText(_param->_helper.c_str()); } void ParamRepresentation::redefineParam(std::string fullSubName, ParamType newType) { _isSubParam = true; _subName = fullSubName; _paramType = newType; } LinkConnexionRepresentation::LinkConnexionRepresentation(std::string text, bool isInput, QWidget *father) : QLabel(_QT(text), father), _isInput(isInput) { _father = father; QWidget* tmp = father->parentWidget(); if (father!=NULL) _vertex = dynamic_cast<VertexRepresentation*>(father->parentWidget()); else _vertex = NULL; _activeVertex = NULL; _name = text; }; QPoint LinkConnexionRepresentation::getWorldAnchor() { QPoint p = parentWidget()->mapTo(Window::getInstance()->getMainWidget(), mapTo(parentWidget(), pos()) / 2); if (_isInput) return QPoint(p.x(), (int)(p.y() + height() / 2.)); else return QPoint(p.x() + width(), (int)(p.y() + height() / 2.)); } void LinkConnexionRepresentation::setVisibility(bool visible) { if (_shouldShow == visible) return;//Nothing to do... _shouldShow = visible; emit askSynchro(); } void LinkConnexionRepresentation::changeStyleProperty(const char* propertyName, QVariant val) { setProperty(propertyName, val); style()->unpolish(this); style()->polish(this); update(); } void LinkConnexionRepresentation::mousePressEvent(QMouseEvent *e) { if (_vertex == NULL) return;//Nothing to do... _activeVertex = _vertex; _activeVertex->setParamActiv(this); setCursor(Qt::CrossCursor); //get the position of widget inside main widget and send signal of a new link creation: emit creationLink(getWorldAnchor()); e->ignore(); } void LinkConnexionRepresentation::mouseReleaseEvent(QMouseEvent *e) { if (_activeVertex != NULL) _activeVertex->setParamActiv(NULL); _activeVertex = NULL; setCursor(Qt::ArrowCursor); emit releaseLink(Window::getInstance()->getMainWidget()->mapFromGlobal(e->globalPos())); }; void LinkConnexionRepresentation::mouseMoveEvent(QMouseEvent *me) { me->ignore(); }; void LinkConnexionRepresentation::enterEvent(QEvent *) { setCursor(Qt::CrossCursor); } }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include "allocators.h" #include <QKeyEvent> #include <QMessageBox> #include <QPushButton> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(model), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint()); ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint()); ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint()); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); this->model = model; switch (mode) { case Encrypt: // Ask passphrase x2 ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.")); ui->passLabel1->hide(); ui->passEdit1->hide(); setWindowTitle(tr("Encrypt wallet")); break; case UnlockAnonymize: ui->anonymizationCheckBox->setChecked(true); ui->anonymizationCheckBox->show(); case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } ui->anonymizationCheckBox->setChecked(model->isAnonymizeOnlyUnlocked()); textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if (!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch (mode) { case Encrypt: { if (newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR PIV</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval == QMessageBox::Yes) { if (newpass1 == newpass2) { if (model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("PIVX will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your PIVs from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case UnlockAnonymize: case Unlock: if (!model->setWalletLocked(false, oldpass, ui->anonymizationCheckBox->isChecked())) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if (!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if (newpass1 == newpass2) { if (model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch (mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case UnlockAnonymize: // Old passphrase x1 case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent* event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent* ke = static_cast<QKeyEvent*>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject* object, QEvent* event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent* ke = static_cast<QKeyEvent*>(event); QString str = ke->text(); if (str.length() != 0) { const QChar* psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); }
// Copyright 2018 The Fuchsia 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 "layer.h" #include <math.h> #include "runner.h" #include "utils.h" namespace { uint32_t scale(uint32_t x, uint32_t from_limit, uint32_t to_limit) { if (from_limit == to_limit) { return x; } else { return (x * to_limit + (from_limit - 1)) / from_limit; } } } // namespace namespace display_test { namespace internal { LayerImpl::LayerImpl(Runner* runner) : runner_(runner) { runner->display()->CreateLayer([this](zx_status_t status, uint64_t id) { ZX_ASSERT(status == ZX_OK); id_ = id; runner_->OnResourceReady(); }); } fuchsia::hardware::display::ControllerPtr& LayerImpl::controller() const { return runner_->display(); } } // namespace internal PrimaryLayer::PrimaryLayer(internal::Runner* runner, uint32_t width, uint32_t height) : Layer(runner) { config_ = {}; config_.width = width; config_.height = height; config_.pixel_format = internal::ImageImpl::kFormat; pending_state_.set_position = false; pending_state_.transform = fuchsia::hardware::display::Transform::IDENTITY; pending_state_.src = {}; pending_state_.src.width = width; pending_state_.src.height = height; pending_state_.dest = pending_state_.src; pending_state_.set_alpha = false; pending_state_.alpha_mode = fuchsia::hardware::display::AlphaMode::DISABLE; pending_state_.image = nullptr; pending_state_.flip_image = false; } void PrimaryLayer::SetImage(const Image* image) { pending_state_.image = internal::ImageImpl::GetImageImpl(image); pending_state_.flip_image = true; } void PrimaryLayer::SetPosition(fuchsia::hardware::display::Transform transform, fuchsia::hardware::display::Frame src, fuchsia::hardware::display::Frame dest) { src.x_pos = src.x_pos & ~1; dest.x_pos = dest.x_pos & ~1; src.width = src.width & ~1; dest.width = dest.width & ~1; ZX_ASSERT(src.width == dest.width || dest.width >= kMinScalableImageSize); ZX_ASSERT(src.height == dest.height || dest.height >= kMinScalableImageSize); pending_state_.transform = transform; pending_state_.src = src; pending_state_.dest = dest; pending_state_.set_position = true; } void PrimaryLayer::SetAlpha(fuchsia::hardware::display::AlphaMode mode, float val) { pending_state_.alpha_mode = mode; pending_state_.alpha_val = val; pending_state_.set_alpha = true; } bool PrimaryLayer::GetPixel(const void* state, uint32_t x, uint32_t y, uint32_t* value_out, bool* skip_out) const { auto s = static_cast<const struct state*>(state); // Transform the global x,y coordinate to a dest-frame coordinate x -= s->dest.x_pos; y -= s->dest.y_pos; if (x >= s->dest.width || y >= s->dest.height) { return false; } uint32_t dest_width = s->dest.width; uint32_t dest_height = s->dest.height; // Undo x reflection if necessary if (s->transform == fuchsia::hardware::display::Transform::REFLECT_X || s->transform == fuchsia::hardware::display::Transform::ROT_180 || s->transform == fuchsia::hardware::display::Transform::ROT_270 || s->transform == fuchsia::hardware::display::Transform::ROT_90_REFLECT_X) { x = (dest_width - 1) - x; } // Undo y reflection if necessary if (s->transform == fuchsia::hardware::display::Transform::REFLECT_Y || s->transform == fuchsia::hardware::display::Transform::ROT_180 || s->transform == fuchsia::hardware::display::Transform::ROT_270 || s->transform == fuchsia::hardware::display::Transform::ROT_90_REFLECT_Y) { y = (dest_height - 1) - y; } // Undo 90-degree counterclockwise rotation if necessary if (s->transform == fuchsia::hardware::display::Transform::ROT_90 || s->transform == fuchsia::hardware::display::Transform::ROT_90_REFLECT_X || s->transform == fuchsia::hardware::display::Transform::ROT_90_REFLECT_Y || s->transform == fuchsia::hardware::display::Transform::ROT_270) { dest_width = s->dest.height; dest_height = s->dest.width; uint32_t tmp = x; x = (dest_width - 1) - y; y = tmp; } // Scale from dest-coords back to src-coords x = scale(x, dest_width, s->src.width); y = scale(y, dest_height, s->src.height); // If we're scaling, skip over pixels that depend on hardware interpolation if (dest_width != s->src.width || dest_height != s->src.height) { constexpr uint32_t bounds = kMinScalableImageSize / 4; if ((x < bounds || dest_width - bounds <= x) && (y < bounds || dest_height - bounds <= y)) { *skip_out = false; } else { *skip_out = true; } } else { *skip_out = false; } // Now we can actually get the image pixel data uint32_t val = s->image->get_pixel(s->src.x_pos + x, s->src.y_pos + y); // If there's plane alpha, add combine it with the image pixel if (!isnan(s->alpha_val)) { uint8_t plane_alpha = static_cast<uint8_t>(round(s->alpha_val * 255)); uint32_t pixel_alpha = val >> 24; pixel_alpha = ((pixel_alpha * plane_alpha) + 254) >> 8; val = (val & ~(0xff000000)) | (pixel_alpha << 24); // If the mode is premultiplied, the hardware is supposed to // premultiply the alpha value before blending. if (s->alpha_mode == fuchsia::hardware::display::AlphaMode::PREMULTIPLIED) { val = internal::premultiply_color_channels(val, plane_alpha); } } if (s->alpha_mode == fuchsia::hardware::display::AlphaMode::DISABLE) { // Clobber the alpha value if it's disabled val |= 0xff000000; } else if (s->alpha_mode == fuchsia::hardware::display::AlphaMode::HW_MULTIPLY) { // If blending is hwmultiply, then do the the channel multiplication // here so the caller of GetPixel can treat everything is premultiplied. val = internal::premultiply_color_channels(val, val >> 24); } *value_out = val; return true; } const void* PrimaryLayer::ApplyState() { auto state = new struct state; *state = pending_state_; pending_state_.set_config = false; pending_state_.set_position = false; pending_state_.set_alpha = false; pending_state_.flip_image = false; if (state->src.height != state->dest.height || state->src.width != state->dest.width) { ZX_ASSERT(state->image->is_scalable()); } return state; } void PrimaryLayer::SendState(const void* state) const { auto s = static_cast<const struct state*>(state); if (s->set_config) { controller()->SetLayerPrimaryConfig(id(), config_); } if (s->set_position) { controller()->SetLayerPrimaryPosition(id(), s->transform, s->src, s->dest); } if (s->set_alpha) { controller()->SetLayerPrimaryAlpha(id(), s->alpha_mode, s->alpha_val); } if (s->flip_image) { controller()->SetLayerImage(id(), s->image->id(), 0, 0); } } void PrimaryLayer::DeleteState(const void* state) const { delete static_cast<const struct state*>(state); } uint64_t PrimaryLayer::image_id(const void* state) const { auto image = static_cast<const struct state*>(state)->image; return image ? image->id() : 0; } } // namespace display_test
/* different algorithms; multiple sources and targets Danil Kirsanov, 01/2008 */ #include <iostream> #include <fstream> #include <string> #include "geodesic_algorithm_dijkstra.h" #include "geodesic_algorithm_subdivision.h" #include "geodesic_algorithm_exact.h" int main(int argc, char **argv) { std::vector<double> points; std::vector<unsigned> faces; std::string filename = "./src/hedgehog_mesh.txt"; geodesic::read_mesh_from_file(filename.c_str(),points,faces); geodesic::Mesh mesh; mesh.initialize_mesh_data(points, faces); //create internal mesh data structure including edges geodesic::GeodesicAlgorithmExact exact_algorithm(&mesh); //exact algorithm geodesic::GeodesicAlgorithmDijkstra dijkstra_algorithm(&mesh); //simplest approximate algorithm: path only allowed on the edges of the mesh unsigned const subdivision_level = 3; //three additional vertices per every edge in subdivision algorithm geodesic::GeodesicAlgorithmSubdivision subdivision_algorithm(&mesh,2); //with subdivision_level=0 this algorithm becomes Dijkstra, with subdivision_level->infinity it becomes exact std::vector<geodesic::GeodesicAlgorithmBase* > all_algorithms; //for simplicity, store all possible geodesic algorithms here all_algorithms.push_back(&dijkstra_algorithm); all_algorithms.push_back(&subdivision_algorithm); all_algorithms.push_back(&exact_algorithm); std::vector<geodesic::SurfacePoint> sources; sources.push_back(geodesic::SurfacePoint(&mesh.vertices()[0])); //one source is located at vertex zero sources.push_back(geodesic::SurfacePoint(&mesh.edges()[12])); //second source is located in the middle of edge 12 sources.push_back(geodesic::SurfacePoint(&mesh.faces()[20])); //third source is located in the middle of face 20 std::vector<geodesic::SurfacePoint> targets; //same thing with targets targets.push_back(geodesic::SurfacePoint(&mesh.vertices().back())); targets.push_back(geodesic::SurfacePoint(&mesh.edges()[10])); targets.push_back(geodesic::SurfacePoint(&mesh.faces()[3])); for(unsigned index=0; index<all_algorithms.size(); ++index) { geodesic::GeodesicAlgorithmBase* algorithm = all_algorithms[index]; //all algorithms are derived from GeodesicAlgorithmBase std::cout << std::endl << "results for algorithm " << algorithm->name() << std::endl; algorithm->propagate(sources); //cover the whole mesh algorithm->print_statistics(); //------------------first task: compute the pathes to the targets---- std::vector<geodesic::SurfacePoint> path; for(int i=0; i<targets.size(); ++i) { algorithm->trace_back(targets[i], path); print_info_about_path(path); } //------------------second task: for each source, find the furthest vertex that it covers ---- std::vector<double> max_distance(sources.size(), 0.0); //distance to the furthest vertex that is covered by the given source for(int i=0; i<mesh.vertices().size(); ++i) { geodesic::SurfacePoint p(&mesh.vertices()[i]); double distance; unsigned best_source = algorithm->best_source(p,distance); max_distance[best_source] = std::max(max_distance[best_source], distance); } std::cout << std::endl; for(int i=0; i<max_distance.size(); ++i) { std::cout << "distance to the furthest vertex that is covered by source " << i << " is " << max_distance[i] << std::endl; } } return 0; }
#include "Box2D.h" #include "Shape.h" //@line:26 JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_Shape_jniGetRadius(JNIEnv* env, jobject object, jlong addr) { //@line:48 b2Shape* shape = (b2Shape*)addr; return shape->m_radius; } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_Shape_jniSetRadius(JNIEnv* env, jobject object, jlong addr, jfloat radius) { //@line:58 b2Shape* shape = (b2Shape*)addr; shape->m_radius = radius; } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_Shape_jniDispose(JNIEnv* env, jobject object, jlong addr) { //@line:68 b2Shape* shape = (b2Shape*)addr; delete shape; } JNIEXPORT jint JNICALL Java_com_badlogic_gdx_physics_box2d_Shape_jniGetType(JNIEnv* env, jclass clazz, jlong addr) { //@line:73 b2Shape* shape = (b2Shape*)addr; switch(shape->m_type) { case b2Shape::e_circle: return 0; case b2Shape::e_edge: return 1; case b2Shape::e_polygon: return 2; case b2Shape::e_chain: return 3; default: return -1; } } JNIEXPORT jint JNICALL Java_com_badlogic_gdx_physics_box2d_Shape_jniGetChildCount(JNIEnv* env, jobject object, jlong addr) { //@line:89 b2Shape* shape = (b2Shape*)addr; return shape->GetChildCount(); }
#include "gmock/gmock.h" #include "infra/util/SharedPtr.hpp" #include "infra/util/SharedObjectAllocatorFixedSize.hpp" #include "infra/util/test_helper/MockCallback.hpp" #include "infra/util/test_helper/MonitoredConstructionObject.hpp" using AllocatorMySharedObject = infra::SharedObjectAllocator<infra::MonitoredConstructionObject, void(infra::ConstructionMonitorMock&)>; class SharedObjectAllocatorFixedSizeTest : public testing::Test { public: testing::StrictMock<infra::ConstructionMonitorMock> objectConstructionMock; }; TEST_F(SharedObjectAllocatorFixedSizeTest, allocate_one_object) { AllocatorMySharedObject::UsingAllocator<infra::SharedObjectAllocatorFixedSize>::WithStorage<2> allocator; void* savedObject; EXPECT_CALL(objectConstructionMock, Construct(testing::_)).WillOnce(testing::SaveArg<0>(&savedObject)); infra::SharedPtr<infra::MonitoredConstructionObject> object = allocator.Allocate(objectConstructionMock); EXPECT_TRUE(static_cast<bool>(object)); EXPECT_CALL(objectConstructionMock, Destruct(savedObject)); } TEST_F(SharedObjectAllocatorFixedSizeTest, when_allocation_fails_empty_SharedPtr_is_returned) { infra::SharedObjectAllocatorFixedSize<infra::MonitoredConstructionObject, void(infra::ConstructionMonitorMock&)>::WithStorage<0> allocator; infra::SharedPtr<infra::MonitoredConstructionObject> object = allocator.Allocate(objectConstructionMock); EXPECT_FALSE(static_cast<bool>(object)); } TEST_F(SharedObjectAllocatorFixedSizeTest, object_is_destructed_but_not_deallocated_while_WeakPtr_has_a_reference) { infra::SharedObjectAllocatorFixedSize<infra::MonitoredConstructionObject, void(infra::ConstructionMonitorMock&)>::WithStorage<1> allocator; infra::WeakPtr<infra::MonitoredConstructionObject> weakObject; { EXPECT_CALL(objectConstructionMock, Construct(testing::_)); infra::SharedPtr<infra::MonitoredConstructionObject> object = allocator.Allocate(objectConstructionMock); weakObject = object; EXPECT_CALL(objectConstructionMock, Destruct(testing::_)); } testing::Mock::VerifyAndClearExpectations(&objectConstructionMock); EXPECT_EQ(nullptr, allocator.Allocate(objectConstructionMock)); } TEST_F(SharedObjectAllocatorFixedSizeTest, invoke_on_allocatable_when_WeakPtrs_expire) { infra::SharedObjectAllocatorFixedSize<infra::MonitoredConstructionObject, void(infra::ConstructionMonitorMock&)>::WithStorage<1> allocator; testing::StrictMock<infra::MockCallback<void()>> callback; allocator.OnAllocatable([&]() { callback.callback(); }); { infra::WeakPtr<infra::MonitoredConstructionObject> weakObject; { EXPECT_CALL(objectConstructionMock, Construct(testing::_)); infra::SharedPtr<infra::MonitoredConstructionObject> object = allocator.Allocate(objectConstructionMock); weakObject = object; EXPECT_CALL(objectConstructionMock, Destruct(testing::_)); } EXPECT_CALL(callback, callback()); } testing::Mock::VerifyAndClearExpectations(&callback); }
#include "tcpdataprovider.h" void TcpDataProvider::sendMessage(QTcpSocket &socket, const Message &message) { QByteArray data; QDataStream ds(&data, QIODevice::ReadWrite); ds.setVersion(QDataStream::Qt_5_11); ds << static_cast<int>(eMessage) << message; socket.write(data); } void TcpDataProvider::sendUserStatus(QTcpSocket &socket, const UserStatus &userStatus) { QByteArray data; QDataStream ds(&data, QIODevice::ReadWrite); ds.setVersion(QDataStream::Qt_5_11); ds << static_cast<int>(eUserStatus) << userStatus; socket.write(data); } void TcpDataProvider::sendLoginPackage(QTcpSocket &socket, const UserStatus &loginData) { QByteArray data; QDataStream ds(&data, QIODevice::ReadWrite); ds.setVersion(QDataStream::Qt_5_11); ds << static_cast<int>(-1) << loginData; socket.write(data); } void TcpDataProvider::getData(QTcpSocket &socket) { int m_CurrentMessage = eMessage; QByteArray data = socket.readAll(); qDebug() << "TcpDataProvider::getData size " << data.size(); QDataStream ds(&data, QIODevice::ReadWrite); ds.setVersion(QDataStream::Qt_5_11); while(!ds.atEnd()) { ds >> m_CurrentMessage; switch(m_CurrentMessage) { case eMessage: { Message incommingMess; ds >> incommingMess; emit newMessageDetected(incommingMess); } break; case eUserStatus: { UserStatus userStat; ds >> userStat; emit newUserStatusDetected(userStat); } break; /*case eMessageHistoryResponse: { size_t userId; ds >> userId; QVector<QString> historyData; ds >> historyData; m_cachedHistory.fillChatHistoty(userId, historyData); emit chatHistoryUpdated(userId); }*/ case eCurrentUserResponse: { UserStatus userStat; ds >> userStat; emit currentUserDetected(userStat); } break; case eMessageHistoryRequest: default: break; }; } }
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Ltucoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "guiutil.h" #include "networkstyle.h" #include "clientversion.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0) { // transparent background setAttribute(Qt::WA_TranslucentBackground); setStyleSheet("background:transparent;"); // no window decorations setWindowFlags(Qt::FramelessWindowHint); // set reference point, paddings int paddingLeft = 14; int paddingTop = 470; int titleVersionVSpace = 17; int titleCopyrightVSpace = 32; float fontFactor = 1.0; // define text to place QString titleText = tr("Ltucoin Core"); QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion())); QString copyrightTextBtc = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString copyrightTextLtucoin = QChar(0xA9)+QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Ltucoin Core developers")); QString titleAddText = networkStyle->getTitleAddText(); // networkstyle.cpp can't (yet) read themes, so we do it here to get the correct Splash-screen QString splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash"; if(GetBoolArg("-regtest", false)) splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash_testnet"; if(GetBoolArg("-testnet", false)) splashScreenPath = ":/images/" + GUIUtil::getThemeName() + "/splash_testnet"; QString font = QApplication::font().toString(); // load the bitmap for writing some text over it pixmap = QPixmap(splashScreenPath); QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // check font size and drawing with pixPaint.setFont(QFont(font, 28*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 28*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(paddingLeft,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); pixPaint.drawText(paddingLeft,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(paddingLeft,paddingTop+titleCopyrightVSpace,copyrightTextBtc); pixPaint.drawText(paddingLeft,paddingTop+titleCopyrightVSpace+12,copyrightTextLtucoin); // draw additional text if special network if(!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width()-titleAddTextWidth-10,pixmap.height()-25,titleAddText); } pixPaint.end(); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), pixmap.size()); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { Q_UNUSED(mainWin); /* If the window is minimized, hide() will be ignored. */ /* Make sure we de-minimize the splashscreen window before hiding */ if (isMinimized()) showNormal(); hide(); deleteLater(); // No more need for this } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if(pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent *event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); }
/* * Copyright (c) 2017-2020 [Ribose Inc](https://www.ribose.com). * 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. * * 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 <fstream> #include <vector> #include <string> #include <rnp/rnp.h> #include "rnp_tests.h" #include "support.h" #include "librepgp/stream-common.h" #include "librepgp/stream-packet.h" #include "utils.h" #include <json.h> #include <vector> #include <string> // structure for filling input typedef struct { uint32_t remaining; uint8_t dummy; } dummy_reader_ctx_st; // reader of sequence of dummy bytes static bool dummy_reader(void *app_ctx, void *buf, size_t len, size_t *read) { size_t filled = 0; dummy_reader_ctx_st *ctx = NULL; ctx = (dummy_reader_ctx_st *) app_ctx; filled = (len > ctx->remaining) ? ctx->remaining : len; if (filled > 0) { memset(buf, ctx->dummy, filled); ctx->remaining -= filled; } *read = filled; return true; } static void test_partial_length_init(rnp_ffi_t *ffi, uint32_t key_flags) { rnp_input_t input = NULL; // init ffi assert_rnp_success(rnp_ffi_create(ffi, "GPG", "GPG")); assert_rnp_success( rnp_ffi_set_pass_provider(*ffi, ffi_string_password_provider, (void *) "password")); if (key_flags & RNP_LOAD_SAVE_SECRET_KEYS) { assert_rnp_success(rnp_input_from_path(&input, "data/keyrings/1/secring.gpg")); assert_rnp_success(rnp_load_keys(*ffi, "GPG", input, key_flags)); assert_rnp_success(rnp_input_destroy(input)); } if (key_flags & RNP_LOAD_SAVE_PUBLIC_KEYS) { assert_rnp_success(rnp_input_from_path(&input, "data/keyrings/1/pubring.gpg")); assert_rnp_success(rnp_load_keys(*ffi, "GPG", input, key_flags)); assert_rnp_success(rnp_input_destroy(input)); } } TEST_F(rnp_tests, test_partial_length_public_key) { rnp_input_t input = NULL; rnp_ffi_t ffi = NULL; assert_rnp_success(rnp_ffi_create(&ffi, "GPG", "GPG")); assert_rnp_success( rnp_input_from_path(&input, "data/test_partial_length/pubring.gpg.partial")); assert_int_equal(rnp_load_keys(ffi, "GPG", input, RNP_LOAD_SAVE_PUBLIC_KEYS), RNP_ERROR_BAD_FORMAT); assert_rnp_success(rnp_input_destroy(input)); assert_rnp_success(rnp_ffi_destroy(ffi)); } TEST_F(rnp_tests, test_partial_length_signature) { rnp_ffi_t ffi = NULL; rnp_input_t input = NULL; rnp_output_t output = NULL; // init ffi test_partial_length_init(&ffi, RNP_LOAD_SAVE_PUBLIC_KEYS); // message having partial length signature packet assert_rnp_success( rnp_input_from_path(&input, "data/test_partial_length/message.txt.partial-signed")); assert_rnp_success(rnp_output_to_null(&output)); rnp_op_verify_t verify = NULL; assert_rnp_success(rnp_op_verify_create(&verify, ffi, input, output)); assert_rnp_failure(rnp_op_verify_execute(verify)); // cleanup assert_rnp_success(rnp_op_verify_destroy(verify)); assert_rnp_success(rnp_input_destroy(input)); assert_rnp_success(rnp_output_destroy(output)); assert_rnp_success(rnp_ffi_destroy(ffi)); } TEST_F(rnp_tests, test_partial_length_first_packet_256) { rnp_ffi_t ffi = NULL; rnp_input_t input = NULL; rnp_output_t output = NULL; // init ffi test_partial_length_init(&ffi, RNP_LOAD_SAVE_PUBLIC_KEYS); // message having first partial length packet of 256 bytes assert_rnp_success( rnp_input_from_path(&input, "data/test_partial_length/message.txt.partial-256")); assert_rnp_success(rnp_output_to_null(&output)); rnp_op_verify_t verify = NULL; assert_rnp_success(rnp_op_verify_create(&verify, ffi, input, output)); assert_rnp_success(rnp_op_verify_execute(verify)); // cleanup assert_rnp_success(rnp_op_verify_destroy(verify)); assert_rnp_success(rnp_input_destroy(input)); assert_rnp_success(rnp_output_destroy(output)); assert_rnp_success(rnp_ffi_destroy(ffi)); } TEST_F(rnp_tests, test_partial_length_zero_last_chunk) { rnp_ffi_t ffi = NULL; rnp_input_t input = NULL; rnp_output_t output = NULL; // init ffi test_partial_length_init(&ffi, RNP_LOAD_SAVE_PUBLIC_KEYS); // message in partial packets having 0-size last chunk assert_rnp_success( rnp_input_from_path(&input, "data/test_partial_length/message.txt.partial-zero-last")); assert_rnp_success(rnp_output_to_null(&output)); rnp_op_verify_t verify = NULL; assert_rnp_success(rnp_op_verify_create(&verify, ffi, input, output)); assert_rnp_success(rnp_op_verify_execute(verify)); // cleanup assert_rnp_success(rnp_op_verify_destroy(verify)); assert_rnp_success(rnp_input_destroy(input)); assert_rnp_success(rnp_output_destroy(output)); assert_rnp_success(rnp_ffi_destroy(ffi)); } TEST_F(rnp_tests, test_partial_length_largest) { rnp_ffi_t ffi = NULL; rnp_input_t input = NULL; rnp_output_t output = NULL; // init ffi test_partial_length_init(&ffi, RNP_LOAD_SAVE_PUBLIC_KEYS); // message having largest possible partial packet assert_rnp_success( rnp_input_from_path(&input, "data/test_partial_length/message.txt.partial-1g")); assert_rnp_success(rnp_output_to_null(&output)); rnp_op_verify_t verify = NULL; assert_rnp_success(rnp_op_verify_create(&verify, ffi, input, output)); assert_rnp_success(rnp_op_verify_execute(verify)); // cleanup assert_rnp_success(rnp_op_verify_destroy(verify)); assert_rnp_success(rnp_input_destroy(input)); assert_rnp_success(rnp_output_destroy(output)); assert_rnp_success(rnp_ffi_destroy(ffi)); } TEST_F(rnp_tests, test_partial_length_first_packet_length) { rnp_ffi_t ffi = NULL; rnp_input_t input = NULL; rnp_output_t output = NULL; rnp_op_sign_t sign = NULL; rnp_key_handle_t key = NULL; // uncacheable size will emulate unknown length from callback source size_t uncacheable_size = PGP_INPUT_CACHE_SIZE + 1; // init ffi test_partial_length_init(&ffi, RNP_LOAD_SAVE_SECRET_KEYS); // generate a sequence of octets with appropriate length using callback dummy_reader_ctx_st reader_ctx; reader_ctx.dummy = 'X'; reader_ctx.remaining = uncacheable_size; assert_rnp_success(rnp_input_from_callback(&input, dummy_reader, NULL, &reader_ctx)); assert_rnp_success(rnp_output_to_memory(&output, uncacheable_size + 1024)); assert_rnp_success(rnp_op_sign_create(&sign, ffi, input, output)); assert_rnp_success(rnp_locate_key(ffi, "keyid", "7BC6709B15C23A4A", &key)); assert_rnp_success(rnp_op_sign_add_signature(sign, key, NULL)); assert_rnp_success(rnp_key_handle_destroy(key)); key = NULL; // signing assert_rnp_success(rnp_op_sign_execute(sign)); // read from the saved packets pgp_source_t src; uint8_t * mem = NULL; size_t len = 0; assert_rnp_success(rnp_output_memory_get_buf(output, &mem, &len, false)); assert_rnp_success(init_mem_src(&src, mem, len, false)); // skip first packet (one-pass signature) pgp_packet_body_t body; assert_rnp_success(stream_read_packet_body(&src, &body)); assert_int_equal(body.tag, PGP_PKT_ONE_PASS_SIG); free_packet_body(&body); // checking next packet header (should be partial length literal data) uint8_t flags = 0; assert_true(src_read_eq(&src, &flags, 1)); assert_int_equal(flags, PGP_PTAG_ALWAYS_SET | PGP_PTAG_NEW_FORMAT | PGP_PKT_LITDATA); // checking length bool last = true; // should be reset by stream_read_partial_chunk_len() assert_true(stream_read_partial_chunk_len(&src, &len, &last)); assert_true(len >= PGP_PARTIAL_PKT_FIRST_PART_MIN_SIZE); assert_false(last); // cleanup src_close(&src); assert_rnp_success(rnp_op_sign_destroy(sign)); assert_rnp_success(rnp_input_destroy(input)); assert_rnp_success(rnp_output_destroy(output)); assert_rnp_success(rnp_ffi_destroy(ffi)); }
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ #ifndef _MANIFEST_IMPORT_HXX #define _MANIFEST_IMPORT_HXX #include <cppuhelper/implbase1.hxx> // helper for implementations #ifndef _COM_SUN_STAR_XML_SAX_XDUCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #include "PackageConstants.hxx" #include <vector> #include <com/sun/star/beans/PropertyValues.hpp> #include <HashMaps.hxx> namespace com { namespace sun { namespace star { namespace xml { namespace sax { class XAttributeList; } } namespace beans { struct PropertyValue; } } } } typedef ::std::hash_map< ::rtl::OUString, ::rtl::OUString, ::rtl::OUStringHash, eqFunc > StringHashMap; struct ManifestScopeEntry { ::rtl::OUString m_aConvertedName; StringHashMap m_aNamespaces; ManifestScopeEntry( const ::rtl::OUString& aConvertedName, const StringHashMap& aNamespaces ) : m_aConvertedName( aConvertedName ) , m_aNamespaces( aNamespaces ) {} ~ManifestScopeEntry() {} }; typedef ::std::vector< ManifestScopeEntry > ManifestStack; class ManifestImport : public cppu::WeakImplHelper1 < com::sun::star::xml::sax::XDocumentHandler > { protected: ::com::sun::star::uno::Any maValues[ PKG_SIZE_ENCR_MNFST ]; ::std::vector < ::com::sun::star::beans::PropertyValues > & rManVector; ManifestStack aStack; sal_Int32 nDerivedKeySize; bool bIgnoreEncryptData; const ::rtl::OUString sCdataAttribute; const ::rtl::OUString sMediaTypeAttribute; const ::rtl::OUString sVersionAttribute; const ::rtl::OUString sFullPathAttribute; const ::rtl::OUString sSizeAttribute; const ::rtl::OUString sSaltAttribute; const ::rtl::OUString sInitialisationVectorAttribute; const ::rtl::OUString sIterationCountAttribute; const ::rtl::OUString sKeySizeAttribute; const ::rtl::OUString sAlgorithmNameAttribute; const ::rtl::OUString sStartKeyAlgNameAttribute; const ::rtl::OUString sKeyDerivationNameAttribute; const ::rtl::OUString sChecksumAttribute; const ::rtl::OUString sChecksumTypeAttribute; ::rtl::OUString PushNameAndNamespaces( const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttribs, StringHashMap& o_aConvertedAttribs ); ::rtl::OUString ConvertNameWithNamespace( const ::rtl::OUString& aName, const StringHashMap& aNamespaces ); ::rtl::OUString ConvertName( const ::rtl::OUString& aName ); public: ManifestImport( std::vector < ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > > & rNewVector ); ~ManifestImport( void ); virtual void SAL_CALL startDocument( ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endDocument( ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL startElement( const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttribs ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endElement( const ::rtl::OUString& aName ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL characters( const ::rtl::OUString& aChars ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& xLocator ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); }; #endif
/* Copyright 2017 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/grappler/costs/virtual_placer.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/grappler/clusters/cluster.h" #include "tensorflow/core/grappler/devices.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { namespace grappler { VirtualPlacer::VirtualPlacer(const Cluster* cluster) : has_gpu_(false) { CHECK(cluster); devices_ = cluster->GetDevices(); for (const auto& device : devices_) { if (str_util::Lowercase(device.first).find("gpu") != string::npos) { has_gpu_ = true; } } unknown_device_.set_type("UNKNOWN"); } const DeviceProperties& VirtualPlacer::get_device(const NodeDef& node) const { string device; if (!node.device().empty()) { auto it = devices_.find(node.device()); if (it != devices_.end()) { return it->second; } DeviceNameUtils::ParsedName parsed_name; bool parsed = DeviceNameUtils::ParseFullName(node.device(), &parsed_name); if (!parsed) { parsed = DeviceNameUtils::ParseLocalName(node.device(), &parsed_name); parsed_name.job = "localhost"; } if (!parsed) { if (node.device() == "GPU" || node.device() == "CPU" || node.device() == "gpu" || node.device() == "cpu") { parsed_name.job = "localhost"; parsed_name.type = node.device(); parsed = true; } } if (!parsed) { return unknown_device_; } else { device = strings::StrCat( "/job:", parsed_name.job, "/replica:", parsed_name.replica, "/task:", parsed_name.task, "/", str_util::Lowercase(parsed_name.type), ":", parsed_name.id); } } else { if (has_gpu_) { device = "/job:localhost/replica:0/task:0/gpu:0"; } else { device = "/job:localhost/replica:0/task:0/cpu:0"; } } auto it = devices_.find(device); if (it == devices_.end()) { return unknown_device_; } return it->second; } } // end namespace grappler } // end namespace tensorflow
#include "PhysicsGame.h" int main() { PhysicsGame* game = new PhysicsGame(); game->run("Physics Game", 1280, 720, false); delete game; return 0; }
/* Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "precompiled.hpp" #include <string> #include "msg.hpp" #include "session_base.hpp" #include "err.hpp" #include "plain_server.hpp" #include "wire.hpp" #include "plain_common.hpp" zmq::plain_server_t::plain_server_t (session_base_t *session_, const std::string &peer_address_, const options_t &options_) : mechanism_base_t (session_, options_), zap_client_common_handshake_t ( session_, peer_address_, options_, sending_welcome) { // Note that there is no point to PLAIN if ZAP is not set up to handle the // username and password, so if ZAP is not configured it is considered a // failure. // Given this is a backward-incompatible change, it's behind a socket // option disabled by default. if (options.zap_enforce_domain) zmq_assert (zap_required ()); } zmq::plain_server_t::~plain_server_t () { } int zmq::plain_server_t::next_handshake_command (msg_t *msg_) { int rc = 0; switch (state) { case sending_welcome: produce_welcome (msg_); state = waiting_for_initiate; break; case sending_ready: produce_ready (msg_); state = ready; break; case sending_error: produce_error (msg_); state = error_sent; break; default: errno = EAGAIN; rc = -1; } return rc; } int zmq::plain_server_t::process_handshake_command (msg_t *msg_) { int rc = 0; switch (state) { case waiting_for_hello: rc = process_hello (msg_); break; case waiting_for_initiate: rc = process_initiate (msg_); break; default: // TODO see comment in curve_server_t::process_handshake_command session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNSPECIFIED); errno = EPROTO; rc = -1; break; } if (rc == 0) { rc = msg_->close (); errno_assert (rc == 0); rc = msg_->init (); errno_assert (rc == 0); } return rc; } int zmq::plain_server_t::process_hello (msg_t *msg_) { int rc = check_basic_command_structure (msg_); if (rc == -1) return -1; const char *ptr = static_cast<char *> (msg_->data ()); size_t bytes_left = msg_->size (); if (bytes_left < hello_prefix_len || memcmp (ptr, hello_prefix, hello_prefix_len) != 0) { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } ptr += hello_prefix_len; bytes_left -= hello_prefix_len; if (bytes_left < 1) { // PLAIN I: invalid PLAIN client, did not send username session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } const uint8_t username_length = *ptr++; bytes_left -= sizeof (username_length); if (bytes_left < username_length) { // PLAIN I: invalid PLAIN client, sent malformed username session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } const std::string username = std::string (ptr, username_length); ptr += username_length; bytes_left -= username_length; if (bytes_left < 1) { // PLAIN I: invalid PLAIN client, did not send password session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } const uint8_t password_length = *ptr++; bytes_left -= sizeof (password_length); if (bytes_left != password_length) { // PLAIN I: invalid PLAIN client, sent malformed password or // extraneous data session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } const std::string password = std::string (ptr, password_length); // Use ZAP protocol (RFC 27) to authenticate the user. rc = session->zap_connect (); if (rc != 0) { session->get_socket ()->event_handshake_failed_no_detail ( session->get_endpoint (), EFAULT); return -1; } send_zap_request (username, password); state = waiting_for_zap_reply; // TODO actually, it is quite unlikely that we can read the ZAP // reply already, but removing this has some strange side-effect // (probably because the pipe's in_active flag is true until a read // is attempted) return receive_and_process_zap_reply () == -1 ? -1 : 0; } void zmq::plain_server_t::produce_welcome (msg_t *msg_) const { const int rc = msg_->init_size (welcome_prefix_len); errno_assert (rc == 0); memcpy (msg_->data (), welcome_prefix, welcome_prefix_len); } int zmq::plain_server_t::process_initiate (msg_t *msg_) { const unsigned char *ptr = static_cast<unsigned char *> (msg_->data ()); const size_t bytes_left = msg_->size (); if (bytes_left < initiate_prefix_len || memcmp (ptr, initiate_prefix, initiate_prefix_len) != 0) { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } const int rc = parse_metadata (ptr + initiate_prefix_len, bytes_left - initiate_prefix_len); if (rc == 0) state = sending_ready; return rc; } void zmq::plain_server_t::produce_ready (msg_t *msg_) const { make_command_with_basic_properties (msg_, ready_prefix, ready_prefix_len); } void zmq::plain_server_t::produce_error (msg_t *msg_) const { const char expected_status_code_len = 3; zmq_assert (status_code.length () == static_cast<size_t> (expected_status_code_len)); const size_t status_code_len_size = sizeof (expected_status_code_len); const int rc = msg_->init_size (error_prefix_len + status_code_len_size + expected_status_code_len); zmq_assert (rc == 0); char *msg_data = static_cast<char *> (msg_->data ()); memcpy (msg_data, error_prefix, error_prefix_len); msg_data[error_prefix_len] = expected_status_code_len; memcpy (msg_data + error_prefix_len + status_code_len_size, status_code.c_str (), status_code.length ()); } void zmq::plain_server_t::send_zap_request (const std::string &username_, const std::string &password_) { const uint8_t *credentials[] = { reinterpret_cast<const uint8_t *> (username_.c_str ()), reinterpret_cast<const uint8_t *> (password_.c_str ())}; size_t credentials_sizes[] = {username_.size (), password_.size ()}; const char plain_mechanism_name[] = "PLAIN"; zap_client_t::send_zap_request ( plain_mechanism_name, sizeof (plain_mechanism_name) - 1, credentials, credentials_sizes, sizeof (credentials) / sizeof (credentials[0])); }
#include "muscle.h" #include "dpreglist.h" #include "diaglist.h" #include "pwpath.h" #include "profile.h" #include "timing.h" #define TRACE 0 #define TRACE_PATH 0 #define LIST_DIAGS 0 static double g_dDPAreaWithoutDiags = 0.0; static double g_dDPAreaWithDiags = 0.0; static void OffsetPath(PWPath &Path, unsigned uOffsetA, unsigned uOffsetB) { const unsigned uEdgeCount = Path.GetEdgeCount(); for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); // Nasty hack -- poke new values back into path, circumventing class PWEdge &NonConstEdge = (PWEdge &) Edge; NonConstEdge.uPrefixLengthA += uOffsetA; NonConstEdge.uPrefixLengthB += uOffsetB; } } static void DiagToPath(const Diag &d, PWPath &Path) { Path.Clear(); const unsigned uLength = d.m_uLength; for (unsigned i = 0; i < uLength; ++i) { PWEdge Edge; Edge.cType = 'M'; Edge.uPrefixLengthA = d.m_uStartPosA + i + 1; Edge.uPrefixLengthB = d.m_uStartPosB + i + 1; Path.AppendEdge(Edge); } } static void AppendRegPath(PWPath &Path, const PWPath &RegPath) { const unsigned uRegEdgeCount = RegPath.GetEdgeCount(); for (unsigned uRegEdgeIndex = 0; uRegEdgeIndex < uRegEdgeCount; ++uRegEdgeIndex) { const PWEdge &RegEdge = RegPath.GetEdge(uRegEdgeIndex); Path.AppendEdge(RegEdge); } } SCORE GlobalAlignDiags(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path) { #if LIST_DIAGS TICKS t1 = GetClockTicks(); #endif DiagList DL; if (ALPHA_Amino == g_Alpha) FindDiags(PA, uLengthA, PB, uLengthB, DL); else if (ALPHA_DNA == g_Alpha || ALPHA_RNA == g_Alpha) FindDiagsNuc(PA, uLengthA, PB, uLengthB, DL); else Quit("GlobalAlignDiags: bad alpha"); #if TRACE Log("GlobalAlignDiags, diag list:\n"); DL.LogMe(); #endif DL.Sort(); DL.DeleteIncompatible(); #if TRACE Log("After DeleteIncompatible:\n"); DL.LogMe(); #endif MergeDiags(DL); #if TRACE Log("After MergeDiags:\n"); DL.LogMe(); #endif DPRegionList RL; DiagListToDPRegionList(DL, RL, uLengthA, uLengthB); #if TRACE Log("RegionList:\n"); RL.LogMe(); #endif #if LIST_DIAGS { TICKS t2 = GetClockTicks(); unsigned uArea = RL.GetDPArea(); Log("ticks=%ld\n", (long) (t2 - t1)); Log("area=%u\n", uArea); } #endif g_dDPAreaWithoutDiags += uLengthA*uLengthB; double dDPAreaWithDiags = 0.0; const unsigned uRegionCount = RL.GetCount(); for (unsigned uRegionIndex = 0; uRegionIndex < uRegionCount; ++uRegionIndex) { const DPRegion &r = RL.Get(uRegionIndex); PWPath RegPath; if (DPREGIONTYPE_Diag == r.m_Type) { DiagToPath(r.m_Diag, RegPath); #if TRACE_PATH Log("DiagToPath, path=\n"); RegPath.LogMe(); #endif } else if (DPREGIONTYPE_Rect == r.m_Type) { const unsigned uRegStartPosA = r.m_Rect.m_uStartPosA; const unsigned uRegStartPosB = r.m_Rect.m_uStartPosB; const unsigned uRegLengthA = r.m_Rect.m_uLengthA; const unsigned uRegLengthB = r.m_Rect.m_uLengthB; const ProfPos *RegPA = PA + uRegStartPosA; const ProfPos *RegPB = PB + uRegStartPosB; dDPAreaWithDiags += uRegLengthA*uRegLengthB; GlobalAlignNoDiags(RegPA, uRegLengthA, RegPB, uRegLengthB, RegPath); #if TRACE_PATH Log("GlobalAlignNoDiags RegPath=\n"); RegPath.LogMe(); #endif OffsetPath(RegPath, uRegStartPosA, uRegStartPosB); #if TRACE_PATH Log("After offset path, RegPath=\n"); RegPath.LogMe(); #endif } else Quit("GlobalAlignDiags, Invalid region type %u", r.m_Type); AppendRegPath(Path, RegPath); #if TRACE_PATH Log("After AppendPath, path="); Path.LogMe(); #endif } #if TRACE { double dDPAreaWithoutDiags = uLengthA*uLengthB; Log("DP area with diags %.3g without %.3g pct saved %.3g %%\n", dDPAreaWithDiags, dDPAreaWithoutDiags, (1.0 - dDPAreaWithDiags/dDPAreaWithoutDiags)*100.0); } #endif g_dDPAreaWithDiags += dDPAreaWithDiags; return 0; } void ListDiagSavings() { if (!g_bVerbose || !g_bDiags) return; double dAreaSaved = g_dDPAreaWithoutDiags - g_dDPAreaWithDiags; double dPct = dAreaSaved*100.0/g_dDPAreaWithoutDiags; Log("DP area saved by diagonals %-4.1f%%\n", dPct); }
#include "precompiled.h" #include "VisibilityQueryInterface.h" #include "Renderer.h" namespace EDRendererD3D { RenderShapeBase *VisibilityQueryInterface::theShapePtr = 0; VisibilityQueryInterface::VisibilityQueryInterface(void) { // queryPtr = 0; //depthSurfacePtr = 0; renderTargetPtr = 0; pixelCountThreshold = 0; } VisibilityQueryInterface::~VisibilityQueryInterface(void) { //queryPtr->Release(); } //void VisibilityQueryInterface::Initialize( // RenderTarget *_renderTargetPtr, IDirect3DSurface9 *_depthSurfacePtr) //{ // depthSurfacePtr = _depthSurfacePtr; // renderTargetPtr = _renderTargetPtr; // Renderer::theDevicePtr->CreateQuery(D3DQUERYTYPE_OCCLUSION, &queryPtr); //} //void VisibilityQueryInterface::IssueQuery(D3DXMATRIX *transformMat) //{ // // Begin the query // queryPtr->Issue(D3DISSUE_BEGIN); // // Render the object // LPDIRECT3DSURFACE9 pOldDS = NULL; // Renderer::theDevicePtr->GetDepthStencilSurface( &pOldDS ); // Renderer::theDevicePtr->SetDepthStencilSurface( depthSurfacePtr ); // //renderTargetPtr->ActivateTarget(0); // //Renderer::Clear(0,0, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 255), 1, 0); // assert(theShapePtr); // theShapePtr->SetWorldMatrix(transformMat); // theShapePtr->GetRenderContext()->AddRenderNode(theShapePtr); // theShapePtr->GetRenderContext()->RenderProcess(); // theShapePtr->GetRenderContext()->ClearRenderSet(); // //renderTargetPtr->RevertTarget(); // if( pOldDS ) // { // Renderer::theDevicePtr->SetDepthStencilSurface( pOldDS ); // pOldDS->Release(); // } // // End the query // queryPtr->Issue(D3DISSUE_END); //} VisibilityQueryResult VisibilityQueryInterface::GetResult(void) { VisibilityQueryResult retVal = VQR_Incomplete; //DWORD visiblePixels = 0; //if(S_FALSE == queryPtr->GetData(&visiblePixels, sizeof(DWORD), D3DGETDATA_FLUSH)) // retVal = VQR_Incomplete; //else //{ // if(visiblePixels > pixelCountThreshold) // retVal = VQR_Visible; // else // retVal = VQR_NotVisiable; //} return retVal; } }
/* * 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 "AsyncHandlerRegestry.h" #include <Exception.h> #include <Poco/Hash.h> #include "Configuration.h" namespace upmq { namespace broker { AsyncHandlerRegestry::AsyncHandlerRegestry() : _size(static_cast<size_t>(NET_CONFIG.maxConnections)), _thread("\tasync-handler-registry\t"), _connections(_size), _isRunning(false), _current_size(0), _connectionCounter(0) { log = &Poco::Logger::get(CONFIGURATION::Instance().log().name); TRACE(log); for (int i = 0; i < static_cast<int>(_size); ++i) { _freeNums.enqueue(i); } } void AsyncHandlerRegestry::addAHandler(AsyncTCPHandler *ahandler) { TRACE(log); int nextNum = freeNum(); if (nextNum != -1) { ahandler->num = static_cast<size_t>(nextNum); _connections[ahandler->num] = std::shared_ptr<AsyncTCPHandler>(ahandler); ++_current_size; } else { throw EXCEPTION("can't get free connection handeler", "try to increase max connections", -1); } } std::shared_ptr<AsyncTCPHandler> AsyncHandlerRegestry::aHandler(size_t num) const { TRACE(log); return _connections[num]; } void AsyncHandlerRegestry::deleteAHandler(size_t num) { TRACE(log); _freeNums.enqueue(static_cast<int>(num)); --_current_size; } void AsyncHandlerRegestry::put(size_t num, std::shared_ptr<MessageDataContainer> sMessage) { TRACE(log); if (_connections[num] == nullptr) { throw EXCEPTION("tcp connection not found", std::to_string(num), Proto::ERROR_CONNECTION); } _connections[num]->put(std::move(sMessage)); } void AsyncHandlerRegestry::run() { TRACE(log); _isRunning = true; int num; while (_isRunning) { if (_needToErase.wait_dequeue_timed(num, 1000000)) { auto &connection = _connections[static_cast<size_t>(num)]; if (connection && connection->needErase()) { if (connection->readComplete()) { connection = nullptr; } else { connection->onReadable(nullptr); if (connection->readComplete()) { connection = nullptr; } } } } } size_t cnt = 0; while (cnt != _connections.size()) { cnt = 0; for (auto &connection : _connections) { if (!connection) { ++cnt; continue; } if (connection->needErase()) { if (connection->readComplete()) { connection = nullptr; } else { connection->onReadable(nullptr); } } else { connection->setNeedErase(); connection->onReadable(nullptr); if (connection->readComplete()) { connection = nullptr; ++cnt; } } } } try { _connections.clear(); } catch (...) { } } int AsyncHandlerRegestry::erasedConnections() { TRACE(log); int erased = 0; for (auto &connection : _connections) { if (connection && connection->needErase()) { connection = nullptr; ++erased; } } return erased; } void AsyncHandlerRegestry::start() { TRACE(log); if (_isRunning) { return; } try { _thread.start(*this); } catch (Poco::Exception &pex) { throw EXCEPTION("can't start AsyncHandlerRegestry", pex.message(), -1); // error name and number } } void AsyncHandlerRegestry::stop() { TRACE(log); if (_isRunning) { _isRunning = false; _thread.join(); } } size_t AsyncHandlerRegestry::size() const { TRACE(log); return _current_size; } int AsyncHandlerRegestry::freeNum() const { TRACE(log); int num = 0; if (!_freeNums.wait_dequeue_timed(num, 1000000)) { return -1; } return num; } AsyncHandlerRegestry::~AsyncHandlerRegestry() { TRACE(log); }; void AsyncHandlerRegestry::needToErase(size_t num) { TRACE(log); _needToErase.enqueue(static_cast<int>(num)); } } // namespace broker } // namespace upmq
/** * @file * @brief General game bindings. **/ /* --- General game bindings module "crawl" */ #include "AppHdr.h" #include "l-libs.h" #include "chardump.h" #include "cluautil.h" #include "command.h" #include "delay.h" #include "dlua.h" #include "end.h" #include "english.h" #include "fight.h" #include "hints.h" #include "initfile.h" #include "item-name.h" #include "libutil.h" #include "macro.h" #include "menu.h" #include "message.h" #include "notes.h" #include "output.h" #include "perlin.h" #include "prompt.h" #include "religion.h" #include "sound.h" #include "state.h" #include "state.h" #include "stringutil.h" #include "tutorial.h" #include "unwind.h" #include "version.h" #include "view.h" #include "worley.h" #ifdef TARGET_OS_WINDOWS # include "windows.h" #else # include <sys/time.h> # include <time.h> #endif ///////////////////////////////////////////////////////////////////// // User accessible // /* --- Print a message. -- @param message message to print -- @channel channel to print on; defaults to 0 (<code>MSGCH_PLAIN</code>) function mpr(message, channel) */ static int crawl_mpr(lua_State *ls) { if (!crawl_state.io_inited) return 0; const char *message = luaL_checkstring(ls, 1); if (!message) return 0; int ch = MSGCH_PLAIN; if (lua_isnumber(ls, 2)) ch = luaL_checkint(ls, 2); else { const char *channel = lua_tostring(ls, 2); if (channel) ch = str_to_channel(channel); } if (ch < 0 || ch >= NUM_MESSAGE_CHANNELS) ch = MSGCH_PLAIN; mprf(static_cast<msg_channel_type>(ch), "%s", message); return 0; } /* --- function formatted_mpr(message, channel) */ static int crawl_formatted_mpr(lua_State *ls) { if (!crawl_state.io_inited) return 0; const char *message = luaL_checkstring(ls, 1); if (!message) return 0; int ch = MSGCH_PLAIN; if (lua_isnumber(ls, 2)) ch = luaL_checkint(ls, 2); else { const char *channel = lua_tostring(ls, 2); if (channel) ch = str_to_channel(channel); } if (ch < 0 || ch >= NUM_MESSAGE_CHANNELS) ch = MSGCH_PLAIN; formatted_mpr(formatted_string::parse_string(message), static_cast<msg_channel_type>(ch)); return 0; } /* --- Print to stderr for debugging hooks. function stderr(text) */ LUAFN(crawl_stderr) { const char *text = luaL_checkstring(ls, 1); fprintf(stderr, "%s\n", text); return 0; } /* --- Debugging spew. function dpr(text) */ LUAFN(crawl_dpr) { #ifdef DEBUG_DIAGNOSTICS const char *text = luaL_checkstring(ls, 1); if (crawl_state.io_inited) dprf("%s", text); #endif return 0; } /* --- function delay(ms) */ LUAWRAP(crawl_delay, delay(luaL_checkint(ls, 1))) /* --- function more() */ LUAWRAP(crawl_more, more()) /* --- function flush_prev_message() */ LUAWRAP(crawl_flush_prev_message, flush_prev_message()) /* --- function clear_messages(force) */ LUAWRAP(crawl_clear_messages, clear_messages(lua_isboolean(ls, 1) ? lua_toboolean(ls, 1) : false)) /* --- function redraw_screen() */ LUAWRAP(crawl_redraw_screen, redraw_screen()) /* --- function set_more_autoclear(flag) */ static int crawl_set_more_autoclear(lua_State *ls) { if (lua_isnone(ls, 1)) { luaL_argerror(ls, 1, "needs a boolean argument"); return 0; } set_more_autoclear(lua_toboolean(ls, 1)); return 0; } /* --- function enable_more(flag) */ static int crawl_enable_more(lua_State *ls) { if (lua_isnone(ls, 1)) { luaL_argerror(ls, 1, "needs a boolean argument"); return 0; } crawl_state.show_more_prompt = lua_toboolean(ls, 1); return 0; } /* --- Wrapper for <code>cancellable_get_line()</code>. Since that takes -- a pre-allocated buffer, an arbitrary 500-character limit is -- currently imposed. -- @return Either a string if one is input, or nil if input is cancelled function c_input_line() */ static int crawl_c_input_line(lua_State *ls) { char linebuf[500]; bool valid = !cancellable_get_line(linebuf, sizeof linebuf); if (valid) lua_pushstring(ls, linebuf); else lua_pushnil(ls); return 1; } /* --- Get input key (combo). -- @return integer representing the key (combo) input function getch() */ LUARET1(crawl_getch, number, getchm()) /* --- Check for pending input. -- @return 1 if there is, 0 otherwise function kbhit() */ LUARET1(crawl_kbhit, number, kbhit()) /* --- Flush the input buffer (typeahead). function flush_input() */ LUAWRAP(crawl_flush_input, flush_input_buffer(FLUSH_LUA)) static char _lua_char(lua_State *ls, int ndx, char defval = 0) { return lua_isnone(ls, ndx) || !lua_isstring(ls, ndx)? defval : lua_tostring(ls, ndx)[0]; } /* --- Ask the player a yes/no question. -- The player is supposed to answer by pressing Y or N. -- @param prompt question for the user -- @param safe accept lowercase answers? -- @param safeanswer if a letter, this will be considered a safe default -- @param clear_after clear the question after the user answers? -- @param noprompt if true, skip asking the question; just wait for the answer function yesno(prompt, safe, safeanswer, clear_after, interrupt_delays, noprompt) */ static int crawl_yesno(lua_State *ls) { const char *prompt = luaL_checkstring(ls, 1); const bool safe = lua_toboolean(ls, 2); const int safeanswer = _lua_char(ls, 3); const bool clear_after = lua_isnone(ls, 4) ? true : lua_toboolean(ls, 4); const bool interrupt_delays = lua_isnone(ls, 5) ? true : lua_toboolean(ls, 5); const bool noprompt = lua_isnone(ls, 6) ? false : lua_toboolean(ls, 6); lua_pushboolean(ls, yesno(prompt, safe, safeanswer, clear_after, interrupt_delays, noprompt)); return 1; } /* --- Ask the player a yes/no/quit question. -- Mostly like <code>yesno()</code>, but doesn't yet support as many -- parameters in this Lua binding. -- @param allow_all actually ask a yes/no/quit/all question function yesnoquit(prompt, safe, safeanswer, allow_all, clear_after) */ static int crawl_yesnoquit(lua_State *ls) { const char *prompt = luaL_checkstring(ls, 1); const bool safe = lua_toboolean(ls, 2); const int safeanswer = _lua_char(ls, 3); const bool allow_all = lua_isnone(ls, 4) ? false : lua_toboolean(ls, 4); const bool clear_after = lua_isnone(ls, 5) ? true : lua_toboolean(ls, 5); // Skipping the other params until somebody needs them. lua_pushnumber(ls, yesnoquit(prompt, safe, safeanswer, allow_all, clear_after)); return 1; } static void crawl_sendkeys_proc(lua_State *ls, int argi) { if (lua_isstring(ls, argi)) { const char *keys = luaL_checkstring(ls, argi); if (!keys) return; char32_t wc; while (int len = utf8towc(&wc, keys)) { macro_sendkeys_end_add_expanded(wc); keys += len; } } else if (lua_istable(ls, argi)) { for (int i = 1; ; ++i) { lua_rawgeti(ls, argi, i); if (lua_isnil(ls, -1)) { lua_pop(ls, 1); return; } crawl_sendkeys_proc(ls, lua_gettop(ls)); lua_pop(ls, 1); } } else if (lua_isnumber(ls, argi)) macro_sendkeys_end_add_expanded(luaL_checkint(ls, argi)); } /* --- XXX vararg function -- function sendkeys() */ static int crawl_sendkeys(lua_State *ls) { int top = lua_gettop(ls); for (int i = 1; i <= top; ++i) crawl_sendkeys_proc(ls, i); return 0; } /* --- Tell Crawl to process one command. -- @return whether it will actually do so? function process_command() */ static int crawl_process_command(lua_State *ls) { const bool will_process = !you_are_delayed() || current_delay()->is_macro(); if (will_process) { // This should only be called from a macro delay, but run_macro // may not have started the macro delay; do so now. if (!you_are_delayed()) start_delay<MacroDelay>(); start_delay<MacroProcessKeyDelay>(); } lua_pushboolean(ls, will_process); return 1; } static bool _check_can_do_command(lua_State *ls) { auto delay = current_delay(); if (delay && !delay->is_macro()) { luaL_error(ls, "Cannot currently process new keys (%s delay active)", delay->name()); return false; } if (you.turn_is_over) { luaL_error(ls, "Cannot currently process new keys (turn is over)"); return false; } return true; } /* --- function process_keys() */ static int crawl_process_keys(lua_State *ls) { if (!_check_can_do_command(ls)) return 0; // if there's pending input, pushing to the end of the buffer may separate // the first element of the sequence from the rest. TODO: should this be // changed to push the key sequence to the beginning of the buffer? See // crawl_do_commands below. if (has_pending_input()) { luaL_error(ls, "Cannot currently process new keys (there is pending input)"); return 0; } const char* keys = luaL_checkstring(ls, 1); if (strlen(keys) == 0) { luaL_argerror(ls, 1, "Must have at least one key to process."); return 0; } command_type cmd = key_to_command(keys[0], KMC_DEFAULT); if (cmd == CMD_NO_CMD) { luaL_argerror(ls, 1, "First key is invalid command"); return 0; } unwind_bool gen(crawl_state.invisible_targeting, lua_isboolean(ls, 2) && lua_toboolean(ls, 2)); flush_input_buffer(FLUSH_BEFORE_COMMAND); for (int i = 1, len = strlen(keys); i < len; i++) macro_sendkeys_end_add_expanded(keys[i]); process_command(cmd); return 0; } static int crawl_set_sendkeys_errors(lua_State *ls) { // enable or disable crashing on flushing an incomplete sendkeys buffer. // used for tests, not generally useful in real life. Crashing only happens // in wizmode. const bool errors = lua_toboolean(ls, 1); crawl_state.nonempty_buffer_flush_errors = errors; return 0; } static int crawl_do_commands(lua_State *ls) { if (!_check_can_do_command(ls)) return 0; unwind_bool gen(crawl_state.invisible_targeting, lua_isboolean(ls, 2) && lua_toboolean(ls, 2)); if (lua_isboolean(ls, 2)) lua_pop(ls, 1); if (!lua_istable(ls, 1)) { luaL_argerror(ls, 1, "Must be an array"); return 0; } vector<string> commands; lua_pushnil(ls); while (lua_next(ls, 1)) { if (!lua_isstring(ls, -1)) { luaL_argerror(ls, 1, "Table contains non-string"); return 0; } commands.push_back(lua_tostring(ls, -1)); lua_pop(ls, 1); } bool first = true; command_type firstcmd = CMD_NO_CMD; deque<command_type> cmd_seq; for (const auto& command : commands) { command_type cmd = name_to_command(command); if (cmd == CMD_NO_CMD) { luaL_argerror(ls, 1, ("Invalid command: " + command).c_str()); return 0; } if (first) { firstcmd = cmd; first = false; } else cmd_seq.push_front(cmd); // reverse order for adding below } flush_input_buffer(FLUSH_BEFORE_COMMAND); // insert commands to the front of the macro buffer so that they are // guaranteed to be processed adjacent to firstcmd for (auto c : cmd_seq) macro_buf_add_cmd(c, true); process_command(firstcmd); return 0; } #ifdef USE_SOUND /* --- Play a sound. -- @param sf filename of sound to play function playsound(sf) */ static int crawl_playsound(lua_State *ls) { const char *sf = luaL_checkstring(ls, 1); if (!sf) return 0; play_sound(sf); return 0; } #endif /* --- Run a macro. -- @param macroname name of macro to run function runmacro(macroname) */ static int crawl_runmacro(lua_State *ls) { const char *macroname = luaL_checkstring(ls, 1); if (!macroname) return 0; run_macro(macroname); return 0; } /* --- Set user options from string. -- @param s string of options to set, in same format as <tt>init.txt</tt>/<tt>.crawlrc</tt>. function setopt(s) */ static int crawl_setopt(lua_State *ls) { if (!lua_isstring(ls, 1)) return 0; const char *s = lua_tostring(ls, 1); if (s) { // Note that the conditional script can contain nested Lua[ ]Lua code. read_options(s, true); } return 0; } /* --- Read options from file. -- @param filename name of file to read from function read_options(filename) */ static int crawl_read_options(lua_State *ls) { if (!lua_isstring(ls, 1)) return 0; const char* filename = lua_tostring(ls, 1); Options.include(filename, true, true); return 0; } static int crawl_bindkey(lua_State *ls) { const char *s = nullptr; if (lua_isstring(ls, 1)) s = lua_tostring(ls, 1); if (!s || !lua_isfunction(ls, 2) || lua_gettop(ls) != 2) return 0; lua_pushvalue(ls, 2); string name = clua.setuniqregistry(); if (lua_gettop(ls) != 2) { fprintf(stderr, "Stack top has changed!\n"); lua_settop(ls, 2); } macro_userfn(s, name.c_str()); return 0; } static int crawl_msgch_num(lua_State *ls) { const char *s = luaL_checkstring(ls, 1); if (!s) return 0; int ch = str_to_channel(s); if (ch == -1) return 0; lua_pushnumber(ls, ch); return 1; } static int crawl_msgch_name(lua_State *ls) { int num = luaL_checkint(ls, 1); string name = channel_to_str(num); lua_pushstring(ls, name.c_str()); return 1; } static int crawl_take_note(lua_State *ls) { const char* msg = luaL_checkstring(ls, 1); take_note(Note(NOTE_MESSAGE, 0, 0, msg)); return 0; } static int crawl_messages(lua_State *ls) { const int count = luaL_checkint(ls, 1); lua_pushstring(ls, get_last_messages(count).c_str()); return 1; } #define REGEX_METATABLE "crawl.regex" #define MESSF_METATABLE "crawl.messf" static int crawl_regex(lua_State *ls) { const char *s = luaL_checkstring(ls, 1); if (!s) return 0; text_pattern **tpudata = clua_new_userdata< text_pattern* >(ls, REGEX_METATABLE); if (tpudata) { *tpudata = new text_pattern(s); return 1; } return 0; } static int crawl_regex_find(lua_State *ls) { text_pattern **pattern = clua_get_userdata< text_pattern* >(ls, REGEX_METATABLE); if (!pattern) return 0; const char *text = luaL_checkstring(ls, -1); if (!text) return 0; lua_pushboolean(ls, (*pattern)->matches(text)); return 1; } static int crawl_regex_equals(lua_State *ls) { text_pattern **pattern = clua_get_userdata< text_pattern* >(ls, REGEX_METATABLE); text_pattern **arg = clua_get_userdata< text_pattern* >(ls, REGEX_METATABLE, 2); lua_pushboolean(ls, pattern && arg && **pattern == **arg); return 1; } static const luaL_reg crawl_regex_ops[] = { { "matches", crawl_regex_find }, { "equals", crawl_regex_equals }, { nullptr, nullptr } }; static int crawl_message_filter(lua_State *ls) { const char *pattern = luaL_checkstring(ls, 1); if (!pattern) return 0; int num = lua_isnumber(ls, 2)? luaL_checkint(ls, 2) : -1; message_filter **mf = clua_new_userdata< message_filter* >(ls, MESSF_METATABLE); if (mf) { *mf = new message_filter(num, pattern); return 1; } return 0; } static int crawl_messf_matches(lua_State *ls) { message_filter **mf = clua_get_userdata< message_filter* >(ls, MESSF_METATABLE); if (!mf) return 0; const char *pattern = luaL_checkstring(ls, 2); int ch = luaL_checkint(ls, 3); if (pattern) { bool filt = (*mf)->is_filtered(ch, pattern); lua_pushboolean(ls, filt); return 1; } return 0; } static int crawl_messf_equals(lua_State *ls) { message_filter **mf = clua_get_userdata< message_filter* >(ls, MESSF_METATABLE); message_filter **arg = clua_get_userdata< message_filter* >(ls, MESSF_METATABLE, 2); lua_pushboolean(ls, mf && arg && **mf == **arg); return 1; } static const luaL_reg crawl_messf_ops[] = { { "matches", crawl_messf_matches }, { "equals", crawl_messf_equals }, { nullptr, nullptr } }; static int crawl_trim(lua_State *ls) { const char *s = luaL_checkstring(ls, 1); if (!s) return 0; string text = s; trim_string(text); lua_pushstring(ls, text.c_str()); return 1; } static int crawl_split(lua_State *ls) { const char *s = luaL_checkstring(ls, 1), *token = luaL_checkstring(ls, 2); if (!s || !token) return 0; vector<string> segs = split_string(token, s); if (lua_isboolean(ls, 3) && lua_toboolean(ls, 3)) reverse(segs.begin(), segs.end()); lua_newtable(ls); for (int i = 0, count = segs.size(); i < count; ++i) { lua_pushstring(ls, segs[i].c_str()); lua_rawseti(ls, -2, i + 1); } return 1; } static int _crawl_grammar(lua_State *ls) { description_level_type ndesc = DESC_PLAIN; if (lua_isstring(ls, 2)) ndesc = description_type_by_name(lua_tostring(ls, 2)); PLUARET(string, thing_do_grammar(ndesc, false, false, luaL_checkstring(ls, 1)).c_str()); } static int crawl_article_a(lua_State *ls) { const char *s = luaL_checkstring(ls, 1); bool lowercase = true; if (lua_isboolean(ls, 2)) lowercase = lua_toboolean(ls, 2); lua_pushstring(ls, article_a(s, lowercase).c_str()); return 1; } LUARET1(crawl_game_started, boolean, crawl_state.need_save || crawl_state.map_stat_gen || crawl_state.obj_stat_gen || crawl_state.test) LUARET1(crawl_stat_gain_prompt, boolean, crawl_state.stat_gain_prompt) LUARET1(crawl_random2, number, random2(luaL_checkint(ls, 1))) LUARET1(crawl_one_chance_in, boolean, one_chance_in(luaL_checkint(ls, 1))) LUARET1(crawl_random2avg, number, random2avg(luaL_checkint(ls, 1), luaL_checkint(ls, 2))) LUARET1(crawl_random_range, number, random_range(luaL_checkint(ls, 1), luaL_checkint(ls, 2), lua_isnumber(ls, 3)? luaL_checkint(ls, 3) : 1)) LUARET1(crawl_coinflip, boolean, coinflip()) LUARET1(crawl_roll_dice, number, lua_gettop(ls) == 1 ? roll_dice(1, luaL_checkint(ls, 1)) : roll_dice(luaL_checkint(ls, 1), luaL_checkint(ls, 2))) LUARET1(crawl_x_chance_in_y, boolean, x_chance_in_y(luaL_checkint(ls, 1), luaL_checkint(ls, 2))) LUARET1(crawl_div_rand_round, number, div_rand_round(luaL_checkint(ls, 1), luaL_checkint(ls, 2))) LUARET1(crawl_random_real, number, random_real()) LUARET1(crawl_weapon_check, boolean, wielded_weapon_check(you.weapon())) // Get the full worley noise datum for a given point static int crawl_worley(lua_State *ls) { double px = lua_tonumber(ls,1); double py = lua_tonumber(ls,2); double pz = lua_tonumber(ls,3); worley::noise_datum n = worley::noise(px,py,pz); lua_pushnumber(ls, n.distance[0]); lua_pushnumber(ls, n.distance[1]); lua_pushnumber(ls, n.id[0]); lua_pushnumber(ls, n.id[1]); lua_pushnumber(ls, n.pos[0][0]); lua_pushnumber(ls, n.pos[0][1]); lua_pushnumber(ls, n.pos[0][2]); lua_pushnumber(ls, n.pos[1][0]); lua_pushnumber(ls, n.pos[1][1]); lua_pushnumber(ls, n.pos[1][2]); return 10; } // Simpler return value for normal situations where we just // want the difference between the nearest point distances. // Also returns the id in case we want a per-node number. static int crawl_worley_diff(lua_State *ls) { double px = lua_tonumber(ls,1); double py = lua_tonumber(ls,2); double pz = lua_tonumber(ls,3); worley::noise_datum n = worley::noise(px,py,pz); lua_pushnumber(ls, n.distance[1]-n.distance[0]); lua_pushnumber(ls, n.id[0]); return 2; } // Splits a 32-bit integer into four bytes. This is useful // in conjunction with worley ids to get four random numbers // instead of one from the current node id. static int crawl_split_bytes(lua_State *ls) { uint32_t val = lua_tonumber(ls,1); uint8_t bytes[4] = { (uint8_t)(val >> 24), (uint8_t)(val >> 16), (uint8_t)(val >> 8), (uint8_t)(val) }; lua_pushnumber(ls, bytes[0]); lua_pushnumber(ls, bytes[1]); lua_pushnumber(ls, bytes[2]); lua_pushnumber(ls, bytes[3]); return 4; } // Supports 2D-4D Simplex noise. The first two parameters are required // for 2D noise, the next two are optional for 3D or 4D. // TODO: Could support octaves here but maybe it can be handled more // flexibly in lua static int crawl_simplex(lua_State *ls) { int dims = 0; double vals[4]; if (lua_isnumber(ls,1)) { vals[dims] = lua_tonumber(ls,1); dims++; } if (lua_isnumber(ls,2)) { vals[dims] = lua_tonumber(ls,2); dims++; } if (lua_isnumber(ls,3)) { vals[dims] = lua_tonumber(ls,3); dims++; } if (lua_isnumber(ls,4)) { vals[dims] = lua_tonumber(ls,4); dims++; } double result; switch (dims) { case 2: result = perlin::noise(vals[0],vals[1]); break; case 3: result = perlin::noise(vals[0],vals[1],vals[2]); break; case 4: result = perlin::noise(vals[0],vals[1],vals[2],vals[3]); break; default: return 0; // TODO: Throw error? } lua_pushnumber(ls, result); return 1; } static int crawl_is_tiles(lua_State *ls) { lua_pushboolean(ls, is_tiles()); return 1; } static int crawl_is_webtiles(lua_State *ls) { #ifdef USE_TILE_WEB lua_pushboolean(ls, true); #else lua_pushboolean(ls, false); #endif return 1; } static int crawl_is_touch_ui(lua_State *ls) { #ifdef TOUCH_UI lua_pushboolean(ls, true); #else lua_pushboolean(ls, false); #endif return 1; } static int crawl_get_command(lua_State *ls) { if (lua_gettop(ls) == 0) { lua_pushnil(ls); return 1; } const command_type cmd = name_to_command(luaL_checkstring(ls, 1)); string cmd_name = command_to_string(cmd, true); if (strcmp(cmd_name.c_str(), "<") == 0) cmd_name = "<<"; lua_pushstring(ls, cmd_name.c_str()); return 1; } LUAWRAP(crawl_endgame, screen_end_game(luaL_checkstring(ls, 1))) LUAWRAP(crawl_tutorial_hunger, set_tutorial_hunger(luaL_checkint(ls, 1))) LUAWRAP(crawl_tutorial_skill, set_tutorial_skill(luaL_checkstring(ls, 1), luaL_checkint(ls, 2))) LUAWRAP(crawl_tutorial_hint, tutorial_init_hint(luaL_checkstring(ls, 1))) LUAWRAP(crawl_print_hint, print_hint(luaL_checkstring(ls, 1))) /** * A random choice function crawl.random_element for clua. * * @param[in] list A lua array or table of elements to choose from. If list is * an array, a random element is chosen from list. If list is a table, the * values should be numeric or convertible to numeric and give the weights for * their corresponding keys. A value with no key will default to a weight of * 1. A random key is then returned based on these weights. * @returns A random element from list. */ static int crawl_random_element(lua_State *ls) { const int table_idx = 1; const int value_idx = 2; if (lua_gettop(ls) == 0) { lua_pushnil(ls); return 1; } // Only the first arg does anything now. Maybe this should // select from a variable number of table args? lua_pop(ls, lua_gettop(ls) - 1); // Keep max value on the stack, as it could be any type of value. lua_pushnil(ls); int rollsize = 0; lua_pushnil(ls); while (lua_next(ls, table_idx) != 0) { const int weight_idx = -1; const int key_idx = -2; int this_weight = lua_isnil(ls, weight_idx) ? 1 : (int)lua_tonumber(ls, weight_idx); if (rollsize > 0) { rollsize += this_weight; if (x_chance_in_y(this_weight, rollsize)) { lua_pushvalue(ls, key_idx); lua_replace(ls, value_idx); } } else { lua_pushvalue(ls, key_idx); lua_replace(ls, value_idx); rollsize = this_weight; } lua_pop(ls, 1); } lua_pushvalue(ls, value_idx); return 1; } static int crawl_err_trace(lua_State *ls) { const int nargs = lua_gettop(ls); const int err = lua_pcall(ls, nargs - 1, LUA_MULTRET, 0); if (err) { // This code from lua.c:traceback() (mostly) (void) lua_tostring(ls, 1); lua_getfield(ls, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(ls, -1)) { lua_pop(ls, 1); return lua_error(ls); } lua_getfield(ls, -1, "traceback"); if (!lua_isfunction(ls, -1)) { lua_pop(ls, 2); return lua_error(ls); } lua_pushvalue(ls, 1); lua_pushinteger(ls, 2); // Skip crawl_err_trace and traceback. lua_call(ls, 2, 1); // What's on top should be the error. lua_error(ls); } return lua_gettop(ls); } static int crawl_tutorial_msg(lua_State *ls) { const char *key = luaL_checkstring(ls, 1); if (!key) return 0; tutorial_msg(key, lua_isboolean(ls, 2) && lua_toboolean(ls, 2)); return 0; } LUAWRAP(crawl_dump_char, dump_char(you.your_name, true)) #ifdef WIZARD static int crawl_call_dlua(lua_State *ls) { if (!you.wizard) luaL_error(ls, "This function is wizard mode only."); const char* code = luaL_checkstring(ls, 1); if (!code) return 0; luaL_loadbuffer(dlua, code, strlen(code), "call_dlua"); int status = lua_pcall(dlua, 0, LUA_MULTRET, 0); if (status) { if (!lua_isnil(dlua, -1)) { const char *msg = lua_tostring(dlua, -1); if (msg == nullptr) msg = "(error object is not a string)"; mprf(MSGCH_ERROR, "%s", msg); } lua_settop(dlua, 0); // don't bother unwinding, just nuke the stack return 0; } if (lua_gettop(dlua) > 0) { // TODO: shuttle things other than a single scalar value if (lua_isnil(dlua, -1)) lua_pushnil(ls); else if (lua_isboolean(dlua, -1)) lua_pushboolean(ls, lua_toboolean(dlua, -1)); else if (lua_isnumber(dlua, -1)) lua_pushnumber(ls, lua_tonumber(dlua, -1)); else if (const char *ret = lua_tostring(dlua, -1)) lua_pushstring(ls, ret); else { mprf(MSGCH_ERROR, "call_dlua: cannot pass non-scalars yet (TODO)"); lua_pushnil(ls); } lua_settop(dlua, 0); // clear the stack return 1; } return 0; } #endif /** Implements the clua function crawl.version() The optional lua argument is a string from "long", "major", or "short" to determine which version type to return. The default is "long", and argument check is case-insensitive. */ static int crawl_version(lua_State *ls) { string type = "long"; if (lua_gettop(ls) > 0) { const char *ltype = luaL_checkstring(ls, 1); if (ltype) type = lowercase_string(ltype); } if (type == "long") lua_pushstring(ls, Version::Long); else if (type == "short") lua_pushstring(ls, Version::Short); else if (type == "major") lua_pushstring(ls, Version::Major); else { luaL_argerror(ls, 1, "must be a string \"long\", \"short\", or \"major\""); return 0; } return 1; } static const struct luaL_reg crawl_clib[] = { { "mpr", crawl_mpr }, { "formatted_mpr", crawl_formatted_mpr }, { "dpr", crawl_dpr }, { "stderr", crawl_stderr }, { "more", crawl_more }, { "more_autoclear", crawl_set_more_autoclear }, { "enable_more", crawl_enable_more }, { "flush_prev_message", crawl_flush_prev_message }, { "clear_messages", crawl_clear_messages }, { "delay", crawl_delay }, { "random2", crawl_random2 }, { "one_chance_in", crawl_one_chance_in }, { "random2avg", crawl_random2avg }, { "coinflip", crawl_coinflip }, { "roll_dice", crawl_roll_dice }, { "x_chance_in_y", crawl_x_chance_in_y }, { "random_range", crawl_random_range }, { "random_element", crawl_random_element }, { "div_rand_round", crawl_div_rand_round }, { "random_real", crawl_random_real }, { "worley", crawl_worley }, { "worley_diff", crawl_worley_diff }, { "split_bytes", crawl_split_bytes }, { "simplex", crawl_simplex }, { "redraw_screen", crawl_redraw_screen }, { "c_input_line", crawl_c_input_line}, { "getch", crawl_getch }, { "yesno", crawl_yesno }, { "yesnoquit", crawl_yesnoquit }, { "kbhit", crawl_kbhit }, { "flush_input", crawl_flush_input }, { "sendkeys", crawl_sendkeys }, { "process_command", crawl_process_command }, { "process_keys", crawl_process_keys }, { "set_sendkeys_errors", crawl_set_sendkeys_errors }, { "do_commands", crawl_do_commands }, #ifdef USE_SOUND { "playsound", crawl_playsound }, #endif { "runmacro", crawl_runmacro }, { "bindkey", crawl_bindkey }, { "setopt", crawl_setopt }, { "read_options", crawl_read_options }, { "msgch_num", crawl_msgch_num }, { "msgch_name", crawl_msgch_name }, { "take_note", crawl_take_note }, { "messages", crawl_messages }, { "regex", crawl_regex }, { "message_filter", crawl_message_filter }, { "trim", crawl_trim }, { "split", crawl_split }, { "grammar", _crawl_grammar }, { "article_a", crawl_article_a }, { "game_started", crawl_game_started }, { "stat_gain_prompt", crawl_stat_gain_prompt }, { "is_tiles", crawl_is_tiles }, { "is_webtiles", crawl_is_webtiles }, { "is_touch_ui", crawl_is_touch_ui }, { "err_trace", crawl_err_trace }, { "get_command", crawl_get_command }, { "endgame", crawl_endgame }, { "tutorial_msg", crawl_tutorial_msg }, { "dump_char", crawl_dump_char }, #ifdef WIZARD { "call_dlua", crawl_call_dlua }, #endif { "version", crawl_version }, { "weapon_check", crawl_weapon_check}, { nullptr, nullptr }, }; void cluaopen_crawl(lua_State *ls) { clua_register_metatable(ls, REGEX_METATABLE, crawl_regex_ops, lua_object_gc<text_pattern>); clua_register_metatable(ls, MESSF_METATABLE, crawl_messf_ops, lua_object_gc<message_filter>); luaL_openlib(ls, "crawl", crawl_clib, 0); } ///////////////////////////////////////////////////////////////////// // Non-user-accessible bindings (dlua). // LUAFN(_crawl_args) { return clua_stringtable(ls, SysEnv.cmd_args); } LUAFN(_crawl_milestone) { mark_milestone(luaL_checkstring(ls, 1), luaL_checkstring(ls, 2), luaL_checkstring(ls, 3)); return 0; } LUAFN(_crawl_redraw_view) { viewwindow(); return 0; } LUAFN(_crawl_redraw_stats) { you.wield_change = true; you.redraw_title = true; you.redraw_quiver = true; you.redraw_hit_points = true; you.redraw_magic_points = true; you.redraw_stats.init(true); you.redraw_experience = true; you.redraw_armour_class = true; you.redraw_evasion = true; you.redraw_status_lights = true; print_stats(); return 0; } LUAFN(_crawl_millis) { #ifdef TARGET_OS_WINDOWS // MSVC has no gettimeofday(). FILETIME ft; GetSystemTimeAsFileTime(&ft); uint64_t tt = ft.dwHighDateTime; tt <<= 32; tt |= ft.dwLowDateTime; tt /= 10000; tt -= 11644473600000ULL; lua_pushnumber(ls, tt); #else struct timeval tv; gettimeofday(&tv, nullptr); lua_pushnumber(ls, tv.tv_sec * 1000 + tv.tv_usec / 1000); #endif return 1; } static string _crawl_make_name(lua_State *ls) { // A quick wrapper around itemname:make_name. return make_name(); } LUARET1(crawl_make_name, string, _crawl_make_name(ls).c_str()) /** Check that a Lua argument is a god name, and store that god's enum in * a variable. * * @param argno The Lua argument number of the god name. Evaluated once. * @param godvar An existing writable lvalue to hold the enumeration value * of the god. Evaluated zero or one times. * @param fn The identifier to use as the function name in an error * message. Should generally be the Lua name of the calling * function. Stringified, not evaluated. * * @post If argument (argno) was not a string containing a valid god name, * we returned from the calling function with a Lua argument error. * godvar may or may not have been evaluated and/or assigned to. * @post If argument (argno) was a valid god name, godvar was evaluated * exactly once and assigned that god's enum value. */ #define CHECK_GOD_ARG(argno, godvar, fn) do \ { \ int _cg_arg = (argno); \ const char *_cg_name = luaL_checkstring(ls, _cg_arg); \ if (!_cg_name) \ return luaL_argerror(ls, _cg_arg, #fn " requires a god!"); \ if (((godvar) = str_to_god(_cg_name)) == GOD_NO_GOD) \ { \ return luaL_argerror(ls, _cg_arg, \ make_stringf("'%s' matches no god.", \ _cg_name).c_str()); \ } \ } while (0) LUAFN(_crawl_unavailable_god) { god_type god = GOD_NO_GOD; CHECK_GOD_ARG(1, god, unavailable_god); lua_pushboolean(ls, is_unavailable_god(god)); return 1; } LUAFN(_crawl_god_speaks) { if (!crawl_state.io_inited) return 0; god_type god = GOD_NO_GOD; CHECK_GOD_ARG(1, god, god_speaks); const char *message = luaL_checkstring(ls, 2); if (!message) return 0; god_speaks(god, message); return 0; } LUAFN(_crawl_set_max_runes) { int max_runes = luaL_checkinteger(ls, 1); if (max_runes < 0 || max_runes > NUM_RUNE_TYPES) luaL_error(ls, make_stringf("Bad number of max runes: %d", max_runes).c_str()); else you.obtainable_runes = max_runes; return 0; } LUAWRAP(_crawl_mark_game_won, crawl_state.mark_last_game_won()) LUAFN(crawl_hints_type) { if (crawl_state.game_is_tutorial()) lua_pushstring(ls, "tutorial"); else if (!crawl_state.game_is_hints()) lua_pushstring(ls, ""); else switch (Hints.hints_type) { case HINT_BERSERK_CHAR: lua_pushstring(ls, "berserk"); break; case HINT_RANGER_CHAR: lua_pushstring(ls, "ranger"); break; case HINT_MAGIC_CHAR: lua_pushstring(ls, "magic"); break; default: die("invalid hints_type"); } return 1; } static const struct luaL_reg crawl_dlib[] = { { "args", _crawl_args }, { "mark_milestone", _crawl_milestone }, { "redraw_view", _crawl_redraw_view }, { "redraw_stats", _crawl_redraw_stats }, { "god_speaks", _crawl_god_speaks }, { "millis", _crawl_millis }, { "make_name", crawl_make_name }, { "set_max_runes", _crawl_set_max_runes }, { "tutorial_hunger", crawl_tutorial_hunger }, { "tutorial_skill", crawl_tutorial_skill }, { "tutorial_hint", crawl_tutorial_hint }, { "print_hint", crawl_print_hint }, { "mark_game_won", _crawl_mark_game_won }, { "hints_type", crawl_hints_type }, { "unavailable_god", _crawl_unavailable_god }, { nullptr, nullptr } }; void dluaopen_crawl(lua_State *ls) { luaL_openlib(ls, "crawl", crawl_dlib, 0); }
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ // Software Guide : BeginLatex // // Even though \href{http://www.itk.org}{ITK} can be used to perform // general image processing tasks, the primary purpose of the toolkit is the // processing of medical image data. In that respect, additional // information about the images is considered mandatory. In particular the // information associated with the physical spacing between pixels and the // position of the image in space with respect to some world coordinate // system are extremely important. // // Image origin, image voxel directions (i.e. orientation) and spacing are fundamental to many // applications. Registration, for example, is performed in physical // coordinates. Improperly defined spacing, direction, and origins will result in // inconsistent results in such processes. Medical images with no spatial // information should not be used for medical diagnosis, image analysis, // feature extraction, assisted radiation therapy or image guided surgery. In // other words, medical images lacking spatial information are not only // useless but also hazardous. // // \begin{figure} \center // \includegraphics[width=\textwidth]{ImageOriginAndSpacing} // \itkcaption[ITK Image Geometrical Concepts]{Geometrical concepts associated // with the ITK image.} // \label{fig:ImageOriginAndSpacing} // \end{figure} // // Figure \ref{fig:ImageOriginAndSpacing} illustrates the main geometrical // concepts associated with the \doxygen{Image}. // In this figure, circles are // used to represent the center of pixels. The value of the pixel is assumed // to exist as a Dirac Delta Function located at the pixel center. Pixel // spacing is measured between the pixel centers and can be different along // each dimension. The image origin is associated with the coordinates of the // first pixel in the image. // For this simplified example, the voxel lattice is perfectly aligned with physical // space orientation, and the image direction is therefore an identity mapping. If the // voxel lattice samples were rotated with respect to physical space, then the image direction // would contain a rotation matrix with respect. // // A \emph{pixel} is considered to be the // rectangular region surrounding the pixel center holding the data // value. This can be viewed as the Voronoi region of the image grid, as // illustrated in the right side of the figure. Linear interpolation of // image values is performed inside the Delaunay region whose corners // are pixel centers. // // Software Guide : EndLatex #include "itkImage.h" // Function to simulate getting mouse click from an image static itk::Image< unsigned short, 3 >::IndexType GetIndexFromMouseClick() { itk::Image< unsigned short, 3 >::IndexType LeftEyeIndex; LeftEyeIndex[0]=60; LeftEyeIndex[1]=127; LeftEyeIndex[2]=93; return LeftEyeIndex; } int main(int, char *[]) { const unsigned int Dimension=3; typedef itk::Image< unsigned short, Dimension > ImageType; ImageType::Pointer image = ImageType::New(); const ImageType::SizeType size = {{ 200, 200, 200}}; //Size along {X,Y,Z} const ImageType::IndexType start = {{ 0, 0, 0 }}; // First index on {X,Y,Z} ImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions( region ); image->Allocate(true); // initialize buffer // to zero // Software Guide : BeginLatex // // Image spacing is represented in a \code{FixedArray} // whose size matches the dimension of the image. In order to manually set // the spacing of the image, an array of the corresponding type must be // created. The elements of the array should then be initialized with the // spacing between the centers of adjacent pixels. The following code // illustrates the methods available in the Image class for dealing with // spacing and origin. // // \index{itk::Image!Spacing} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageType::SpacingType spacing; // Note: measurement units (e.g., mm, inches, etc.) are defined by the application. spacing[0] = 0.33; // spacing along X spacing[1] = 0.33; // spacing along Y spacing[2] = 1.20; // spacing along Z // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The array can be assigned to the image using // the \code{SetSpacing()} method. // // \index{itk::Image!SetSpacing()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet image->SetSpacing( spacing ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The spacing information can be retrieved from an image by using the // \code{GetSpacing()} method. This method returns a reference to a // \code{FixedArray}. The returned object can then be used to read the // contents of the array. Note the use of the \code{const} keyword to indicate // that the array will not be modified. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const ImageType::SpacingType& sp = image->GetSpacing(); std::cout << "Spacing = "; std::cout << sp[0] << ", " << sp[1] << ", " << sp[2] << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The image origin is managed in a similar way to the spacing. A // \code{Point} of the appropriate dimension must first be // allocated. The coordinates of the origin can then be assigned to // every component. These coordinates correspond to the position of // the first pixel of the image with respect to an arbitrary // reference system in physical space. It is the user's // responsibility to make sure that multiple images used in the same // application are using a consistent reference system. This is // extremely important in image registration applications. // // The following code illustrates the creation and assignment of a variable // suitable for initializing the image origin. // // \index{itk::Image!origin} // \index{itk::Image!SetOrigin()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // coordinates of the center of the first pixel in N-D ImageType::PointType newOrigin; newOrigin.Fill(0.0); image->SetOrigin( newOrigin ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The origin can also be retrieved from an image by using the // \code{GetOrigin()} method. This will return a reference to a // \code{Point}. The reference can be used to read the contents of // the array. Note again the use of the \code{const} keyword to indicate // that the array contents will not be modified. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const ImageType::PointType & origin = image->GetOrigin(); std::cout << "Origin = "; std::cout << origin[0] << ", " << origin[1] << ", " << origin[2] << std::endl; // Software Guide : EndCodeSnippet //TODO: This example should really be writen for a more complicated direction cosine. i.e. // As the first index element increases, the 1st physcial space decreases. // Software Guide : BeginLatex // // The image direction matrix represents the orientation relationships between // the image samples and physical space coordinate systems. The image direction // matrix is an orthonormal matrix that describes the possible permutation of image Index // values and the rotational aspects that are needed to properly reconcile image index // organization with physical space axis. // The image directions is a $N x N$ matrix where $N$ is the dimension of the image. An // identity image direction indicates that increasing values of the 1st, 2nd, 3rd index element corresponds // to increasing values the 1st, 2nd and 3rd physcial space axis respectively, and that the voxel // samples are perfectly aligned with the physical space axis. // // The following code illustrates the creation and assignment of a variable // suitable for initializing the image direction with an identity. // // \index{itk::Image!direction} // \index{itk::Image!SetDirection()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // coordinates of the center of the first pixel in N-D ImageType::DirectionType direction; direction.SetIdentity(); image->SetDirection( direction ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The direction can also be retrieved from an image by using the // \code{GetDirection()} method. This will return a reference to a // \code{Matrix}. The reference can be used to read the contents of // the array. Note again the use of the \code{const} keyword to indicate // that the matrix contents can not be modified. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const ImageType::DirectionType& direct = image->GetDirection(); std::cout << "Direction = " << std::endl; std::cout << direct << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Once the spacing, origin, and direction of the image samples have been initialized, the image // will correctly map pixel indices to and from physical space // coordinates. The following code illustrates how a point in physical // space can be mapped into an image index for the purpose of reading the // content of the closest pixel. // // First, a \doxygen{Point} type must be declared. The point type is // templated over the type used to represent coordinates and over the // dimension of the space. In this particular case, the dimension of the // point must match the dimension of the image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Point< double, ImageType::ImageDimension > PointType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The Point class, like an \doxygen{Index}, is a relatively small and // simple object. For this reason, it is not reference-counted like the // large data objects in ITK. Consequently, it is also not manipulated // with \doxygen{SmartPointer}s. Point objects are simply declared as // instances of any other C++ class. Once the point is declared, its // components can be accessed using traditional array notation. In // particular, the \code{[]} operator is available. For efficiency reasons, // no bounds checking is performed on the index used to access a particular // point component. It is the user's responsibility to make sure that the // index is in the range $\{0,Dimension-1\}$. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet PointType point; point[0] = 1.45; // x coordinate point[1] = 7.21; // y coordinate point[2] = 9.28; // z coordinate // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The image will map the point to an index using the values of the // current spacing and origin. An index object must be provided to // receive the results of the mapping. The index object can be // instantiated by using the \code{IndexType} defined in the Image // type. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageType::IndexType pixelIndex; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \code{TransformPhysicalPointToIndex()} method of the image class // will compute the pixel index closest to the point provided. The method // checks for this index to be contained inside the current buffered pixel // data. The method returns a boolean indicating whether the resulting // index falls inside the buffered region or not. The output index should // not be used when the returned value of the method is \code{false}. // // The following lines illustrate the point to index mapping and the // subsequent use of the pixel index for accessing pixel data from the // image. // // \index{itk::Image!TransformPhysicalPointToIndex()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const bool isInside = image->TransformPhysicalPointToIndex( point, pixelIndex ); if ( isInside ) { ImageType::PixelType pixelValue = image->GetPixel( pixelIndex ); pixelValue += 5; image->SetPixel( pixelIndex, pixelValue ); } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Remember that \code{GetPixel()} and \code{SetPixel()} are very // inefficient methods for accessing pixel data. Image iterators should be // used when massive access to pixel data is required. // // Software Guide : EndLatex // // Software Guide : BeginLatex // // The following example illustrates the mathematical relationships between // Image Index locations and it's corresponding Physical Point representation // for a given Image. // // \index{itk::Image!PhysicalPoint} // \index{itk::Image!Index} // // Let us imagine that a graphical user interface exists // where the end user manually selects the voxel index location // of the left eye in a volume with a mouse interface. We need to // convert that index location to a physical location so that // laser guided surgery can be accurately performed. // // SoftwareGuide : EndLatex // Software Guide : BeginLatex // // Use a predefined function: TransformIndexToPhysicalPoint // SoftwareGuide : EndLatex // Software Guide : BeginCodeSnippet const ImageType::IndexType LeftEyeIndex = GetIndexFromMouseClick(); ImageType::PointType LeftEyePoint; image->TransformIndexToPhysicalPoint(LeftEyeIndex,LeftEyePoint); // Software Guide : EndCodeSnippet std::cout << "===========================================" << std::endl; std::cout << "The Left Eye Location is " << LeftEyePoint << std::endl; // Software Guide : BeginLatex // // For a given index $I_{3X1}$, the physical location $P_{3X1}$ is calculated // as following: // // \begin{equation} // P_{3X1} = O_{3X1} + D_{3X3} * diag( S_{3X1} )_{3x3} * I_{3X1} // \end{equation} // , where $D$ is an orthonormal direction cosines matrix and // $S$ is the image spacing diagonal matrix. // // In matlab syntax the conversions are: // // \begin{verbatim} // % Non-identity Spacing and Direction // spacing=diag( [0.9375, 0.9375, 1.5] ); // direction=[0.998189, 0.0569345, -0.0194113; // 0.0194429, -7.38061e-08, 0.999811; // 0.0569237, -0.998378, -0.00110704]; // point = origin + direction * spacing * LeftEyeIndex // \end{verbatim} // // A corresponding mathematical expansion of the C/C++ code is: // SoftwareGuide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Matrix<double, Dimension, Dimension> MatrixType; MatrixType SpacingMatrix; SpacingMatrix.Fill( 0.0F ); const ImageType::SpacingType & ImageSpacing = image->GetSpacing(); SpacingMatrix( 0,0 ) = ImageSpacing[0]; SpacingMatrix( 1,1 ) = ImageSpacing[1]; SpacingMatrix( 2,2 ) = ImageSpacing[2]; const ImageType::DirectionType & ImageDirectionCosines = image->GetDirection(); const ImageType::PointType &ImageOrigin = image->GetOrigin(); typedef itk::Vector< double, Dimension > VectorType; VectorType LeftEyeIndexVector; LeftEyeIndexVector[0]= LeftEyeIndex[0]; LeftEyeIndexVector[1]= LeftEyeIndex[1]; LeftEyeIndexVector[2]= LeftEyeIndex[2]; ImageType::PointType LeftEyePointByHand = ImageOrigin + ImageDirectionCosines * SpacingMatrix * LeftEyeIndexVector; // Software Guide : EndCodeSnippet std::cout << "===========================================" << std::endl; std::cout << "Spacing:: " << std::endl << SpacingMatrix << std::endl; std::cout << "===========================================" << std::endl; std::cout << "DirectionCosines:: " << std::endl << ImageDirectionCosines << std::endl; std::cout << "===========================================" << std::endl; std::cout << "Origin:: " << std::endl << ImageOrigin << std::endl; std::cout << "===========================================" << std::endl; std::cout << "The Left Eye Location is " << LeftEyePointByHand << std::endl; // // Check if two results are identical // if ( (LeftEyePointByHand - LeftEyePoint).GetNorm() < 0.01F ) { std::cout << "===========================================" << std::endl; std::cout << "Two results are identical as expected!" << std::endl; std::cout << "The Left Eye from TransformIndexToPhysicalPoint is " << LeftEyePoint << std::endl; std::cout << "The Left Eye from Math is " << LeftEyePointByHand << std::endl; } return EXIT_SUCCESS; }
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000. // (C) Copyright Eric Friedman 2002-2003. // (C) Copyright Antony Polukhin 2013. // 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). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TT_HAS_TRIVIAL_MOVE_ASSIGN_HPP_INCLUDED #define BOOST_TT_HAS_TRIVIAL_MOVE_ASSIGN_HPP_INCLUDED #include <boost/type_traits/intrinsics.hpp> #include <boost/type_traits/integral_constant.hpp> #if !defined(BOOST_HAS_TRIVIAL_MOVE_ASSIGN) || defined(BOOST_MSVC) || defined(BOOST_INTEL) #include <boost/type_traits/is_pod.hpp> #include <boost/type_traits/is_const.hpp> #include <boost/type_traits/is_volatile.hpp> #ifdef BOOST_MSVC #include <boost/type_traits/is_reference.hpp> #endif #endif #if defined(__GNUC__) || defined(__clang) #include <boost/type_traits/is_assignable.hpp> #include <boost/type_traits/is_volatile.hpp> #endif #ifdef __SUNPRO_CC #include <boost/type_traits/is_assignable.hpp> #include <boost/type_traits/remove_const.hpp> #if __cplusplus >= 201103 #define SOLARIS_EXTRA_CHECK && is_assignable<typename remove_const<T>::type&, typename remove_const<T>::type&&>::value #endif #endif #ifndef SOLARIS_EXTRA_CHECK #define SOLARIS_EXTRA_CHECK #endif namespace network_boost{ template <typename T> struct has_trivial_move_assign : public integral_constant<bool, #ifdef BOOST_HAS_TRIVIAL_MOVE_ASSIGN BOOST_HAS_TRIVIAL_MOVE_ASSIGN(T) #else ::network_boost::is_pod<T>::value && !::network_boost::is_const<T>::value && !::network_boost::is_volatile<T>::value SOLARIS_EXTRA_CHECK #endif > {}; template <> struct has_trivial_move_assign<void> : public false_type{}; #ifndef BOOST_NO_CV_VOID_SPECIALIZATIONS template <> struct has_trivial_move_assign<void const> : public false_type{}; template <> struct has_trivial_move_assign<void const volatile> : public false_type{}; template <> struct has_trivial_move_assign<void volatile> : public false_type{}; #endif template <class T> struct has_trivial_move_assign<T&> : public false_type{}; #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES template <class T> struct has_trivial_move_assign<T&&> : public false_type{}; #endif // Array types are not assignable: template <class T, std::size_t N> struct has_trivial_move_assign<T[N]> : public false_type{}; template <class T> struct has_trivial_move_assign<T[]> : public false_type{}; } // namespace network_boost #undef SOLARIS_EXTRA_CHECK #endif // BOOST_TT_HAS_TRIVIAL_MOVE_ASSIGN_HPP_INCLUDED
// Copyright (c) 2014-2017 The Storel Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privatesend-client.h" #include "coincontrol.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" #include "masternode-sync.h" #include "masternodeman.h" #include "script/sign.h" #include "txmempool.h" #include "util.h" #include "utilmoneystr.h" #include <memory> CPrivateSendClient privateSendClient; void CPrivateSendClient::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman) { if(fMasterNode) return; if(fLiteMode) return; // ignore all Storel related functionality if(!masternodeSync.IsBlockchainSynced()) return; if(strCommand == NetMsgType::DSQUEUE) { TRY_LOCK(cs_darksend, lockRecv); if(!lockRecv) return; if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSQUEUE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } CDarksendQueue dsq; vRecv >> dsq; // process every dsq only once BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) { if(q == dsq) { // LogPrint("privatesend", "DSQUEUE -- %s seen\n", dsq.ToString()); return; } } LogPrint("privatesend", "DSQUEUE -- %s new\n", dsq.ToString()); if(dsq.IsExpired()) return; masternode_info_t infoMn; if(!mnodeman.GetMasternodeInfo(dsq.vin.prevout, infoMn)) return; if(!dsq.CheckSignature(infoMn.pubKeyMasternode)) { // we probably have outdated info mnodeman.AskForMN(pfrom, dsq.vin.prevout, connman); return; } // if the queue is ready, submit if we can if(dsq.fReady) { if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != infoMn.addr) { LogPrintf("DSQUEUE -- message doesn't match current Masternode: infoMixingMasternode=%s, addr=%s\n", infoMixingMasternode.addr.ToString(), infoMn.addr.ToString()); return; } if(nState == POOL_STATE_QUEUE) { LogPrint("privatesend", "DSQUEUE -- PrivateSend queue (%s) is ready on masternode %s\n", dsq.ToString(), infoMn.addr.ToString()); SubmitDenominate(connman); } } else { BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) { if(q.vin == dsq.vin) { // no way same mn can send another "not yet ready" dsq this soon LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending WAY too many dsq messages\n", infoMn.addr.ToString()); return; } } int nThreshold = infoMn.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5; LogPrint("privatesend", "DSQUEUE -- nLastDsq: %d threshold: %d nDsqCount: %d\n", infoMn.nLastDsq, nThreshold, mnodeman.nDsqCount); //don't allow a few nodes to dominate the queuing process if(infoMn.nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) { LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending too many dsq messages\n", infoMn.addr.ToString()); return; } if(!mnodeman.AllowMixing(dsq.vin.prevout)) return; LogPrint("privatesend", "DSQUEUE -- new PrivateSend queue (%s) from masternode %s\n", dsq.ToString(), infoMn.addr.ToString()); if(infoMixingMasternode.fInfoValid && infoMixingMasternode.vin.prevout == dsq.vin.prevout) { dsq.fTried = true; } vecDarksendQueue.push_back(dsq); dsq.Relay(connman); } } else if(strCommand == NetMsgType::DSSTATUSUPDATE) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSSTATUSUPDATE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != pfrom->addr) { //LogPrintf("DSSTATUSUPDATE -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; int nMsgState; int nMsgEntriesCount; int nMsgStatusUpdate; int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgState >> nMsgEntriesCount >> nMsgStatusUpdate >> nMsgMessageID; LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgSessionID %d nMsgState: %d nEntriesCount: %d nMsgStatusUpdate: %d nMsgMessageID %d\n", nMsgSessionID, nMsgState, nEntriesCount, nMsgStatusUpdate, nMsgMessageID); if(nMsgState < POOL_STATE_MIN || nMsgState > POOL_STATE_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgState is out of bounds: %d\n", nMsgState); return; } if(nMsgStatusUpdate < STATUS_REJECTED || nMsgStatusUpdate > STATUS_ACCEPTED) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgStatusUpdate is out of bounds: %d\n", nMsgStatusUpdate); return; } if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } LogPrint("privatesend", "DSSTATUSUPDATE -- GetMessageByID: %s\n", CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID))); if(!CheckPoolStateUpdate(PoolState(nMsgState), nMsgEntriesCount, PoolStatusUpdate(nMsgStatusUpdate), PoolMessage(nMsgMessageID), nMsgSessionID)) { LogPrint("privatesend", "DSSTATUSUPDATE -- CheckPoolStateUpdate failed\n"); } } else if(strCommand == NetMsgType::DSFINALTX) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSFINALTX -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != pfrom->addr) { //LogPrintf("DSFINALTX -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; CTransaction txNew; vRecv >> nMsgSessionID >> txNew; if(nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSFINALTX -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID); return; } LogPrint("privatesend", "DSFINALTX -- txNew %s", txNew.ToString()); //check to see if input is spent already? (and probably not confirmed) SignFinalTransaction(txNew, pfrom, connman); } else if(strCommand == NetMsgType::DSCOMPLETE) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSCOMPLETE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != pfrom->addr) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current Masternode: infoMixingMasternode=%s addr=%s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgMessageID; if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSCOMPLETE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } if(nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID); return; } LogPrint("privatesend", "DSCOMPLETE -- nMsgSessionID %d nMsgMessageID %d (%s)\n", nMsgSessionID, nMsgMessageID, CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID))); CompletedTransaction(PoolMessage(nMsgMessageID)); } } void CPrivateSendClient::ResetPool() { nCachedLastSuccessBlock = 0; txMyCollateral = CMutableTransaction(); vecMasternodesUsed.clear(); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); } void CPrivateSendClient::SetNull() { // Client side nEntriesCount = 0; fLastEntryAccepted = false; infoMixingMasternode = masternode_info_t(); CPrivateSendBase::SetNull(); } // // Unlock coins after mixing fails or succeeds // void CPrivateSendClient::UnlockCoins() { while(true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if(!lockWallet) {MilliSleep(50); continue;} BOOST_FOREACH(COutPoint outpoint, vecOutPointLocked) pwalletMain->UnlockCoin(outpoint); break; } vecOutPointLocked.clear(); } std::string CPrivateSendClient::GetStatus() { static int nStatusMessageProgress = 0; nStatusMessageProgress += 10; std::string strSuffix = ""; if(WaitForAnotherBlock() || !masternodeSync.IsBlockchainSynced()) return strAutoDenomResult; switch(nState) { case POOL_STATE_IDLE: return _("PrivateSend is idle."); case POOL_STATE_QUEUE: if( nStatusMessageProgress % 70 <= 30) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 50) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Submitted to masternode, waiting in queue %s"), strSuffix);; case POOL_STATE_ACCEPTING_ENTRIES: if(nEntriesCount == 0) { nStatusMessageProgress = 0; return strAutoDenomResult; } else if(fLastEntryAccepted) { if(nStatusMessageProgress % 10 > 8) { fLastEntryAccepted = false; nStatusMessageProgress = 0; } return _("PrivateSend request complete:") + " " + _("Your transaction was accepted into the pool!"); } else { if( nStatusMessageProgress % 70 <= 40) return strprintf(_("Submitted following entries to masternode: %u / %d"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions()); else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions(), strSuffix); } case POOL_STATE_SIGNING: if( nStatusMessageProgress % 70 <= 40) return _("Found enough users, signing ..."); else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Found enough users, signing ( waiting %s )"), strSuffix); case POOL_STATE_ERROR: return _("PrivateSend request incomplete:") + " " + strLastMessage + " " + _("Will retry..."); case POOL_STATE_SUCCESS: return _("PrivateSend request complete:") + " " + strLastMessage; default: return strprintf(_("Unknown state: id = %u"), nState); } } // // Check the mixing progress and send client updates if a Masternode // void CPrivateSendClient::CheckPool() { // reset if we're here for 10 seconds if((nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) && GetTimeMillis() - nTimeLastSuccessfulStep >= 10000) { LogPrint("privatesend", "CPrivateSendClient::CheckPool -- timeout, RESETTING\n"); UnlockCoins(); if (nState == POOL_STATE_ERROR) { keyHolderStorage.ReturnAll(); } else { keyHolderStorage.KeepAll(); } SetNull(); } } // // Check for various timeouts (queue objects, mixing, etc) // void CPrivateSendClient::CheckTimeout() { { TRY_LOCK(cs_darksend, lockDS); if(!lockDS) return; // it's ok to fail here, we run this quite frequently // check mixing queue objects for timeouts std::vector<CDarksendQueue>::iterator it = vecDarksendQueue.begin(); while(it != vecDarksendQueue.end()) { if((*it).IsExpired()) { LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- Removing expired queue (%s)\n", (*it).ToString()); it = vecDarksendQueue.erase(it); } else ++it; } } if(!fEnablePrivateSend && !fMasterNode) return; // catching hanging sessions if(!fMasterNode) { switch(nState) { case POOL_STATE_ERROR: LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- Pool error -- Running CheckPool\n"); CheckPool(); break; case POOL_STATE_SUCCESS: LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- Pool success -- Running CheckPool\n"); CheckPool(); break; default: break; } } int nLagTime = fMasterNode ? 0 : 10000; // if we're the client, give the server a few extra seconds before resetting. int nTimeout = (nState == POOL_STATE_SIGNING) ? PRIVATESEND_SIGNING_TIMEOUT : PRIVATESEND_QUEUE_TIMEOUT; bool fTimeout = GetTimeMillis() - nTimeLastSuccessfulStep >= nTimeout*1000 + nLagTime; if(nState != POOL_STATE_IDLE && fTimeout) { LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- %s timed out (%ds) -- restting\n", (nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); SetState(POOL_STATE_ERROR); strLastMessage = _("Session timed out."); } } // // Execute a mixing denomination via a Masternode. // This is only ran from clients // bool CPrivateSendClient::SendDenominate(const std::vector<CTxIn>& vecTxIn, const std::vector<CTxOut>& vecTxOut, CConnman& connman) { if(fMasterNode) { LogPrintf("CPrivateSendClient::SendDenominate -- PrivateSend from a Masternode is not supported currently.\n"); return false; } if(txMyCollateral == CMutableTransaction()) { LogPrintf("CPrivateSendClient:SendDenominate -- PrivateSend collateral not set\n"); return false; } // lock the funds we're going to use BOOST_FOREACH(CTxIn txin, txMyCollateral.vin) vecOutPointLocked.push_back(txin.prevout); BOOST_FOREACH(CTxIn txin, vecTxIn) vecOutPointLocked.push_back(txin.prevout); // we should already be connected to a Masternode if(!nSessionID) { LogPrintf("CPrivateSendClient::SendDenominate -- No Masternode has been selected yet.\n"); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } if(!CheckDiskSpace()) { UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); fEnablePrivateSend = false; LogPrintf("CPrivateSendClient::SendDenominate -- Not enough disk space, disabling PrivateSend.\n"); return false; } SetState(POOL_STATE_ACCEPTING_ENTRIES); strLastMessage = ""; LogPrintf("CPrivateSendClient::SendDenominate -- Added transaction to pool.\n"); //check it against the memory pool to make sure it's valid { CValidationState validationState; CMutableTransaction tx; BOOST_FOREACH(const CTxIn& txin, vecTxIn) { LogPrint("privatesend", "CPrivateSendClient::SendDenominate -- txin=%s\n", txin.ToString()); tx.vin.push_back(txin); } BOOST_FOREACH(const CTxOut& txout, vecTxOut) { LogPrint("privatesend", "CPrivateSendClient::SendDenominate -- txout=%s\n", txout.ToString()); tx.vout.push_back(txout); } LogPrintf("CPrivateSendClient::SendDenominate -- Submitting partial tx %s", tx.ToString()); mempool.PrioritiseTransaction(tx.GetHash(), tx.GetHash().ToString(), 1000, 0.1*COIN); TRY_LOCK(cs_main, lockMain); if(!lockMain || !AcceptToMemoryPool(mempool, validationState, CTransaction(tx), false, NULL, false, true, true)) { LogPrintf("CPrivateSendClient::SendDenominate -- AcceptToMemoryPool() failed! tx=%s", tx.ToString()); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } } // store our entry for later use CDarkSendEntry entry(vecTxIn, vecTxOut, txMyCollateral); vecEntries.push_back(entry); RelayIn(entry, connman); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } // Incoming message from Masternode updating the progress of mixing bool CPrivateSendClient::CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew) { if(fMasterNode) return false; // do not update state when mixing client state is one of these if(nState == POOL_STATE_IDLE || nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) return false; strAutoDenomResult = _("Masternode:") + " " + CPrivateSend::GetMessageByID(nMessageID); // if rejected at any state if(nStatusUpdate == STATUS_REJECTED) { LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- entry is rejected by Masternode\n"); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); SetState(POOL_STATE_ERROR); strLastMessage = CPrivateSend::GetMessageByID(nMessageID); return true; } if(nStatusUpdate == STATUS_ACCEPTED && nState == nStateNew) { if(nStateNew == POOL_STATE_QUEUE && nSessionID == 0 && nSessionIDNew != 0) { // new session id should be set only in POOL_STATE_QUEUE state nSessionID = nSessionIDNew; nTimeLastSuccessfulStep = GetTimeMillis(); LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- set nSessionID to %d\n", nSessionID); return true; } else if(nStateNew == POOL_STATE_ACCEPTING_ENTRIES && nEntriesCount != nEntriesCountNew) { nEntriesCount = nEntriesCountNew; nTimeLastSuccessfulStep = GetTimeMillis(); fLastEntryAccepted = true; LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- new entry accepted!\n"); return true; } } // only situations above are allowed, fail in any other case return false; } // // After we receive the finalized transaction from the Masternode, we must // check it to make sure it's what we want, then sign it if we agree. // If we refuse to sign, it's possible we'll be charged collateral // bool CPrivateSendClient::SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman) { if(fMasterNode || pnode == NULL) return false; finalMutableTransaction = finalTransactionNew; LogPrintf("CPrivateSendClient::SignFinalTransaction -- finalMutableTransaction=%s", finalMutableTransaction.ToString()); // Make sure it's BIP69 compliant sort(finalMutableTransaction.vin.begin(), finalMutableTransaction.vin.end(), CompareInputBIP69()); sort(finalMutableTransaction.vout.begin(), finalMutableTransaction.vout.end(), CompareOutputBIP69()); if(finalMutableTransaction.GetHash() != finalTransactionNew.GetHash()) { LogPrintf("CPrivateSendClient::SignFinalTransaction -- WARNING! Masternode %s is not BIP69 compliant!\n", infoMixingMasternode.vin.prevout.ToStringShort()); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } std::vector<CTxIn> sigs; //make sure my inputs/outputs are present, otherwise refuse to sign BOOST_FOREACH(const CDarkSendEntry entry, vecEntries) { BOOST_FOREACH(const CTxDSIn txdsin, entry.vecTxDSIn) { /* Sign my transaction and all outputs */ int nMyInputIndex = -1; CScript prevPubKey = CScript(); CTxIn txin = CTxIn(); for(unsigned int i = 0; i < finalMutableTransaction.vin.size(); i++) { if(finalMutableTransaction.vin[i] == txdsin) { nMyInputIndex = i; prevPubKey = txdsin.prevPubKey; txin = txdsin; } } if(nMyInputIndex >= 0) { //might have to do this one input at a time? int nFoundOutputsCount = 0; CAmount nValue1 = 0; CAmount nValue2 = 0; for(unsigned int i = 0; i < finalMutableTransaction.vout.size(); i++) { BOOST_FOREACH(const CTxOut& txout, entry.vecTxDSOut) { if(finalMutableTransaction.vout[i] == txout) { nFoundOutputsCount++; nValue1 += finalMutableTransaction.vout[i].nValue; } } } BOOST_FOREACH(const CTxOut txout, entry.vecTxDSOut) nValue2 += txout.nValue; int nTargetOuputsCount = entry.vecTxDSOut.size(); if(nFoundOutputsCount < nTargetOuputsCount || nValue1 != nValue2) { // in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's // better then signing if the transaction doesn't look like what we wanted. LogPrintf("CPrivateSendClient::SignFinalTransaction -- My entries are not correct! Refusing to sign: nFoundOutputsCount: %d, nTargetOuputsCount: %d\n", nFoundOutputsCount, nTargetOuputsCount); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } const CKeyStore& keystore = *pwalletMain; LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- Signing my input %i\n", nMyInputIndex); if(!SignSignature(keystore, prevPubKey, finalMutableTransaction, nMyInputIndex, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { // changes scriptSig LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- Unable to sign my own transaction!\n"); // not sure what to do here, it will timeout...? } sigs.push_back(finalMutableTransaction.vin[nMyInputIndex]); LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- nMyInputIndex: %d, sigs.size(): %d, scriptSig=%s\n", nMyInputIndex, (int)sigs.size(), ScriptToAsmStr(finalMutableTransaction.vin[nMyInputIndex].scriptSig)); } } } if(sigs.empty()) { LogPrintf("CPrivateSendClient::SignFinalTransaction -- can't sign anything!\n"); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } // push all of our signatures to the Masternode LogPrintf("CPrivateSendClient::SignFinalTransaction -- pushing sigs to the masternode, finalMutableTransaction=%s", finalMutableTransaction.ToString()); connman.PushMessage(pnode, NetMsgType::DSSIGNFINALTX, sigs); SetState(POOL_STATE_SIGNING); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } void CPrivateSendClient::NewBlock() { static int64_t nTimeNewBlockReceived = 0; //we we're processing lots of blocks, we'll just leave if(GetTime() - nTimeNewBlockReceived < 10) return; nTimeNewBlockReceived = GetTime(); LogPrint("privatesend", "CPrivateSendClient::NewBlock\n"); CheckTimeout(); } // mixing transaction was completed (failed or successful) void CPrivateSendClient::CompletedTransaction(PoolMessage nMessageID) { if(fMasterNode) return; if(nMessageID == MSG_SUCCESS) { LogPrintf("CompletedTransaction -- success\n"); nCachedLastSuccessBlock = nCachedBlockHeight; keyHolderStorage.KeepAll(); } else { LogPrintf("CompletedTransaction -- error\n"); keyHolderStorage.ReturnAll(); } UnlockCoins(); SetNull(); strLastMessage = CPrivateSend::GetMessageByID(nMessageID); } bool CPrivateSendClient::WaitForAnotherBlock() { if(!masternodeSync.IsMasternodeListSynced()) return true; if(fPrivateSendMultiSession) return false; return nCachedBlockHeight - nCachedLastSuccessBlock < nMinBlocksToWait; } bool CPrivateSendClient::CheckAutomaticBackup() { switch(nWalletBackups) { case 0: LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Automatic backups disabled, no mixing available.\n"); strAutoDenomResult = _("Automatic backups disabled") + ", " + _("no mixing available."); fEnablePrivateSend = false; // stop mixing pwalletMain->nKeysLeftSinceAutoBackup = 0; // no backup, no "keys since last backup" return false; case -1: // Automatic backup failed, nothing else we can do until user fixes the issue manually. // There is no way to bring user attention in daemon mode so we just update status and // keep spaming if debug is on. LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- ERROR! Failed to create automatic backup.\n"); strAutoDenomResult = _("ERROR! Failed to create automatic backup") + ", " + _("see debug.log for details."); return false; case -2: // We were able to create automatic backup but keypool was not replenished because wallet is locked. // There is no way to bring user attention in daemon mode so we just update status and // keep spaming if debug is on. LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- WARNING! Failed to create replenish keypool, please unlock your wallet to do so.\n"); strAutoDenomResult = _("WARNING! Failed to replenish keypool, please unlock your wallet to do so.") + ", " + _("see debug.log for details."); return false; } if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_STOP) { // We should never get here via mixing itself but probably smth else is still actively using keypool LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Very low number of keys left: %d, no mixing available.\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d") + ", " + _("no mixing available."), pwalletMain->nKeysLeftSinceAutoBackup); // It's getting really dangerous, stop mixing fEnablePrivateSend = false; return false; } else if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING) { // Low number of keys left but it's still more or less safe to continue LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Very low number of keys left: %d\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d"), pwalletMain->nKeysLeftSinceAutoBackup); if(fCreateAutoBackups) { LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Trying to create new backup.\n"); std::string warningString; std::string errorString; if(!AutoBackupWallet(pwalletMain, "", warningString, errorString)) { if(!warningString.empty()) { // There were some issues saving backup but yet more or less safe to continue LogPrintf("CPrivateSendClient::CheckAutomaticBackup -- WARNING! Something went wrong on automatic backup: %s\n", warningString); } if(!errorString.empty()) { // Things are really broken LogPrintf("CPrivateSendClient::CheckAutomaticBackup -- ERROR! Failed to create automatic backup: %s\n", errorString); strAutoDenomResult = strprintf(_("ERROR! Failed to create automatic backup") + ": %s", errorString); return false; } } } else { // Wait for smth else (e.g. GUI action) to create automatic backup for us return false; } } LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Keys left since latest backup: %d\n", pwalletMain->nKeysLeftSinceAutoBackup); return true; } // // Passively run mixing in the background to anonymize funds based on the given configuration. // bool CPrivateSendClient::DoAutomaticDenominating(CConnman& connman, bool fDryRun) { if(fMasterNode) return false; // no client-side mixing on masternodes if(!fEnablePrivateSend) return false; if(!pwalletMain || pwalletMain->IsLocked(true)) return false; if(nState != POOL_STATE_IDLE) return false; if(!masternodeSync.IsMasternodeListSynced()) { strAutoDenomResult = _("Can't mix while sync in progress."); return false; } if(!CheckAutomaticBackup()) return false; if(GetEntriesCount() > 0) { strAutoDenomResult = _("Mixing in progress..."); return false; } TRY_LOCK(cs_darksend, lockDS); if(!lockDS) { strAutoDenomResult = _("Lock is already in place."); return false; } if(!fDryRun && pwalletMain->IsLocked(true)) { strAutoDenomResult = _("Wallet is locked."); return false; } if(WaitForAnotherBlock()) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Last successful PrivateSend action was too recent\n"); strAutoDenomResult = _("Last successful PrivateSend action was too recent."); return false; } if(mnodeman.size() == 0) { LogPrint("privatesend", "CPrivateSendClient::DoAutomaticDenominating -- No Masternodes detected\n"); strAutoDenomResult = _("No Masternodes detected."); return false; } CAmount nValueMin = CPrivateSend::GetSmallestDenomination(); // if there are no confirmed DS collateral inputs yet if(!pwalletMain->HasCollateralInputs()) { // should have some additional amount for them nValueMin += CPrivateSend::GetMaxCollateralAmount(); } // including denoms but applying some restrictions CAmount nBalanceNeedsAnonymized = pwalletMain->GetNeedsToBeAnonymizedBalance(nValueMin); // anonymizable balance is way too small if(nBalanceNeedsAnonymized < nValueMin) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Not enough funds to anonymize\n"); strAutoDenomResult = _("Not enough funds to anonymize."); return false; } // excluding denoms CAmount nBalanceAnonimizableNonDenom = pwalletMain->GetAnonymizableBalance(true); // denoms CAmount nBalanceDenominatedConf = pwalletMain->GetDenominatedBalance(); CAmount nBalanceDenominatedUnconf = pwalletMain->GetDenominatedBalance(true); CAmount nBalanceDenominated = nBalanceDenominatedConf + nBalanceDenominatedUnconf; LogPrint("privatesend", "CPrivateSendClient::DoAutomaticDenominating -- nValueMin: %f, nBalanceNeedsAnonymized: %f, nBalanceAnonimizableNonDenom: %f, nBalanceDenominatedConf: %f, nBalanceDenominatedUnconf: %f, nBalanceDenominated: %f\n", (float)nValueMin/COIN, (float)nBalanceNeedsAnonymized/COIN, (float)nBalanceAnonimizableNonDenom/COIN, (float)nBalanceDenominatedConf/COIN, (float)nBalanceDenominatedUnconf/COIN, (float)nBalanceDenominated/COIN); if(fDryRun) return true; // Check if we have should create more denominated inputs i.e. // there are funds to denominate and denominated balance does not exceed // max amount to mix yet. if(nBalanceAnonimizableNonDenom >= nValueMin + CPrivateSend::GetCollateralAmount() && nBalanceDenominated < nPrivateSendAmount*COIN) return CreateDenominated(connman); //check if we have the collateral sized inputs if(!pwalletMain->HasCollateralInputs()) return !pwalletMain->HasCollateralInputs(false) && MakeCollateralAmounts(connman); if(nSessionID) { strAutoDenomResult = _("Mixing in progress..."); return false; } // Initial phase, find a Masternode // Clean if there is anything left from previous session UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); // should be no unconfirmed denoms in non-multi-session mode if(!fPrivateSendMultiSession && nBalanceDenominatedUnconf > 0) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\n"); strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue."); return false; } //check our collateral and create new if needed std::string strReason; if(txMyCollateral == CMutableTransaction()) { if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- create collateral error:%s\n", strReason); return false; } } else { if(!CPrivateSend::IsCollateralValid(txMyCollateral)) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- invalid collateral, recreating...\n"); if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- create collateral error: %s\n", strReason); return false; } } } int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); // If we've used 90% of the Masternode list then drop the oldest first ~30% int nThreshold_high = nMnCountEnabled * 0.9; int nThreshold_low = nThreshold_high * 0.7; LogPrint("privatesend", "Checking vecMasternodesUsed: size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); if((int)vecMasternodesUsed.size() > nThreshold_high) { vecMasternodesUsed.erase(vecMasternodesUsed.begin(), vecMasternodesUsed.begin() + vecMasternodesUsed.size() - nThreshold_low); LogPrint("privatesend", " vecMasternodesUsed: new size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); } bool fUseQueue = GetRandInt(100) > 33; // don't use the queues all of the time for mixing unless we are a liquidity provider if((nLiquidityProvider || fUseQueue) && JoinExistingQueue(nBalanceNeedsAnonymized, connman)) return true; // do not initiate queue if we are a liquidity provider to avoid useless inter-mixing if(nLiquidityProvider) return false; if(StartNewQueue(nValueMin, nBalanceNeedsAnonymized, connman)) return true; strAutoDenomResult = _("No compatible Masternode found."); return false; } bool CPrivateSendClient::JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman) { std::vector<CAmount> vecStandardDenoms = CPrivateSend::GetStandardDenominations(); // Look through the queues and see if anything matches BOOST_FOREACH(CDarksendQueue& dsq, vecDarksendQueue) { // only try each queue once if(dsq.fTried) continue; dsq.fTried = true; if(dsq.IsExpired()) continue; masternode_info_t infoMn; if(!mnodeman.GetMasternodeInfo(dsq.vin.prevout, infoMn)) { LogPrintf("CPrivateSendClient::JoinExistingQueue -- dsq masternode is not in masternode list, masternode=%s\n", dsq.vin.prevout.ToStringShort()); continue; } if(infoMn.nProtocolVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) continue; std::vector<int> vecBits; if(!CPrivateSend::GetDenominationsBits(dsq.nDenom, vecBits)) { // incompatible denom continue; } // mixing rate limit i.e. nLastDsq check should already pass in DSQUEUE ProcessMessage // in order for dsq to get into vecDarksendQueue, so we should be safe to mix already, // no need for additional verification here LogPrint("privatesend", "CPrivateSendClient::JoinExistingQueue -- found valid queue: %s\n", dsq.ToString()); CAmount nValueInTmp = 0; std::vector<CTxIn> vecTxInTmp; std::vector<COutput> vCoinsTmp; // Try to match their denominations if possible, select at least 1 denominations if(!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, vecStandardDenoms[vecBits.front()], nBalanceNeedsAnonymized, vecTxInTmp, vCoinsTmp, nValueInTmp, 0, nPrivateSendRounds)) { LogPrintf("CPrivateSendClient::JoinExistingQueue -- Couldn't match denominations %d %d (%s)\n", vecBits.front(), dsq.nDenom, CPrivateSend::GetDenominationsToString(dsq.nDenom)); continue; } vecMasternodesUsed.push_back(dsq.vin.prevout); CNode* pnodeFound = NULL; bool fDisconnect = false; connman.ForNode(infoMn.addr, CConnman::AllNodes, [&pnodeFound, &fDisconnect](CNode* pnode) { pnodeFound = pnode; if(pnodeFound->fDisconnect) { fDisconnect = true; } else { pnodeFound->AddRef(); } return true; }); if (fDisconnect) continue; LogPrintf("CPrivateSendClient::JoinExistingQueue -- attempt to connect to masternode from queue, addr=%s\n", infoMn.addr.ToString()); // connect to Masternode and submit the queue request CNode* pnode = (pnodeFound && pnodeFound->fMasternode) ? pnodeFound : connman.ConnectNode(CAddress(infoMn.addr, NODE_NETWORK), NULL, true); if(pnode) { infoMixingMasternode = infoMn; nSessionDenom = dsq.nDenom; connman.PushMessage(pnode, NetMsgType::DSACCEPT, nSessionDenom, txMyCollateral); LogPrintf("CPrivateSendClient::JoinExistingQueue -- connected (from queue), sending DSACCEPT: nSessionDenom: %d (%s), addr=%s\n", nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), pnode->addr.ToString()); strAutoDenomResult = _("Mixing in progress..."); SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTimeMillis(); if(pnodeFound) { pnodeFound->Release(); } return true; } else { LogPrintf("CPrivateSendClient::JoinExistingQueue -- can't connect, addr=%s\n", infoMn.addr.ToString()); strAutoDenomResult = _("Error connecting to Masternode."); continue; } } return false; } bool CPrivateSendClient::StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman) { int nTries = 0; int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); // ** find the coins we'll use std::vector<CTxIn> vecTxIn; CAmount nValueInTmp = 0; if(!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vecTxIn, nValueInTmp, 0, nPrivateSendRounds)) { // this should never happen LogPrintf("CPrivateSendClient::StartNewQueue -- Can't mix: no compatible inputs found!\n"); strAutoDenomResult = _("Can't mix: no compatible inputs found!"); return false; } // otherwise, try one randomly while(nTries < 10) { masternode_info_t infoMn = mnodeman.FindRandomNotInVec(vecMasternodesUsed, MIN_PRIVATESEND_PEER_PROTO_VERSION); if(!infoMn.fInfoValid) { LogPrintf("CPrivateSendClient::StartNewQueue -- Can't find random masternode!\n"); strAutoDenomResult = _("Can't find random Masternode."); return false; } vecMasternodesUsed.push_back(infoMn.vin.prevout); if(infoMn.nLastDsq != 0 && infoMn.nLastDsq + nMnCountEnabled/5 > mnodeman.nDsqCount) { LogPrintf("CPrivateSendClient::StartNewQueue -- Too early to mix on this masternode!" " masternode=%s addr=%s nLastDsq=%d CountEnabled/5=%d nDsqCount=%d\n", infoMn.vin.prevout.ToStringShort(), infoMn.addr.ToString(), infoMn.nLastDsq, nMnCountEnabled/5, mnodeman.nDsqCount); nTries++; continue; } CNode* pnodeFound = NULL; bool fDisconnect = false; connman.ForNode(infoMn.addr, CConnman::AllNodes, [&pnodeFound, &fDisconnect](CNode* pnode) { pnodeFound = pnode; if(pnodeFound->fDisconnect) { fDisconnect = true; } else { pnodeFound->AddRef(); } return true; }); if (fDisconnect) { nTries++; continue; } LogPrintf("CPrivateSendClient::StartNewQueue -- attempt %d connection to Masternode %s\n", nTries, infoMn.addr.ToString()); CNode* pnode = (pnodeFound && pnodeFound->fMasternode) ? pnodeFound : connman.ConnectNode(CAddress(infoMn.addr, NODE_NETWORK), NULL, true); if(pnode) { LogPrintf("CPrivateSendClient::StartNewQueue -- connected, addr=%s\n", infoMn.addr.ToString()); infoMixingMasternode = infoMn; std::vector<CAmount> vecAmounts; pwalletMain->ConvertList(vecTxIn, vecAmounts); // try to get a single random denom out of vecAmounts while(nSessionDenom == 0) { nSessionDenom = CPrivateSend::GetDenominationsByAmounts(vecAmounts); } connman.PushMessage(pnode, NetMsgType::DSACCEPT, nSessionDenom, txMyCollateral); LogPrintf("CPrivateSendClient::StartNewQueue -- connected, sending DSACCEPT, nSessionDenom: %d (%s)\n", nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); strAutoDenomResult = _("Mixing in progress..."); SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTimeMillis(); if(pnodeFound) { pnodeFound->Release(); } return true; } else { LogPrintf("CPrivateSendClient::StartNewQueue -- can't connect, addr=%s\n", infoMn.addr.ToString()); nTries++; continue; } } return false; } bool CPrivateSendClient::SubmitDenominate(CConnman& connman) { std::string strError; std::vector<CTxIn> vecTxInRet; std::vector<CTxOut> vecTxOutRet; // Submit transaction to the pool if we get here // Try to use only inputs with the same number of rounds starting from the highest number of rounds possible for(int i = nPrivateSendRounds; i > 0; i--) { if(PrepareDenominate(i - 1, i, strError, vecTxInRet, vecTxOutRet)) { LogPrintf("CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for %d rounds, success\n", i); return SendDenominate(vecTxInRet, vecTxOutRet, connman); } LogPrint("privatesend", "CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for %d rounds, error: %s\n", i, strError); } // We failed? That's strange but let's just make final attempt and try to mix everything if(PrepareDenominate(0, nPrivateSendRounds, strError, vecTxInRet, vecTxOutRet)) { LogPrintf("CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for all rounds, success\n"); return SendDenominate(vecTxInRet, vecTxOutRet, connman); } // Should never actually get here but just in case LogPrintf("CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for all rounds, error: %s\n", strError); strAutoDenomResult = strError; return false; } bool CPrivateSendClient::PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, std::vector<CTxIn>& vecTxInRet, std::vector<CTxOut>& vecTxOutRet) { if(!pwalletMain) { strErrorRet = "Wallet is not initialized"; return false; } if (pwalletMain->IsLocked(true)) { strErrorRet = "Wallet locked, unable to create transaction!"; return false; } if (GetEntriesCount() > 0) { strErrorRet = "Already have pending entries in the PrivateSend pool"; return false; } // make sure returning vectors are empty before filling them up vecTxInRet.clear(); vecTxOutRet.clear(); // ** find the coins we'll use std::vector<CTxIn> vecTxIn; std::vector<COutput> vCoins; CAmount nValueIn = 0; /* Select the coins we'll use if nMinRounds >= 0 it means only denominated inputs are going in and coming out */ std::vector<int> vecBits; if (!CPrivateSend::GetDenominationsBits(nSessionDenom, vecBits)) { strErrorRet = "Incorrect session denom"; return false; } std::vector<CAmount> vecStandardDenoms = CPrivateSend::GetStandardDenominations(); bool fSelected = pwalletMain->SelectCoinsByDenominations(nSessionDenom, vecStandardDenoms[vecBits.front()], CPrivateSend::GetMaxPoolAmount(), vecTxIn, vCoins, nValueIn, nMinRounds, nMaxRounds); if (nMinRounds >= 0 && !fSelected) { strErrorRet = "Can't select current denominated inputs"; return false; } LogPrintf("CPrivateSendClient::PrepareDenominate -- max value: %f\n", (double)nValueIn/COIN); { LOCK(pwalletMain->cs_wallet); BOOST_FOREACH(CTxIn txin, vecTxIn) { pwalletMain->LockCoin(txin.prevout); } } CAmount nValueLeft = nValueIn; // Try to add every needed denomination, repeat up to 5-PRIVATESEND_ENTRY_MAX_SIZE times. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(PRIVATESEND_ENTRY_MAX_SIZE-5+1); while (nStep < nStepsMax) { BOOST_FOREACH(int nBit, vecBits) { CAmount nValueDenom = vecStandardDenoms[nBit]; if (nValueLeft - nValueDenom < 0) continue; // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxIn>::iterator it = vecTxIn.begin(); std::vector<COutput>::iterator it2 = vCoins.begin(); while (it2 != vCoins.end()) { // we have matching inputs if ((*it2).tx->vout[(*it2).i].nValue == nValueDenom) { // add new input in resulting vector vecTxInRet.push_back(*it); // remove corresponting items from initial vectors vecTxIn.erase(it); vCoins.erase(it2); CScript scriptDenom = keyHolderStorage.AddKey(pwalletMain).GetScriptForDestination(); // add new output CTxOut txout(nValueDenom, scriptDenom); vecTxOutRet.push_back(txout); // subtract denomination amount nValueLeft -= nValueDenom; // step is complete break; } ++it; ++it2; } } if(nValueLeft == 0) break; nStep++; } { // unlock unused coins LOCK(pwalletMain->cs_wallet); BOOST_FOREACH(CTxIn txin, vecTxIn) { pwalletMain->UnlockCoin(txin.prevout); } } if (CPrivateSend::GetDenominations(vecTxOutRet) != nSessionDenom) { // unlock used coins on failure LOCK(pwalletMain->cs_wallet); BOOST_FOREACH(CTxIn txin, vecTxInRet) { pwalletMain->UnlockCoin(txin.prevout); } keyHolderStorage.ReturnAll(); strErrorRet = "Can't make current denominated outputs"; return false; } // We also do not care about full amount as long as we have right denominations return true; } // Create collaterals by looping through inputs grouped by addresses bool CPrivateSendClient::MakeCollateralAmounts(CConnman& connman) { std::vector<CompactTallyItem> vecTally; if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally, false)) { LogPrint("privatesend", "CPrivateSendClient::MakeCollateralAmounts -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } // First try to use only non-denominated funds BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!MakeCollateralAmounts(item, false, connman)) continue; return true; } // There should be at least some denominated funds we should be able to break in pieces to continue mixing BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!MakeCollateralAmounts(item, true, connman)) continue; return true; } // If we got here then smth is terribly broken actually LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- ERROR: Can't make collaterals!\n"); return false; } // Split up large inputs or create fee sized inputs bool CPrivateSendClient::MakeCollateralAmounts(const CompactTallyItem& tallyItem, bool fTryDenominated, CConnman& connman) { LOCK2(cs_main, pwalletMain->cs_wallet); // denominated input is always a single one, so we can check its amount directly and return early if(!fTryDenominated && tallyItem.vecTxIn.size() == 1 && pwalletMain->IsDenominatedAmount(tallyItem.nAmount)) return false; CWalletTx wtx; CAmount nFeeRet = 0; int nChangePosRet = -1; std::string strFail = ""; std::vector<CRecipient> vecSend; // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); // make our change address CReserveKey reservekeyChange(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey, false)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); vecSend.push_back((CRecipient){scriptCollateral, CPrivateSend::GetMaxCollateralAmount(), false}); // try to use non-denominated and not mn-like funds first, select them explicitly CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // send change to the same address so that we were able create more denoms out of it later coinControl.destChange = tallyItem.txdest; BOOST_FOREACH(const CTxIn& txin, tallyItem.vecTxIn) coinControl.Select(txin.prevout); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED_NOT1000IFMN); if(!fSuccess) { LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- ONLY_NONDENOMINATED_NOT1000IFMN Error: %s\n", strFail); // If we failed then most likeky there are not enough funds on this address. if(fTryDenominated) { // Try to also use denominated coins (we can't mix denominated without collaterals anyway). // MN-like funds should not be touched in any case. if(!pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NOT1000IFMN)) { LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- ONLY_NOT1000IFMN Error: %s\n", strFail); reservekeyCollateral.ReturnKey(); return false; } } else { // Nothing else we can do. reservekeyCollateral.ReturnKey(); return false; } } reservekeyCollateral.KeepKey(); LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- txid=%s\n", wtx.GetHash().GetHex()); // use the same nCachedLastSuccessBlock as for DS mixinx to prevent race if(!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman)) { LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- CommitTransaction failed!\n"); return false; } nCachedLastSuccessBlock = nCachedBlockHeight; return true; } // Create denominations by looping through inputs grouped by addresses bool CPrivateSendClient::CreateDenominated(CConnman& connman) { LOCK2(cs_main, pwalletMain->cs_wallet); std::vector<CompactTallyItem> vecTally; if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally)) { LogPrint("privatesend", "CPrivateSendClient::CreateDenominated -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } bool fCreateMixingCollaterals = !pwalletMain->HasCollateralInputs(); BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!CreateDenominated(item, fCreateMixingCollaterals, connman)) continue; return true; } LogPrintf("CPrivateSendClient::CreateDenominated -- failed!\n"); return false; } // Create denominations bool CPrivateSendClient::CreateDenominated(const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals, CConnman& connman) { std::vector<CRecipient> vecSend; CKeyHolderStorage keyHolderStorageDenom; CAmount nValueLeft = tallyItem.nAmount; nValueLeft -= CPrivateSend::GetCollateralAmount(); // leave some room for fees LogPrintf("CreateDenominated0 nValueLeft: %f\n", (float)nValueLeft/COIN); // ****** Add an output for mixing collaterals ************ / if(fCreateMixingCollaterals) { CScript scriptCollateral = keyHolderStorageDenom.AddKey(pwalletMain).GetScriptForDestination(); vecSend.push_back((CRecipient){ scriptCollateral, CPrivateSend::GetMaxCollateralAmount(), false }); nValueLeft -= CPrivateSend::GetMaxCollateralAmount(); } // ****** Add outputs for denoms ************ / // try few times - skipping smallest denoms first if there are too many of them already, if failed - use them too int nOutputsTotal = 0; bool fSkip = true; do { std::vector<CAmount> vecStandardDenoms = CPrivateSend::GetStandardDenominations(); BOOST_REVERSE_FOREACH(CAmount nDenomValue, vecStandardDenoms) { if(fSkip) { // Note: denoms are skipped if there are already DENOMS_COUNT_MAX of them // and there are still larger denoms which can be used for mixing // check skipped denoms if(IsDenomSkipped(nDenomValue)) continue; // find new denoms to skip if any (ignore the largest one) if(nDenomValue != vecStandardDenoms.front() && pwalletMain->CountInputsWithAmount(nDenomValue) > DENOMS_COUNT_MAX) { strAutoDenomResult = strprintf(_("Too many %f denominations, removing."), (float)nDenomValue/COIN); LogPrintf("CPrivateSendClient::CreateDenominated -- %s\n", strAutoDenomResult); vecDenominationsSkipped.push_back(nDenomValue); continue; } } int nOutputs = 0; // add each output up to 11 times until it can't be added again while(nValueLeft - nDenomValue >= 0 && nOutputs <= 10) { CScript scriptDenom = keyHolderStorageDenom.AddKey(pwalletMain).GetScriptForDestination(); vecSend.push_back((CRecipient){ scriptDenom, nDenomValue, false }); //increment outputs and subtract denomination amount nOutputs++; nValueLeft -= nDenomValue; LogPrintf("CreateDenominated1: totalOutputs: %d, nOutputsTotal: %d, nOutputs: %d, nValueLeft: %f\n", nOutputsTotal + nOutputs, nOutputsTotal, nOutputs, (float)nValueLeft/COIN); } nOutputsTotal += nOutputs; if(nValueLeft == 0) break; } LogPrintf("CreateDenominated2: nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); // if there were no outputs added, start over without skipping fSkip = !fSkip; } while (nOutputsTotal == 0 && !fSkip); LogPrintf("CreateDenominated3: nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); // if we have anything left over, it will be automatically send back as change - there is no need to send it manually CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // send change to the same address so that we were able create more denoms out of it later coinControl.destChange = tallyItem.txdest; BOOST_FOREACH(const CTxIn& txin, tallyItem.vecTxIn) coinControl.Select(txin.prevout); CWalletTx wtx; CAmount nFeeRet = 0; int nChangePosRet = -1; std::string strFail = ""; // make our change address CReserveKey reservekeyChange(pwalletMain); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED_NOT1000IFMN); if(!fSuccess) { LogPrintf("CPrivateSendClient::CreateDenominated -- Error: %s\n", strFail); keyHolderStorageDenom.ReturnAll(); return false; } keyHolderStorageDenom.KeepAll(); if(!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman)) { LogPrintf("CPrivateSendClient::CreateDenominated -- CommitTransaction failed!\n"); return false; } // use the same nCachedLastSuccessBlock as for DS mixing to prevent race nCachedLastSuccessBlock = nCachedBlockHeight; LogPrintf("CPrivateSendClient::CreateDenominated -- txid=%s\n", wtx.GetHash().GetHex()); return true; } void CPrivateSendClient::RelayIn(const CDarkSendEntry& entry, CConnman& connman) { if(!infoMixingMasternode.fInfoValid) return; connman.ForNode(infoMixingMasternode.addr, [&entry, &connman](CNode* pnode) { LogPrintf("CPrivateSendClient::RelayIn -- found master, relaying message to %s\n", pnode->addr.ToString()); connman.PushMessage(pnode, NetMsgType::DSVIN, entry); return true; }); } void CPrivateSendClient::SetState(PoolState nStateNew) { LogPrintf("CPrivateSendClient::SetState -- nState: %d, nStateNew: %d\n", nState, nStateNew); nState = nStateNew; } void CPrivateSendClient::UpdatedBlockTip(const CBlockIndex *pindex) { nCachedBlockHeight = pindex->nHeight; LogPrint("privatesend", "CPrivateSendClient::UpdatedBlockTip -- nCachedBlockHeight: %d\n", nCachedBlockHeight); if(!fLiteMode && masternodeSync.IsMasternodeListSynced()) { NewBlock(); } CPrivateSend::CheckDSTXes(pindex->nHeight); } //TODO: Rename/move to core void ThreadCheckPrivateSendClient(CConnman& connman) { if(fLiteMode) return; // disable all Storel specific functionality static bool fOneThread; if(fOneThread) return; fOneThread = true; // Make this thread recognisable as the PrivateSend thread RenameThread("storel-ps-client"); unsigned int nTick = 0; unsigned int nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN; while (true) { MilliSleep(1000); if(masternodeSync.IsBlockchainSynced() && !ShutdownRequested()) { nTick++; privateSendClient.CheckTimeout(); if(nDoAutoNextRun == nTick) { privateSendClient.DoAutomaticDenominating(connman); nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN + GetRandInt(PRIVATESEND_AUTO_TIMEOUT_MAX - PRIVATESEND_AUTO_TIMEOUT_MIN); } } } }
/* Copyright 2017 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/compiler/xla/service/cpu/simple_orc_jit.h" #include <stdint.h> #include <algorithm> #include <list> #include <utility> #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/JITSymbol.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/Mangler.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/Host.h" #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/service/cpu/cpu_runtime.h" #include "tensorflow/compiler/xla/service/cpu/custom_call_target_registry.h" #include "tensorflow/compiler/xla/service/cpu/orc_jit_memory_mapper.h" #include "tensorflow/compiler/xla/service/cpu/runtime_conv2d.h" #include "tensorflow/compiler/xla/service/cpu/runtime_conv2d_mkl.h" #include "tensorflow/compiler/xla/service/cpu/runtime_fft.h" #include "tensorflow/compiler/xla/service/cpu/runtime_fork_join.h" #include "tensorflow/compiler/xla/service/cpu/runtime_fp16.h" #include "tensorflow/compiler/xla/service/cpu/runtime_matmul.h" #include "tensorflow/compiler/xla/service/cpu/runtime_matmul_mkl.h" #include "tensorflow/compiler/xla/service/cpu/runtime_single_threaded_conv2d.h" #include "tensorflow/compiler/xla/service/cpu/runtime_single_threaded_matmul.h" #include "tensorflow/compiler/xla/service/cpu/windows_compatibility.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/core/platform/logging.h" namespace xla { namespace cpu { namespace { llvm::SmallVector<std::string, 0> DetectMachineAttributes() { llvm::SmallVector<std::string, 0> result; llvm::StringMap<bool> host_features; if (llvm::sys::getHostCPUFeatures(host_features)) { for (auto& feature : host_features) { if (feature.second) { llvm::StringRef feature_name = feature.first(); // Skip avx512 for now, it isn't quite ready in LLVM. if (feature_name.startswith("avx512")) { continue; } result.push_back(feature_name); } } } return result; } llvm::StringRef GetHostCpuName() { auto cpu_name = llvm::sys::getHostCPUName(); // Skip avx512 for now, it isn't quite ready in LLVM. cpu_name.consume_back("-avx512"); return cpu_name; } } // namespace SimpleOrcJIT::SimpleOrcJIT(const llvm::TargetOptions& target_options, llvm::CodeGenOpt::Level opt_level, bool optimize_for_size, bool enable_fast_math, bool disable_expensive_passes, LLVMCompiler::ModuleHook pre_optimization_hook, LLVMCompiler::ModuleHook post_optimization_hook) : target_machine_( CHECK_NOTNULL(llvm::EngineBuilder() .setTargetOptions(target_options) .setOptLevel(opt_level) .selectTarget( /*TargetTriple=*/llvm::Triple(), /*MArch=*/"", /*MCPU=*/GetHostCpuName(), /*MAttrs=*/DetectMachineAttributes()))), disassembler_(*target_machine_), data_layout_(target_machine_->createDataLayout()), symbol_resolver_(llvm::orc::createLegacyLookupResolver( [this](const std::string& name) -> llvm::JITSymbol { return this->ResolveRuntimeSymbol(name); }, [](llvm::Error Err) { cantFail(std::move(Err), "lookupFlags failed"); })), object_layer_(execution_session_, [this](llvm::orc::VModuleKey) { llvm::orc::RTDyldObjectLinkingLayer::Resources result; result.MemMgr = std::make_shared<llvm::SectionMemoryManager>( orc_jit_memory_mapper::GetInstance()); result.Resolver = symbol_resolver_; return result; }), compile_layer_(object_layer_, CompilerFunctor(target_machine_.get(), &disassembler_, opt_level, optimize_for_size, enable_fast_math, disable_expensive_passes, std::move(pre_optimization_hook), std::move(post_optimization_hook))) { VLOG(1) << "CPU target: " << target_machine_->getTargetCPU().str() << " features: " << target_machine_->getTargetFeatureString().str(); } llvm::JITSymbol SimpleOrcJIT::ResolveRuntimeSymbol(const std::string& name) { if (const uint8* from_constant_pool = external_constant_pool_.Find(string(name))) { return llvm::JITEvaluatedSymbol( reinterpret_cast<uint64_t>(from_constant_pool), llvm::JITSymbolFlags::None); } void* func_addr = CustomCallTargetRegistry::Global()->Lookup(name); if (func_addr == nullptr) { return nullptr; } llvm::JITEvaluatedSymbol symbol_info(reinterpret_cast<uint64_t>(func_addr), llvm::JITSymbolFlags::None); return symbol_info; } SimpleOrcJIT::VModuleKeyT SimpleOrcJIT::AddModule( std::unique_ptr<llvm::Module> module) { auto key = execution_session_.allocateVModule(); cantFail(compile_layer_.addModule(key, std::move(module))); module_keys_.push_back(key); return key; } void SimpleOrcJIT::RemoveModule(SimpleOrcJIT::VModuleKeyT key) { module_keys_.erase(std::remove(module_keys_.begin(), module_keys_.end(), key), module_keys_.end()); cantFail(compile_layer_.removeModule(key)); } llvm::JITSymbol SimpleOrcJIT::FindCompiledSymbol(const std::string& name) { // Resolve symbol from last module to first, allowing later redefinitions of // symbols shadow earlier ones. for (auto& key : llvm::make_range(module_keys_.rbegin(), module_keys_.rend())) { if (auto symbol = compile_layer_.findSymbolIn(key, name, /*ExportedSymbolsOnly=*/true)) { return symbol; } } return nullptr; } namespace { // Register some known symbols with the CustomCallTargetRegistry. bool RegisterKnownJITSymbols() { CustomCallTargetRegistry* registry = CustomCallTargetRegistry::Global(); #define REGISTER_CPU_RUNTIME_SYMBOL(base_name) \ do { \ auto* function_address = \ reinterpret_cast<void*>(__xla_cpu_runtime_##base_name); \ registry->Register(xla::cpu::runtime::k##base_name##SymbolName, \ function_address); \ CHECK_EQ( \ tensorflow::StringPiece(xla::cpu::runtime::k##base_name##SymbolName), \ "__xla_cpu_runtime_" #base_name); \ } while (false) REGISTER_CPU_RUNTIME_SYMBOL(AcquireInfeedBufferForDequeue); REGISTER_CPU_RUNTIME_SYMBOL(AcquireOutfeedBufferForPopulation); REGISTER_CPU_RUNTIME_SYMBOL(MKLConvF32); REGISTER_CPU_RUNTIME_SYMBOL(EigenConvF16); REGISTER_CPU_RUNTIME_SYMBOL(EigenConvF32); REGISTER_CPU_RUNTIME_SYMBOL(EigenFft); REGISTER_CPU_RUNTIME_SYMBOL(EigenMatMulF16); REGISTER_CPU_RUNTIME_SYMBOL(EigenMatMulF32); REGISTER_CPU_RUNTIME_SYMBOL(EigenMatMulF64); REGISTER_CPU_RUNTIME_SYMBOL(MKLMatMulF32); REGISTER_CPU_RUNTIME_SYMBOL(MKLMatMulF64); REGISTER_CPU_RUNTIME_SYMBOL(MKLSingleThreadedMatMulF32); REGISTER_CPU_RUNTIME_SYMBOL(MKLSingleThreadedMatMulF64); REGISTER_CPU_RUNTIME_SYMBOL(EigenSingleThreadedConvF16); REGISTER_CPU_RUNTIME_SYMBOL(EigenSingleThreadedConvF32); REGISTER_CPU_RUNTIME_SYMBOL(EigenSingleThreadedMatMulF16); REGISTER_CPU_RUNTIME_SYMBOL(EigenSingleThreadedMatMulF32); REGISTER_CPU_RUNTIME_SYMBOL(EigenSingleThreadedMatMulF64); REGISTER_CPU_RUNTIME_SYMBOL(ParallelForkJoin); REGISTER_CPU_RUNTIME_SYMBOL(ReleaseInfeedBufferAfterDequeue); REGISTER_CPU_RUNTIME_SYMBOL(ReleaseOutfeedBufferAfterPopulation); registry->Register("__gnu_f2h_ieee", reinterpret_cast<void*>(__gnu_f2h_ieee)); registry->Register("__gnu_h2f_ieee", reinterpret_cast<void*>(__gnu_h2f_ieee)); #undef REGISTER_CPU_RUNTIME_SYMBOL // Register both the f32 (float) and f64 (double) versions of a libm symbol. // Unfortunately the double versions are overloaded on some systems, e.g. // Mac so we need an explicit cast. This requires passing the function signature // for that case. #define REGISTER_LIBM_SYMBOL(name, double_sig) \ do { \ registry->Register(#name "f", reinterpret_cast<void*>(name##f)); \ registry->Register( \ #name, reinterpret_cast<void*>(static_cast<double_sig>(name))); \ } while (false) REGISTER_LIBM_SYMBOL(acos, double (*)(double)); REGISTER_LIBM_SYMBOL(acosh, double (*)(double)); REGISTER_LIBM_SYMBOL(asin, double (*)(double)); REGISTER_LIBM_SYMBOL(asinh, double (*)(double)); REGISTER_LIBM_SYMBOL(atan, double (*)(double)); REGISTER_LIBM_SYMBOL(atan2, double (*)(double, double)); REGISTER_LIBM_SYMBOL(atanh, double (*)(double)); REGISTER_LIBM_SYMBOL(cbrt, double (*)(double)); REGISTER_LIBM_SYMBOL(ceil, double (*)(double)); REGISTER_LIBM_SYMBOL(copysign, double (*)(double, double)); REGISTER_LIBM_SYMBOL(cos, double (*)(double)); REGISTER_LIBM_SYMBOL(cosh, double (*)(double)); REGISTER_LIBM_SYMBOL(erf, double (*)(double)); REGISTER_LIBM_SYMBOL(erfc, double (*)(double)); REGISTER_LIBM_SYMBOL(exp, double (*)(double)); REGISTER_LIBM_SYMBOL(exp2, double (*)(double)); REGISTER_LIBM_SYMBOL(expm1, double (*)(double)); REGISTER_LIBM_SYMBOL(fabs, double (*)(double)); REGISTER_LIBM_SYMBOL(fdim, double (*)(double, double)); REGISTER_LIBM_SYMBOL(floor, double (*)(double)); REGISTER_LIBM_SYMBOL(fma, double (*)(double, double, double)); REGISTER_LIBM_SYMBOL(fmax, double (*)(double, double)); REGISTER_LIBM_SYMBOL(fmin, double (*)(double, double)); REGISTER_LIBM_SYMBOL(fmod, double (*)(double, double)); REGISTER_LIBM_SYMBOL(frexp, double (*)(double, int*)); REGISTER_LIBM_SYMBOL(hypot, double (*)(double, double)); REGISTER_LIBM_SYMBOL(ilogb, int (*)(double)); REGISTER_LIBM_SYMBOL(ldexp, double (*)(double, int)); REGISTER_LIBM_SYMBOL(lgamma, double (*)(double)); REGISTER_LIBM_SYMBOL(llrint, long long (*)(double)); // NOLINT(runtime/int) REGISTER_LIBM_SYMBOL(llround, long long (*)(double)); // NOLINT(runtime/int) REGISTER_LIBM_SYMBOL(log, double (*)(double)); REGISTER_LIBM_SYMBOL(log10, double (*)(double)); REGISTER_LIBM_SYMBOL(log1p, double (*)(double)); REGISTER_LIBM_SYMBOL(log2, double (*)(double)); REGISTER_LIBM_SYMBOL(logb, double (*)(double)); REGISTER_LIBM_SYMBOL(lrint, long (*)(double)); // NOLINT(runtime/int) REGISTER_LIBM_SYMBOL(lround, long (*)(double)); // NOLINT(runtime/int) REGISTER_LIBM_SYMBOL(modf, double (*)(double, double*)); REGISTER_LIBM_SYMBOL(nan, double (*)(const char*)); REGISTER_LIBM_SYMBOL(nearbyint, double (*)(double)); REGISTER_LIBM_SYMBOL(nextafter, double (*)(double, double)); REGISTER_LIBM_SYMBOL(nexttoward, double (*)(double, long double)); REGISTER_LIBM_SYMBOL(pow, double (*)(double, double)); REGISTER_LIBM_SYMBOL(remainder, double (*)(double, double)); REGISTER_LIBM_SYMBOL(remquo, double (*)(double, double, int*)); REGISTER_LIBM_SYMBOL(rint, double (*)(double)); REGISTER_LIBM_SYMBOL(round, double (*)(double)); REGISTER_LIBM_SYMBOL(scalbln, double (*)(double, long)); // NOLINT(runtime/int) REGISTER_LIBM_SYMBOL(scalbn, double (*)(double, int)); REGISTER_LIBM_SYMBOL(sin, double (*)(double)); #ifdef __APPLE__ REGISTER_LIBM_SYMBOL(__sincos, void (*)(double, double*, double*)); #else REGISTER_LIBM_SYMBOL(sincos, void (*)(double, double*, double*)); #endif REGISTER_LIBM_SYMBOL(sinh, double (*)(double)); REGISTER_LIBM_SYMBOL(sqrt, double (*)(double)); REGISTER_LIBM_SYMBOL(tan, double (*)(double)); REGISTER_LIBM_SYMBOL(tanh, double (*)(double)); REGISTER_LIBM_SYMBOL(tgamma, double (*)(double)); REGISTER_LIBM_SYMBOL(trunc, double (*)(double)); #undef REGISTER_LIBM_SYMBOL registry->Register("memcpy", reinterpret_cast<void*>(memcpy)); registry->Register("memmove", reinterpret_cast<void*>(memmove)); registry->Register("memset", reinterpret_cast<void*>(memset)); return true; } bool unused = RegisterKnownJITSymbols(); } // namespace } // namespace cpu } // namespace xla
// Copyright 2019 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/download/mixed_content_download_blocking.h" #include "base/debug/crash_logging.h" #include "base/debug/dump_without_crashing.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_functions.h" #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/common/chrome_features.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/download/public/common/download_stats.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/web_contents.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" #include "url/gurl.h" #include "url/origin.h" using download::DownloadSource; using MixedContentStatus = download::DownloadItem::MixedContentStatus; namespace { // Configuration for which extensions to warn/block. These parameters are set // differently for testing, so the listed defaults are only used when the flag // is manually enabled (and in unit tests). // // Extensions must be in lower case! Extensions are compared against save path // determined by Chrome prior to the user seeing a file picker. // // The extension list for each type (warn, block, silent block) can be // configured in two ways: as an allowlist, or as a blocklist. When the // extension list is a blocklist, extensions listed will trigger a // warning/block. If the extension list is configured as an allowlist, all // extensions EXCEPT those listed will trigger a warning/block. // // To make manual testing easier, the defaults are to have a small blocklist for // block/silent block, and a small allowlist for warnings. This means that // every mixed content download will at *least* generate a warning. const base::FeatureParam<bool> kTreatSilentBlockListAsAllowlist( &features::kTreatUnsafeDownloadsAsActive, "TreatSilentBlockListAsAllowlist", true); const base::FeatureParam<std::string> kSilentBlockExtensionList( &features::kTreatUnsafeDownloadsAsActive, "SilentBlockExtensionList", "silently_unblocked_for_testing"); const base::FeatureParam<bool> kTreatBlockListAsAllowlist( &features::kTreatUnsafeDownloadsAsActive, "TreatBlockListAsAllowlist", false); const base::FeatureParam<std::string> kBlockExtensionList( &features::kTreatUnsafeDownloadsAsActive, "BlockExtensionList", ""); // Note: this is an allowlist, so acts as a catch-all. const base::FeatureParam<bool> kTreatWarnListAsAllowlist( &features::kTreatUnsafeDownloadsAsActive, "TreatWarnListAsAllowlist", false); const base::FeatureParam<std::string> kWarnExtensionList( &features::kTreatUnsafeDownloadsAsActive, "WarnExtensionList", ""); // Map the string file extension to the corresponding histogram enum. InsecureDownloadExtensions GetExtensionEnumFromString( const std::string& extension) { if (extension.empty()) return InsecureDownloadExtensions::kNone; auto lower_extension = base::ToLowerASCII(extension); for (auto candidate : kExtensionsToEnum) { if (candidate.extension == lower_extension) return candidate.value; } return InsecureDownloadExtensions::kUnknown; } // Get the appropriate histogram metric name for the initiator/download security // state combo. std::string GetDownloadBlockingExtensionMetricName( InsecureDownloadSecurityStatus status) { switch (status) { case InsecureDownloadSecurityStatus::kInitiatorUnknownFileSecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorUnknown, kInsecureDownloadHistogramTargetSecure); case InsecureDownloadSecurityStatus::kInitiatorUnknownFileInsecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorUnknown, kInsecureDownloadHistogramTargetInsecure); case InsecureDownloadSecurityStatus::kInitiatorSecureFileSecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorSecure, kInsecureDownloadHistogramTargetSecure); case InsecureDownloadSecurityStatus::kInitiatorSecureFileInsecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorSecure, kInsecureDownloadHistogramTargetInsecure); case InsecureDownloadSecurityStatus::kInitiatorInsecureFileSecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorInsecure, kInsecureDownloadHistogramTargetSecure); case InsecureDownloadSecurityStatus::kInitiatorInsecureFileInsecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorInsecure, kInsecureDownloadHistogramTargetInsecure); case InsecureDownloadSecurityStatus::kInitiatorInferredSecureFileSecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorInferredSecure, kInsecureDownloadHistogramTargetSecure); case InsecureDownloadSecurityStatus::kInitiatorInferredSecureFileInsecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorInferredSecure, kInsecureDownloadHistogramTargetInsecure); case InsecureDownloadSecurityStatus::kInitiatorInferredInsecureFileSecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorInferredInsecure, kInsecureDownloadHistogramTargetSecure); case InsecureDownloadSecurityStatus::kInitiatorInferredInsecureFileInsecure: return GetDLBlockingHistogramName( kInsecureDownloadExtensionInitiatorInferredInsecure, kInsecureDownloadHistogramTargetInsecure); case InsecureDownloadSecurityStatus::kDownloadIgnored: NOTREACHED(); } NOTREACHED(); return std::string(); } // Get appropriate enum value for the initiator/download security state combo // for histogram reporting. |dl_secure| signifies whether the download was // a secure source. |inferred| is whether the initiator value is our best guess. InsecureDownloadSecurityStatus GetDownloadBlockingEnum( absl::optional<url::Origin> initiator, bool dl_secure, bool inferred) { if (inferred) { if (initiator->GetURL().SchemeIsCryptographic()) { if (dl_secure) { return InsecureDownloadSecurityStatus:: kInitiatorInferredSecureFileSecure; } return InsecureDownloadSecurityStatus:: kInitiatorInferredSecureFileInsecure; } if (dl_secure) { return InsecureDownloadSecurityStatus:: kInitiatorInferredInsecureFileSecure; } return InsecureDownloadSecurityStatus:: kInitiatorInferredInsecureFileInsecure; } if (!initiator.has_value()) { if (dl_secure) return InsecureDownloadSecurityStatus::kInitiatorUnknownFileSecure; return InsecureDownloadSecurityStatus::kInitiatorUnknownFileInsecure; } if (initiator->GetURL().SchemeIsCryptographic()) { if (dl_secure) return InsecureDownloadSecurityStatus::kInitiatorSecureFileSecure; return InsecureDownloadSecurityStatus::kInitiatorSecureFileInsecure; } if (dl_secure) return InsecureDownloadSecurityStatus::kInitiatorInsecureFileSecure; return InsecureDownloadSecurityStatus::kInitiatorInsecureFileInsecure; } struct MixedContentDownloadData { MixedContentDownloadData(const base::FilePath& path, const download::DownloadItem* item) : item_(item) { // Configure initiator. bool initiator_inferred = false; initiator_ = item->GetRequestInitiator(); if (!initiator_.has_value() && item->GetTabUrl().is_valid()) { initiator_inferred = true; initiator_ = url::Origin::Create(item->GetTabUrl()); } // Extract extension. #if defined(OS_WIN) extension_ = base::WideToUTF8(path.FinalExtension()); #else extension_ = path.FinalExtension(); #endif if (!extension_.empty()) { DCHECK_EQ(extension_[0], '.'); extension_ = extension_.substr(1); // Omit leading dot. } // Evaluate download security. is_redirect_chain_secure_ = true; // Skip over the final URL so that we can investigate it separately below. // The redirect chain always contains the final URL, so this is always safe // in Chrome, but some tests don't plan for it, so we check here. const auto& chain = item->GetUrlChain(); if (chain.size() > 1) { for (unsigned i = 0; i < chain.size() - 1; ++i) { const GURL& url = chain[i]; if (!network::IsUrlPotentiallyTrustworthy(url)) { is_redirect_chain_secure_ = false; break; } } } const GURL& dl_url = item->GetURL(); bool is_download_secure = is_redirect_chain_secure_ && (network::IsUrlPotentiallyTrustworthy(dl_url) || dl_url.SchemeIsBlob() || dl_url.SchemeIsFile()); // Configure mixed content status. // Some downloads don't qualify for blocking, and are thus never // mixed-content. At a minimum, this includes: // - retries/reloads (since the original DL would have been blocked, and // initiating context is lost on retry anyway), // - anything triggered directly from the address bar or similar. // - internal-Chrome downloads (e.g. downloading profile photos), // - webview/CCT, // - anything extension related, // - etc. // // TODO(1029062): INTERNAL_API is also used for background fetch. That // probably isn't the correct behavior, since INTERNAL_API is otherwise used // for Chrome stuff. Background fetch should probably be HTTPS-only. auto download_source = item->GetDownloadSource(); auto transition_type = item->GetTransitionType(); if (download_source == DownloadSource::RETRY || (transition_type & ui::PAGE_TRANSITION_RELOAD) || (transition_type & ui::PAGE_TRANSITION_TYPED) || (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) || (transition_type & ui::PAGE_TRANSITION_FORWARD_BACK) || (transition_type & ui::PAGE_TRANSITION_AUTO_TOPLEVEL) || (transition_type & ui::PAGE_TRANSITION_AUTO_BOOKMARK) || (transition_type & ui::PAGE_TRANSITION_FROM_API) || download_source == DownloadSource::OFFLINE_PAGE || download_source == DownloadSource::INTERNAL_API || download_source == DownloadSource::EXTENSION_API || download_source == DownloadSource::EXTENSION_INSTALLER) { base::UmaHistogramEnumeration( kInsecureDownloadHistogramName, InsecureDownloadSecurityStatus::kDownloadIgnored); is_mixed_content_ = false; } else { // Not ignorable download. // Record some metrics first. auto security_status = GetDownloadBlockingEnum( initiator_, is_download_secure, initiator_inferred); base::UmaHistogramEnumeration( GetDownloadBlockingExtensionMetricName(security_status), GetExtensionEnumFromString(extension_)); base::UmaHistogramEnumeration(kInsecureDownloadHistogramName, security_status); download::RecordDownloadValidationMetrics( download::DownloadMetricsCallsite::kMixContentDownloadBlocking, download::CheckDownloadConnectionSecurity(item->GetURL(), item->GetUrlChain()), download::DownloadContentFromMimeType(item->GetMimeType(), false)); is_mixed_content_ = (initiator_.has_value() && initiator_->GetURL().SchemeIsCryptographic() && !is_download_secure); } } absl::optional<url::Origin> initiator_; std::string extension_; const download::DownloadItem* item_; bool is_redirect_chain_secure_; bool is_mixed_content_; }; // Whether or not |extension| is contained in the comma-separated list in a // feature param specified by |override_param_name|. If |override_param_name| is // not set, defaults to |default_extensions|. bool ContainsExtension(const base::FeatureParam<std::string>& extensions, const base::FeatureParam<bool>& is_allowlist, const std::string& download_extension) { auto extensions_str = extensions.Get(); std::vector<base::StringPiece> listed_extensions = base::SplitStringPiece( extensions_str, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); for (const auto& unsafe_extension : listed_extensions) { DCHECK_EQ(base::ToLowerASCII(unsafe_extension), unsafe_extension); if (base::LowerCaseEqualsASCII(download_extension, unsafe_extension)) { return !is_allowlist.Get(); // aka true when it's a blocklist. } } return is_allowlist.Get(); // aka false when it's a blocklist. } // Just print a descriptive message to the console about the blocked download. // |is_blocked| indicates whether this download will be blocked now. void PrintConsoleMessage(const MixedContentDownloadData& data, bool is_blocked) { content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(data.item_); if (!web_contents) { return; } web_contents->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, base::StringPrintf( "Mixed Content: The site at '%s' was loaded over a secure " "connection, but the file at '%s' was %s an insecure " "connection. This file should be served over HTTPS. " "This download %s. See " "https://blog.chromium.org/2020/02/" "protecting-users-from-insecure.html" " for more details.", data.initiator_->GetURL().spec().c_str(), data.item_->GetURL().spec().c_str(), (data.is_redirect_chain_secure_ ? "loaded over" : "redirected through"), (is_blocked ? "has been blocked" : "will be blocked in future versions of Chrome"))); } bool IsDownloadPermittedByContentSettings( Profile* profile, const absl::optional<url::Origin>& initiator) { // TODO(crbug.com/1048957): Checking content settings crashes unit tests on // Android. It shouldn't. #if !defined(OS_ANDROID) ContentSettingsForOneType settings; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(profile); host_content_settings_map->GetSettingsForOneType( ContentSettingsType::MIXEDSCRIPT, &settings); // When there's only one rule, it's the default wildcard rule. if (settings.size() == 1) { DCHECK(settings[0].primary_pattern == ContentSettingsPattern::Wildcard()); DCHECK(settings[0].secondary_pattern == ContentSettingsPattern::Wildcard()); return settings[0].GetContentSetting() == CONTENT_SETTING_ALLOW; } for (const auto& setting : settings) { if (setting.primary_pattern.Matches(initiator->GetURL())) { return setting.GetContentSetting() == CONTENT_SETTING_ALLOW; } } NOTREACHED(); #endif return false; } } // namespace MixedContentStatus GetMixedContentStatusForDownload( Profile* profile, const base::FilePath& path, const download::DownloadItem* item) { MixedContentDownloadData data(path, item); if (!data.is_mixed_content_) { return MixedContentStatus::SAFE; } // As of M81, print a console message even if no other blocking is enabled. if (!base::FeatureList::IsEnabled(features::kTreatUnsafeDownloadsAsActive)) { PrintConsoleMessage(data, false); return MixedContentStatus::SAFE; } if (IsDownloadPermittedByContentSettings(profile, data.initiator_)) { PrintConsoleMessage(data, false); return MixedContentStatus::SAFE; } if (ContainsExtension(kSilentBlockExtensionList, kTreatSilentBlockListAsAllowlist, data.extension_)) { PrintConsoleMessage(data, true); // Only permit silent blocking when not initiated by an explicit user // action. Otherwise, fall back to visible blocking. auto download_source = data.item_->GetDownloadSource(); if (download_source == DownloadSource::CONTEXT_MENU || download_source == DownloadSource::WEB_CONTENTS_API) { return MixedContentStatus::BLOCK; } return MixedContentStatus::SILENT_BLOCK; } if (ContainsExtension(kBlockExtensionList, kTreatBlockListAsAllowlist, data.extension_)) { PrintConsoleMessage(data, true); return MixedContentStatus::BLOCK; } if (ContainsExtension(kWarnExtensionList, kTreatWarnListAsAllowlist, data.extension_)) { PrintConsoleMessage(data, true); return MixedContentStatus::WARN; } // The download is still mixed content, but we're not blocking it yet. PrintConsoleMessage(data, false); return MixedContentStatus::SAFE; }
/* * Copyright 2010-2017 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/medialive/model/HlsMediaStoreSettings.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MediaLive { namespace Model { HlsMediaStoreSettings::HlsMediaStoreSettings() : m_connectionRetryInterval(0), m_connectionRetryIntervalHasBeenSet(false), m_filecacheDuration(0), m_filecacheDurationHasBeenSet(false), m_mediaStoreStorageClass(HlsMediaStoreStorageClass::NOT_SET), m_mediaStoreStorageClassHasBeenSet(false), m_numRetries(0), m_numRetriesHasBeenSet(false), m_restartDelay(0), m_restartDelayHasBeenSet(false) { } HlsMediaStoreSettings::HlsMediaStoreSettings(JsonView jsonValue) : m_connectionRetryInterval(0), m_connectionRetryIntervalHasBeenSet(false), m_filecacheDuration(0), m_filecacheDurationHasBeenSet(false), m_mediaStoreStorageClass(HlsMediaStoreStorageClass::NOT_SET), m_mediaStoreStorageClassHasBeenSet(false), m_numRetries(0), m_numRetriesHasBeenSet(false), m_restartDelay(0), m_restartDelayHasBeenSet(false) { *this = jsonValue; } HlsMediaStoreSettings& HlsMediaStoreSettings::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("connectionRetryInterval")) { m_connectionRetryInterval = jsonValue.GetInteger("connectionRetryInterval"); m_connectionRetryIntervalHasBeenSet = true; } if(jsonValue.ValueExists("filecacheDuration")) { m_filecacheDuration = jsonValue.GetInteger("filecacheDuration"); m_filecacheDurationHasBeenSet = true; } if(jsonValue.ValueExists("mediaStoreStorageClass")) { m_mediaStoreStorageClass = HlsMediaStoreStorageClassMapper::GetHlsMediaStoreStorageClassForName(jsonValue.GetString("mediaStoreStorageClass")); m_mediaStoreStorageClassHasBeenSet = true; } if(jsonValue.ValueExists("numRetries")) { m_numRetries = jsonValue.GetInteger("numRetries"); m_numRetriesHasBeenSet = true; } if(jsonValue.ValueExists("restartDelay")) { m_restartDelay = jsonValue.GetInteger("restartDelay"); m_restartDelayHasBeenSet = true; } return *this; } JsonValue HlsMediaStoreSettings::Jsonize() const { JsonValue payload; if(m_connectionRetryIntervalHasBeenSet) { payload.WithInteger("connectionRetryInterval", m_connectionRetryInterval); } if(m_filecacheDurationHasBeenSet) { payload.WithInteger("filecacheDuration", m_filecacheDuration); } if(m_mediaStoreStorageClassHasBeenSet) { payload.WithString("mediaStoreStorageClass", HlsMediaStoreStorageClassMapper::GetNameForHlsMediaStoreStorageClass(m_mediaStoreStorageClass)); } if(m_numRetriesHasBeenSet) { payload.WithInteger("numRetries", m_numRetries); } if(m_restartDelayHasBeenSet) { payload.WithInteger("restartDelay", m_restartDelay); } return payload; } } // namespace Model } // namespace MediaLive } // namespace Aws
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Garmin Canada Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2021 Garmin Canada Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 21.47Release // Tag = production/akw/21.47.00-0-geec27411 //////////////////////////////////////////////////////////////////////////////// #if !defined(FIT_BUFFERED_RECORD_MESG_BROADCASTER_HPP) #define FIT_BUFFERED_RECORD_MESG_BROADCASTER_HPP #include <vector> #include "fit_buffered_record_mesg_listener.hpp" #include "fit_buffered_record_mesg.hpp" #include "fit_record_mesg_listener.hpp" namespace fit { class BufferedRecordMesgBroadcaster : public RecordMesgListener { public: BufferedRecordMesgBroadcaster(void); void AddListener(BufferedRecordMesgListener& mesgListener); void RemoveListener(BufferedRecordMesgListener& mesgListener); void OnMesg(RecordMesg& mesg); private: BufferedRecordMesg bufferedRecordMesg; std::vector<BufferedRecordMesgListener*> listeners; }; } // namespace fit #endif // !defined(FIT_BUFFERED_RECORD_MESG_BROADCASTER_HPP)
// Copyright 2020 Novo Yakov xaxaxaxa232@mail.ru #ifndef INCLUDE_HEADER_HPP_ #define INCLUDE_HEADER_HPP_ #include <iostream> #include <boost/filesystem.hpp> #include <sstream> #include <map> #include <utility> using std::string; using std::vector; using std::ostream; using std::cout; using std::stringstream; using std::make_pair; using std::find_if; using std::runtime_error; class Broker { private: class Account { private: std::string lastDate; size_t fileNum{}; public: inline static void setDate(Account& account, const std::string& date) { account.fileNum++; if (atoi(date.c_str()) > atoi(account.lastDate.c_str())) { account.lastDate = date; } } Account() = default; explicit Account(std::string date) : lastDate(std::move(date)), fileNum(0){}; [[nodiscard]] size_t getFileNum() const { return fileNum; } [[nodiscard]] std::string getLastDate() const { return lastDate; } }; std::map<std::string, Account> accounts; std::string name; public: static Broker InspectSingleBroker(const boost::filesystem::path& p); explicit Broker(std::string n) : name(std::move(n)) {} friend std::ostream& operator<<(std::ostream& os, const std::vector<Broker>& brokers); static std::vector<Broker> Inspect(const boost::filesystem::path& p, std::ostream& os); inline static bool isRightFile(const boost::filesystem::path& fileName); }; inline bool is_separator(char c) { return c == '_'; } inline bool not_separator(char c) { return !is_separator(c); } #endif // INCLUDE_HEADER_HPP_
// Copyright 2015 the V8 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. #include "test/unittests/interpreter/interpreter-assembler-unittest.h" #include "src/code-factory.h" #include "src/compiler/graph.h" #include "src/compiler/node.h" #include "src/interface-descriptors.h" #include "src/isolate.h" #include "test/unittests/compiler/compiler-test-utils.h" #include "test/unittests/compiler/node-test-utils.h" using ::testing::_; namespace v8 { namespace internal { using namespace compiler; namespace interpreter { const interpreter::Bytecode kBytecodes[] = { #define DEFINE_BYTECODE(Name, ...) interpreter::Bytecode::k##Name, BYTECODE_LIST(DEFINE_BYTECODE) #undef DEFINE_BYTECODE }; Matcher<Node*> IsIntPtrConstant(const intptr_t value) { return kPointerSize == 8 ? IsInt64Constant(static_cast<int64_t>(value)) : IsInt32Constant(static_cast<int32_t>(value)); } Matcher<Node*> IsIntPtrAdd(const Matcher<Node*>& lhs_matcher, const Matcher<Node*>& rhs_matcher) { return kPointerSize == 8 ? IsInt64Add(lhs_matcher, rhs_matcher) : IsInt32Add(lhs_matcher, rhs_matcher); } Matcher<Node*> IsIntPtrSub(const Matcher<Node*>& lhs_matcher, const Matcher<Node*>& rhs_matcher) { return kPointerSize == 8 ? IsInt64Sub(lhs_matcher, rhs_matcher) : IsInt32Sub(lhs_matcher, rhs_matcher); } Matcher<Node*> IsWordShl(const Matcher<Node*>& lhs_matcher, const Matcher<Node*>& rhs_matcher) { return kPointerSize == 8 ? IsWord64Shl(lhs_matcher, rhs_matcher) : IsWord32Shl(lhs_matcher, rhs_matcher); } Matcher<Node*> IsWordSar(const Matcher<Node*>& lhs_matcher, const Matcher<Node*>& rhs_matcher) { return kPointerSize == 8 ? IsWord64Sar(lhs_matcher, rhs_matcher) : IsWord32Sar(lhs_matcher, rhs_matcher); } Matcher<Node*> IsWordOr(const Matcher<Node*>& lhs_matcher, const Matcher<Node*>& rhs_matcher) { return kPointerSize == 8 ? IsWord64Or(lhs_matcher, rhs_matcher) : IsWord32Or(lhs_matcher, rhs_matcher); } InterpreterAssemblerTest::InterpreterAssemblerForTest:: ~InterpreterAssemblerForTest() { // Tests don't necessarily read and write accumulator but // InterpreterAssembler checks accumulator uses. if (Bytecodes::ReadsAccumulator(bytecode())) { GetAccumulator(); } if (Bytecodes::WritesAccumulator(bytecode())) { SetAccumulator(nullptr); } } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsLoad( const Matcher<LoadRepresentation>& rep_matcher, const Matcher<Node*>& base_matcher, const Matcher<Node*>& index_matcher) { return ::i::compiler::IsLoad(rep_matcher, base_matcher, index_matcher, _, _); } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsStore( const Matcher<StoreRepresentation>& rep_matcher, const Matcher<Node*>& base_matcher, const Matcher<Node*>& index_matcher, const Matcher<Node*>& value_matcher) { return ::i::compiler::IsStore(rep_matcher, base_matcher, index_matcher, value_matcher, _, _); } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsUnsignedByteOperand( int offset) { return IsLoad( MachineType::Uint8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd(IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset))); } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsSignedByteOperand( int offset) { Matcher<Node*> load_matcher = IsLoad( MachineType::Int8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd(IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset))); if (kPointerSize == 8) { load_matcher = IsChangeInt32ToInt64(load_matcher); } return load_matcher; } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsUnsignedShortOperand( int offset) { if (TargetSupportsUnalignedAccess()) { return IsLoad( MachineType::Uint16(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd(IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset))); } else { #if V8_TARGET_LITTLE_ENDIAN const int kStep = -1; const int kMsbOffset = 1; #elif V8_TARGET_BIG_ENDIAN const int kStep = 1; const int kMsbOffset = 0; #else #error "Unknown Architecture" #endif Matcher<Node*> bytes[2]; for (int i = 0; i < static_cast<int>(arraysize(bytes)); i++) { bytes[i] = IsLoad( MachineType::Uint8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd( IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset + kMsbOffset + kStep * i))); } return IsWord32Or(IsWord32Shl(bytes[0], IsInt32Constant(kBitsPerByte)), bytes[1]); } } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsSignedShortOperand( int offset) { Matcher<Node*> load_matcher; if (TargetSupportsUnalignedAccess()) { load_matcher = IsLoad( MachineType::Int16(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd(IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset))); } else { #if V8_TARGET_LITTLE_ENDIAN const int kStep = -1; const int kMsbOffset = 1; #elif V8_TARGET_BIG_ENDIAN const int kStep = 1; const int kMsbOffset = 0; #else #error "Unknown Architecture" #endif Matcher<Node*> bytes[2]; for (int i = 0; i < static_cast<int>(arraysize(bytes)); i++) { bytes[i] = IsLoad( (i == 0) ? MachineType::Int8() : MachineType::Uint8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd( IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset + kMsbOffset + kStep * i))); } load_matcher = IsWord32Or( IsWord32Shl(bytes[0], IsInt32Constant(kBitsPerByte)), bytes[1]); } if (kPointerSize == 8) { load_matcher = IsChangeInt32ToInt64(load_matcher); } return load_matcher; } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsUnsignedQuadOperand( int offset) { if (TargetSupportsUnalignedAccess()) { return IsLoad( MachineType::Uint32(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd(IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset))); } else { #if V8_TARGET_LITTLE_ENDIAN const int kStep = -1; const int kMsbOffset = 3; #elif V8_TARGET_BIG_ENDIAN const int kStep = 1; const int kMsbOffset = 0; #else #error "Unknown Architecture" #endif Matcher<Node*> bytes[4]; for (int i = 0; i < static_cast<int>(arraysize(bytes)); i++) { bytes[i] = IsLoad( MachineType::Uint8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd( IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset + kMsbOffset + kStep * i))); } return IsWord32Or( IsWord32Shl(bytes[0], IsInt32Constant(3 * kBitsPerByte)), IsWord32Or( IsWord32Shl(bytes[1], IsInt32Constant(2 * kBitsPerByte)), IsWord32Or(IsWord32Shl(bytes[2], IsInt32Constant(1 * kBitsPerByte)), bytes[3]))); } } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsSignedQuadOperand( int offset) { Matcher<Node*> load_matcher; if (TargetSupportsUnalignedAccess()) { load_matcher = IsLoad( MachineType::Int32(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd(IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset))); } else { #if V8_TARGET_LITTLE_ENDIAN const int kStep = -1; int kMsbOffset = 3; #elif V8_TARGET_BIG_ENDIAN const int kStep = 1; int kMsbOffset = 0; #else #error "Unknown Architecture" #endif Matcher<Node*> bytes[4]; for (int i = 0; i < static_cast<int>(arraysize(bytes)); i++) { bytes[i] = IsLoad( (i == 0) ? MachineType::Int8() : MachineType::Uint8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrAdd( IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(offset + kMsbOffset + kStep * i))); } load_matcher = IsWord32Or( IsWord32Shl(bytes[0], IsInt32Constant(3 * kBitsPerByte)), IsWord32Or( IsWord32Shl(bytes[1], IsInt32Constant(2 * kBitsPerByte)), IsWord32Or(IsWord32Shl(bytes[2], IsInt32Constant(1 * kBitsPerByte)), bytes[3]))); } if (kPointerSize == 8) { load_matcher = IsChangeInt32ToInt64(load_matcher); } return load_matcher; } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsSignedOperand( int offset, OperandSize operand_size) { switch (operand_size) { case OperandSize::kByte: return IsSignedByteOperand(offset); case OperandSize::kShort: return IsSignedShortOperand(offset); case OperandSize::kQuad: return IsSignedQuadOperand(offset); case OperandSize::kNone: UNREACHABLE(); } return nullptr; } Matcher<Node*> InterpreterAssemblerTest::InterpreterAssemblerForTest::IsUnsignedOperand( int offset, OperandSize operand_size) { switch (operand_size) { case OperandSize::kByte: return IsUnsignedByteOperand(offset); case OperandSize::kShort: return IsUnsignedShortOperand(offset); case OperandSize::kQuad: return IsUnsignedQuadOperand(offset); case OperandSize::kNone: UNREACHABLE(); } return nullptr; } TARGET_TEST_F(InterpreterAssemblerTest, Dispatch) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* tail_call_node = m.Dispatch(); OperandScale operand_scale = OperandScale::kSingle; Matcher<Node*> next_bytecode_offset_matcher = IsIntPtrAdd(IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant( interpreter::Bytecodes::Size(bytecode, operand_scale))); Matcher<Node*> target_bytecode_matcher = m.IsLoad(MachineType::Uint8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), next_bytecode_offset_matcher); if (kPointerSize == 8) { target_bytecode_matcher = IsChangeUint32ToUint64(target_bytecode_matcher); } Matcher<Node*> code_target_matcher = m.IsLoad( MachineType::Pointer(), IsParameter(InterpreterDispatchDescriptor::kDispatchTable), IsWordShl(target_bytecode_matcher, IsIntPtrConstant(kPointerSizeLog2))); if (interpreter::Bytecodes::IsStarLookahead(bytecode, operand_scale)) { Matcher<Node*> after_lookahead_offset = IsIntPtrAdd(next_bytecode_offset_matcher, IsIntPtrConstant(interpreter::Bytecodes::Size( Bytecode::kStar, operand_scale))); next_bytecode_offset_matcher = IsPhi(MachineType::PointerRepresentation(), next_bytecode_offset_matcher, after_lookahead_offset, _); Matcher<Node*> after_lookahead_bytecode = m.IsLoad(MachineType::Uint8(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), after_lookahead_offset); if (kPointerSize == 8) { after_lookahead_bytecode = IsChangeUint32ToUint64(after_lookahead_bytecode); } target_bytecode_matcher = IsPhi(MachineRepresentation::kWord8, target_bytecode_matcher, after_lookahead_bytecode, _); code_target_matcher = m.IsLoad(MachineType::Pointer(), IsParameter(InterpreterDispatchDescriptor::kDispatchTable), IsWordShl(target_bytecode_matcher, IsIntPtrConstant(kPointerSizeLog2))); } EXPECT_THAT( tail_call_node, IsTailCall(_, code_target_matcher, IsParameter(InterpreterDispatchDescriptor::kAccumulator), next_bytecode_offset_matcher, IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsParameter(InterpreterDispatchDescriptor::kDispatchTable), _, _)); } } TARGET_TEST_F(InterpreterAssemblerTest, Jump) { // If debug code is enabled we emit extra code in Jump. if (FLAG_debug_code) return; int jump_offsets[] = {-9710, -77, 0, +3, +97109}; TRACED_FOREACH(int, jump_offset, jump_offsets) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { if (!interpreter::Bytecodes::IsJump(bytecode)) return; InterpreterAssemblerForTest m(this, bytecode); Node* tail_call_node = m.Jump(m.IntPtrConstant(jump_offset)); Matcher<Node*> next_bytecode_offset_matcher = IsIntPtrAdd( IsParameter(InterpreterDispatchDescriptor::kBytecodeOffset), IsIntPtrConstant(jump_offset)); Matcher<Node*> target_bytecode_matcher = m.IsLoad(MachineType::Uint8(), _, next_bytecode_offset_matcher); if (kPointerSize == 8) { target_bytecode_matcher = IsChangeUint32ToUint64(target_bytecode_matcher); } Matcher<Node*> code_target_matcher = m.IsLoad(MachineType::Pointer(), IsParameter(InterpreterDispatchDescriptor::kDispatchTable), IsWordShl(target_bytecode_matcher, IsIntPtrConstant(kPointerSizeLog2))); EXPECT_THAT( tail_call_node, IsTailCall(_, code_target_matcher, IsParameter(InterpreterDispatchDescriptor::kAccumulator), next_bytecode_offset_matcher, _, IsParameter(InterpreterDispatchDescriptor::kDispatchTable), _, _)); } } } TARGET_TEST_F(InterpreterAssemblerTest, BytecodeOperand) { static const OperandScale kOperandScales[] = { OperandScale::kSingle, OperandScale::kDouble, OperandScale::kQuadruple}; TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { TRACED_FOREACH(interpreter::OperandScale, operand_scale, kOperandScales) { InterpreterAssemblerForTest m(this, bytecode, operand_scale); int number_of_operands = interpreter::Bytecodes::NumberOfOperands(bytecode); for (int i = 0; i < number_of_operands; i++) { int offset = interpreter::Bytecodes::GetOperandOffset(bytecode, i, operand_scale); OperandType operand_type = interpreter::Bytecodes::GetOperandType(bytecode, i); OperandSize operand_size = Bytecodes::SizeOfOperand(operand_type, operand_scale); switch (interpreter::Bytecodes::GetOperandType(bytecode, i)) { case interpreter::OperandType::kRegCount: EXPECT_THAT(m.BytecodeOperandCount(i), m.IsUnsignedOperand(offset, operand_size)); break; case interpreter::OperandType::kFlag8: EXPECT_THAT(m.BytecodeOperandFlag(i), m.IsUnsignedOperand(offset, operand_size)); break; case interpreter::OperandType::kIdx: EXPECT_THAT(m.BytecodeOperandIdx(i), m.IsUnsignedOperand(offset, operand_size)); break; case interpreter::OperandType::kImm: { EXPECT_THAT(m.BytecodeOperandImm(i), m.IsSignedOperand(offset, operand_size)); break; } case interpreter::OperandType::kMaybeReg: case interpreter::OperandType::kReg: case interpreter::OperandType::kRegOut: case interpreter::OperandType::kRegOutPair: case interpreter::OperandType::kRegOutTriple: case interpreter::OperandType::kRegPair: EXPECT_THAT(m.BytecodeOperandReg(i), m.IsSignedOperand(offset, operand_size)); break; case interpreter::OperandType::kRuntimeId: EXPECT_THAT(m.BytecodeOperandRuntimeId(i), m.IsUnsignedOperand(offset, operand_size)); break; case interpreter::OperandType::kIntrinsicId: EXPECT_THAT(m.BytecodeOperandIntrinsicId(i), m.IsUnsignedOperand(offset, operand_size)); break; case interpreter::OperandType::kNone: UNREACHABLE(); break; } } } } } TARGET_TEST_F(InterpreterAssemblerTest, GetSetAccumulator) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { if (!interpreter::Bytecodes::ReadsAccumulator(bytecode) || !interpreter::Bytecodes::WritesAccumulator(bytecode)) { continue; } InterpreterAssemblerForTest m(this, bytecode); // Should be incoming accumulator if not set. EXPECT_THAT(m.GetAccumulator(), IsParameter(InterpreterDispatchDescriptor::kAccumulator)); // Should be set by SetAccumulator. Node* accumulator_value_1 = m.Int32Constant(0xdeadbeef); m.SetAccumulator(accumulator_value_1); EXPECT_THAT(m.GetAccumulator(), accumulator_value_1); Node* accumulator_value_2 = m.Int32Constant(42); m.SetAccumulator(accumulator_value_2); EXPECT_THAT(m.GetAccumulator(), accumulator_value_2); // Should be passed to next bytecode handler on dispatch. Node* tail_call_node = m.Dispatch(); EXPECT_THAT(tail_call_node, IsTailCall(_, _, accumulator_value_2, _, _, _, _)); } } TARGET_TEST_F(InterpreterAssemblerTest, GetContext) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); EXPECT_THAT( m.GetContext(), m.IsLoad(MachineType::AnyTagged(), IsLoadParentFramePointer(), IsIntPtrConstant(Register::current_context().ToOperand() << kPointerSizeLog2))); } } TARGET_TEST_F(InterpreterAssemblerTest, RegisterLocation) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* reg_index_node = m.IntPtrConstant(44); Node* reg_location_node = m.RegisterLocation(reg_index_node); EXPECT_THAT(reg_location_node, IsIntPtrAdd(IsLoadParentFramePointer(), IsWordShl(reg_index_node, IsIntPtrConstant(kPointerSizeLog2)))); } } TARGET_TEST_F(InterpreterAssemblerTest, LoadRegister) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* reg_index_node = m.IntPtrConstant(44); Node* load_reg_node = m.LoadRegister(reg_index_node); EXPECT_THAT(load_reg_node, m.IsLoad(MachineType::AnyTagged(), IsLoadParentFramePointer(), IsWordShl(reg_index_node, IsIntPtrConstant(kPointerSizeLog2)))); } } TARGET_TEST_F(InterpreterAssemblerTest, StoreRegister) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* store_value = m.Int32Constant(0xdeadbeef); Node* reg_index_node = m.IntPtrConstant(44); Node* store_reg_node = m.StoreRegister(store_value, reg_index_node); EXPECT_THAT( store_reg_node, m.IsStore(StoreRepresentation(MachineRepresentation::kTagged, kNoWriteBarrier), IsLoadParentFramePointer(), IsWordShl(reg_index_node, IsIntPtrConstant(kPointerSizeLog2)), store_value)); } } TARGET_TEST_F(InterpreterAssemblerTest, SmiTag) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* value = m.Int32Constant(44); EXPECT_THAT(m.SmiTag(value), IsIntPtrConstant(static_cast<intptr_t>(44) << (kSmiShiftSize + kSmiTagSize))); EXPECT_THAT( m.SmiUntag(value), IsWordSar(value, IsIntPtrConstant(kSmiShiftSize + kSmiTagSize))); } } TARGET_TEST_F(InterpreterAssemblerTest, IntPtrAdd) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* a = m.Int32Constant(0); Node* b = m.Int32Constant(1); Node* add = m.IntPtrAdd(a, b); EXPECT_THAT(add, IsIntPtrAdd(a, b)); } } TARGET_TEST_F(InterpreterAssemblerTest, IntPtrSub) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* a = m.Int32Constant(0); Node* b = m.Int32Constant(1); Node* add = m.IntPtrSub(a, b); EXPECT_THAT(add, IsIntPtrSub(a, b)); } } TARGET_TEST_F(InterpreterAssemblerTest, WordShl) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* a = m.IntPtrConstant(0); Node* add = m.WordShl(a, 10); EXPECT_THAT(add, IsWordShl(a, IsIntPtrConstant(10))); } } TARGET_TEST_F(InterpreterAssemblerTest, LoadConstantPoolEntry) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* index = m.IntPtrConstant(2); Node* load_constant = m.LoadConstantPoolEntry(index); Matcher<Node*> constant_pool_matcher = m.IsLoad( MachineType::AnyTagged(), IsParameter(InterpreterDispatchDescriptor::kBytecodeArray), IsIntPtrConstant(BytecodeArray::kConstantPoolOffset - kHeapObjectTag)); EXPECT_THAT( load_constant, m.IsLoad(MachineType::AnyTagged(), constant_pool_matcher, IsIntPtrAdd( IsIntPtrConstant(FixedArray::kHeaderSize - kHeapObjectTag), IsWordShl(index, IsIntPtrConstant(kPointerSizeLog2))))); } } TARGET_TEST_F(InterpreterAssemblerTest, LoadObjectField) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* object = m.IntPtrConstant(0xdeadbeef); int offset = 16; Node* load_field = m.LoadObjectField(object, offset); EXPECT_THAT(load_field, m.IsLoad(MachineType::AnyTagged(), object, IsIntPtrConstant(offset - kHeapObjectTag))); } } TARGET_TEST_F(InterpreterAssemblerTest, LoadContextSlot) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* context = m.IntPtrConstant(1); Node* slot_index = m.IntPtrConstant(22); Node* load_context_slot = m.LoadContextSlot(context, slot_index); Matcher<Node*> offset = IsIntPtrAdd(IsWordShl(slot_index, IsIntPtrConstant(kPointerSizeLog2)), IsIntPtrConstant(Context::kHeaderSize - kHeapObjectTag)); EXPECT_THAT(load_context_slot, m.IsLoad(MachineType::AnyTagged(), context, offset)); } } TARGET_TEST_F(InterpreterAssemblerTest, StoreContextSlot) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* context = m.IntPtrConstant(1); Node* slot_index = m.IntPtrConstant(22); Node* value = m.SmiConstant(Smi::FromInt(100)); Node* store_context_slot = m.StoreContextSlot(context, slot_index, value); Matcher<Node*> offset = IsIntPtrAdd(IsWordShl(slot_index, IsIntPtrConstant(kPointerSizeLog2)), IsIntPtrConstant(Context::kHeaderSize - kHeapObjectTag)); EXPECT_THAT(store_context_slot, m.IsStore(StoreRepresentation(MachineRepresentation::kTagged, kFullWriteBarrier), context, offset, value)); } } TARGET_TEST_F(InterpreterAssemblerTest, CallRuntime2) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* arg1 = m.Int32Constant(2); Node* arg2 = m.Int32Constant(3); Node* context = m.Int32Constant(4); Node* call_runtime = m.CallRuntime(Runtime::kAdd, context, arg1, arg2); EXPECT_THAT(call_runtime, IsCall(_, _, arg1, arg2, _, IsInt32Constant(2), context, _, _)); } } TARGET_TEST_F(InterpreterAssemblerTest, CallRuntime) { const int kResultSizes[] = {1, 2}; TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { TRACED_FOREACH(int, result_size, kResultSizes) { InterpreterAssemblerForTest m(this, bytecode); Callable builtin = CodeFactory::InterpreterCEntry(isolate(), result_size); Node* function_id = m.Int32Constant(0); Node* first_arg = m.Int32Constant(1); Node* arg_count = m.Int32Constant(2); Node* context = m.Int32Constant(4); Matcher<Node*> function_table = IsExternalConstant( ExternalReference::runtime_function_table_address(isolate())); Matcher<Node*> function = IsIntPtrAdd( function_table, IsInt32Mul(function_id, IsInt32Constant(sizeof(Runtime::Function)))); Matcher<Node*> function_entry = m.IsLoad(MachineType::Pointer(), function, IsIntPtrConstant(offsetof(Runtime::Function, entry))); Node* call_runtime = m.CallRuntimeN(function_id, context, first_arg, arg_count, result_size); EXPECT_THAT(call_runtime, IsCall(_, IsHeapConstant(builtin.code()), arg_count, first_arg, function_entry, context, _, _)); } } } TARGET_TEST_F(InterpreterAssemblerTest, CallJS) { TailCallMode tail_call_modes[] = {TailCallMode::kDisallow, TailCallMode::kAllow}; TRACED_FOREACH(TailCallMode, tail_call_mode, tail_call_modes) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Callable builtin = CodeFactory::InterpreterPushArgsAndCall(isolate(), tail_call_mode); Node* function = m.Int32Constant(0); Node* first_arg = m.Int32Constant(1); Node* arg_count = m.Int32Constant(2); Node* context = m.Int32Constant(3); Node* call_js = m.CallJS(function, context, first_arg, arg_count, tail_call_mode); EXPECT_THAT(call_js, IsCall(_, IsHeapConstant(builtin.code()), arg_count, first_arg, function, context, _, _)); } } } TARGET_TEST_F(InterpreterAssemblerTest, LoadTypeFeedbackVector) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { InterpreterAssemblerForTest m(this, bytecode); Node* feedback_vector = m.LoadTypeFeedbackVector(); Matcher<Node*> load_function_matcher = m.IsLoad(MachineType::AnyTagged(), IsLoadParentFramePointer(), IsIntPtrConstant(Register::function_closure().ToOperand() << kPointerSizeLog2)); Matcher<Node*> load_literals_matcher = m.IsLoad( MachineType::AnyTagged(), load_function_matcher, IsIntPtrConstant(JSFunction::kLiteralsOffset - kHeapObjectTag)); EXPECT_THAT(feedback_vector, m.IsLoad(MachineType::AnyTagged(), load_literals_matcher, IsIntPtrConstant(LiteralsArray::kFeedbackVectorOffset - kHeapObjectTag))); } } } // namespace interpreter } // namespace internal } // namespace v8
#include "common.h" #include "lang/en.h" EWRAM_DATA uint32 keys; EWRAM_DATA RectMinMax viewport; vec3i gCameraViewPos; Matrix gMatrixStack[MAX_MATRICES]; Matrix* gMatrixPtr = gMatrixStack; EWRAM_DATA Sphere gSpheres[2][MAX_SPHERES]; const FloorData* gLastFloorData; FloorData gLastFloorSlant; EWRAM_DATA TargetInfo tinfo; EWRAM_DATA Settings gSettings; EWRAM_DATA SaveGame gSaveGame; EWRAM_DATA uint8 gSaveData[SAVEGAME_SIZE - sizeof(SaveGame)]; EWRAM_DATA int32 gCurTrack; EWRAM_DATA int32 gAnimTexFrame; int32 gLightAmbient; int32 gRandTable[MAX_RAND_TABLE]; int32 gCaustics[MAX_CAUSTICS]; int32 gCausticsFrame; EWRAM_DATA const char* const* STR = STR_EN; EWRAM_DATA ExtraInfoLara playersExtra[MAX_PLAYERS]; #if defined(__GBA__) #include "TRACKS_IMA.h" #include "TITLE_SCR.h" #include "TITLE_PKD.h" #include "GYM_PKD.h" #include "LEVEL1_PKD.h" #include "LEVEL2_PKD.h" #define LEVEL_INFO(name, title, track, secrets) { #name, name##_PKD, title, track, secrets } #else #define LEVEL_INFO(name, title, track, secrets) { #name, NULL, title, track, secrets } #endif #ifdef __3DO__ // TODO fix the title scren on 3DO EWRAM_DATA LevelID gLevelID = LVL_TR1_1; #else EWRAM_DATA LevelID gLevelID = LVL_TR1_TITLE; #endif const LevelInfo gLevelInfo[LVL_MAX] = { // TR1 LEVEL_INFO( TITLE , STR_EMPTY , TRACK_TR1_TITLE , 0 ), LEVEL_INFO( GYM , STR_TR1_GYM , TRACK_NONE , 0 ), LEVEL_INFO( LEVEL1 , STR_TR1_LEVEL1 , TRACK_TR1_CAVES , 3 ), LEVEL_INFO( LEVEL2 , STR_TR1_LEVEL2 , TRACK_TR1_CAVES , 3 ), //LEVEL_INFO( LEVEL3A , STR_TR1_LEVEL3A , TRACK_TR1_CAVES , 5 ), //LEVEL_INFO( LEVEL3B , STR_TR1_LEVEL3B , TRACK_TR1_CAVES , 3 ), //LEVEL_INFO( CUT1 , STR_EMPTY , TRACK_TR1_CUT_1 , 0 ), //LEVEL_INFO( LEVEL4 , STR_TR1_LEVEL4 , TRACK_TR1_WIND , 4 ), //LEVEL_INFO( LEVEL5 , STR_TR1_LEVEL5 , TRACK_TR1_WIND , 3 ), //LEVEL_INFO( LEVEL6 , STR_TR1_LEVEL6 , TRACK_TR1_WIND , 3 ), //LEVEL_INFO( LEVEL7A , STR_TR1_LEVEL7A , TRACK_TR1_CISTERN , 3 ), //LEVEL_INFO( LEVEL7B , STR_TR1_LEVEL7B , TRACK_TR1_CISTERN , 2 ), //LEVEL_INFO( CUT2 , STR_EMPTY , TRACK_TR1_CUT_2 , 0 ), //LEVEL_INFO( LEVEL8A , STR_TR1_LEVEL8A , TRACK_TR1_WIND , 3 ), //LEVEL_INFO( LEVEL8B , STR_TR1_LEVEL8B , TRACK_TR1_WIND , 3 ), //LEVEL_INFO( LEVEL8C , STR_TR1_LEVEL8C , TRACK_TR1_WIND , 1 ), //LEVEL_INFO( LEVEL10A , STR_TR1_LEVEL10A , TRACK_TR1_CISTERN , 3 ), //LEVEL_INFO( CUT3 , STR_EMPTY , TRACK_TR1_CUT_3 , 0 ), //LEVEL_INFO( LEVEL10B , STR_TR1_LEVEL10B , TRACK_TR1_PYRAMID , 3 ), //LEVEL_INFO( CUT4 , STR_EMPTY , TRACK_TR1_CUT_4 , 0 ), //LEVEL_INFO( LEVEL10C , STR_TR1_LEVEL10C , TRACK_TR1_PYRAMID , 3 ), //LEVEL_INFO( EGYPT , STR_TR1_EGYPT , TRACK_TR1_WIND , 3 ), //LEVEL_INFO( CAT , STR_TR1_CAT , TRACK_TR1_WIND , 4 ), //LEVEL_INFO( END , STR_TR1_END , TRACK_TR1_WIND , 2 ) }; #ifdef PROFILING uint32 gCounters[CNT_MAX]; #endif int32 gRandSeedLogic; int32 gRandSeedDraw; #define X_RAND(seed) (((seed = 0x3039 + seed * 0x41C64E6D) >> 10) & 0x7FFF); int32 rand_logic() { return X_RAND(gRandSeedLogic); } int32 rand_draw() { return X_RAND(gRandSeedDraw); } #ifdef USE_DIV_TABLE EWRAM_DATA divTableInt divTable[DIV_TABLE_SIZE] = { // must be at EWRAM start 0xFFFF, 0xFFFF, 0x8000, 0x5555, 0x4000, 0x3333, 0x2AAA, 0x2492, 0x2000, 0x1C71, 0x1999, 0x1745, 0x1555, 0x13B1, 0x1249, 0x1111, 0x1000, 0x0F0F, 0x0E38, 0x0D79, 0x0CCC, 0x0C30, 0x0BA2, 0x0B21, 0x0AAA, 0x0A3D, 0x09D8, 0x097B, 0x0924, 0x08D3, 0x0888, 0x0842, 0x0800, 0x07C1, 0x0787, 0x0750, 0x071C, 0x06EB, 0x06BC, 0x0690, 0x0666, 0x063E, 0x0618, 0x05F4, 0x05D1, 0x05B0, 0x0590, 0x0572, 0x0555, 0x0539, 0x051E, 0x0505, 0x04EC, 0x04D4, 0x04BD, 0x04A7, 0x0492, 0x047D, 0x0469, 0x0456, 0x0444, 0x0432, 0x0421, 0x0410, 0x0400, 0x03F0, 0x03E0, 0x03D2, 0x03C3, 0x03B5, 0x03A8, 0x039B, 0x038E, 0x0381, 0x0375, 0x0369, 0x035E, 0x0353, 0x0348, 0x033D, 0x0333, 0x0329, 0x031F, 0x0315, 0x030C, 0x0303, 0x02FA, 0x02F1, 0x02E8, 0x02E0, 0x02D8, 0x02D0, 0x02C8, 0x02C0, 0x02B9, 0x02B1, 0x02AA, 0x02A3, 0x029C, 0x0295, 0x028F, 0x0288, 0x0282, 0x027C, 0x0276, 0x0270, 0x026A, 0x0264, 0x025E, 0x0259, 0x0253, 0x024E, 0x0249, 0x0243, 0x023E, 0x0239, 0x0234, 0x0230, 0x022B, 0x0226, 0x0222, 0x021D, 0x0219, 0x0214, 0x0210, 0x020C, 0x0208, 0x0204, 0x0200, 0x01FC, 0x01F8, 0x01F4, 0x01F0, 0x01EC, 0x01E9, 0x01E5, 0x01E1, 0x01DE, 0x01DA, 0x01D7, 0x01D4, 0x01D0, 0x01CD, 0x01CA, 0x01C7, 0x01C3, 0x01C0, 0x01BD, 0x01BA, 0x01B7, 0x01B4, 0x01B2, 0x01AF, 0x01AC, 0x01A9, 0x01A6, 0x01A4, 0x01A1, 0x019E, 0x019C, 0x0199, 0x0197, 0x0194, 0x0192, 0x018F, 0x018D, 0x018A, 0x0188, 0x0186, 0x0183, 0x0181, 0x017F, 0x017D, 0x017A, 0x0178, 0x0176, 0x0174, 0x0172, 0x0170, 0x016E, 0x016C, 0x016A, 0x0168, 0x0166, 0x0164, 0x0162, 0x0160, 0x015E, 0x015C, 0x015A, 0x0158, 0x0157, 0x0155, 0x0153, 0x0151, 0x0150, 0x014E, 0x014C, 0x014A, 0x0149, 0x0147, 0x0146, 0x0144, 0x0142, 0x0141, 0x013F, 0x013E, 0x013C, 0x013B, 0x0139, 0x0138, 0x0136, 0x0135, 0x0133, 0x0132, 0x0130, 0x012F, 0x012E, 0x012C, 0x012B, 0x0129, 0x0128, 0x0127, 0x0125, 0x0124, 0x0123, 0x0121, 0x0120, 0x011F, 0x011E, 0x011C, 0x011B, 0x011A, 0x0119, 0x0118, 0x0116, 0x0115, 0x0114, 0x0113, 0x0112, 0x0111, 0x010F, 0x010E, 0x010D, 0x010C, 0x010B, 0x010A, 0x0109, 0x0108, 0x0107, 0x0106, 0x0105, 0x0104, 0x0103, 0x0102, 0x0101, 0x0100, 0x00FF, 0x00FE, 0x00FD, 0x00FC, 0x00FB, 0x00FA, 0x00F9, 0x00F8, 0x00F7, 0x00F6, 0x00F5, 0x00F4, 0x00F3, 0x00F2, 0x00F1, 0x00F0, 0x00F0, 0x00EF, 0x00EE, 0x00ED, 0x00EC, 0x00EB, 0x00EA, 0x00EA, 0x00E9, 0x00E8, 0x00E7, 0x00E6, 0x00E5, 0x00E5, 0x00E4, 0x00E3, 0x00E2, 0x00E1, 0x00E1, 0x00E0, 0x00DF, 0x00DE, 0x00DE, 0x00DD, 0x00DC, 0x00DB, 0x00DB, 0x00DA, 0x00D9, 0x00D9, 0x00D8, 0x00D7, 0x00D6, 0x00D6, 0x00D5, 0x00D4, 0x00D4, 0x00D3, 0x00D2, 0x00D2, 0x00D1, 0x00D0, 0x00D0, 0x00CF, 0x00CE, 0x00CE, 0x00CD, 0x00CC, 0x00CC, 0x00CB, 0x00CA, 0x00CA, 0x00C9, 0x00C9, 0x00C8, 0x00C7, 0x00C7, 0x00C6, 0x00C5, 0x00C5, 0x00C4, 0x00C4, 0x00C3, 0x00C3, 0x00C2, 0x00C1, 0x00C1, 0x00C0, 0x00C0, 0x00BF, 0x00BF, 0x00BE, 0x00BD, 0x00BD, 0x00BC, 0x00BC, 0x00BB, 0x00BB, 0x00BA, 0x00BA, 0x00B9, 0x00B9, 0x00B8, 0x00B8, 0x00B7, 0x00B7, 0x00B6, 0x00B6, 0x00B5, 0x00B5, 0x00B4, 0x00B4, 0x00B3, 0x00B3, 0x00B2, 0x00B2, 0x00B1, 0x00B1, 0x00B0, 0x00B0, 0x00AF, 0x00AF, 0x00AE, 0x00AE, 0x00AD, 0x00AD, 0x00AC, 0x00AC, 0x00AC, 0x00AB, 0x00AB, 0x00AA, 0x00AA, 0x00A9, 0x00A9, 0x00A8, 0x00A8, 0x00A8, 0x00A7, 0x00A7, 0x00A6, 0x00A6, 0x00A5, 0x00A5, 0x00A5, 0x00A4, 0x00A4, 0x00A3, 0x00A3, 0x00A3, 0x00A2, 0x00A2, 0x00A1, 0x00A1, 0x00A1, 0x00A0, 0x00A0, 0x009F, 0x009F, 0x009F, 0x009E, 0x009E, 0x009D, 0x009D, 0x009D, 0x009C, 0x009C, 0x009C, 0x009B, 0x009B, 0x009A, 0x009A, 0x009A, 0x0099, 0x0099, 0x0099, 0x0098, 0x0098, 0x0098, 0x0097, 0x0097, 0x0097, 0x0096, 0x0096, 0x0095, 0x0095, 0x0095, 0x0094, 0x0094, 0x0094, 0x0093, 0x0093, 0x0093, 0x0092, 0x0092, 0x0092, 0x0091, 0x0091, 0x0091, 0x0090, 0x0090, 0x0090, 0x0090, 0x008F, 0x008F, 0x008F, 0x008E, 0x008E, 0x008E, 0x008D, 0x008D, 0x008D, 0x008C, 0x008C, 0x008C, 0x008C, 0x008B, 0x008B, 0x008B, 0x008A, 0x008A, 0x008A, 0x0089, 0x0089, 0x0089, 0x0089, 0x0088, 0x0088, 0x0088, 0x0087, 0x0087, 0x0087, 0x0087, 0x0086, 0x0086, 0x0086, 0x0086, 0x0085, 0x0085, 0x0085, 0x0084, 0x0084, 0x0084, 0x0084, 0x0083, 0x0083, 0x0083, 0x0083, 0x0082, 0x0082, 0x0082, 0x0082, 0x0081, 0x0081, 0x0081, 0x0081, 0x0080, 0x0080, 0x0080, 0x0080, 0x007F, 0x007F, 0x007F, 0x007F, 0x007E, 0x007E, 0x007E, 0x007E, 0x007D, 0x007D, 0x007D, 0x007D, 0x007C, 0x007C, 0x007C, 0x007C, 0x007B, 0x007B, 0x007B, 0x007B, 0x007A, 0x007A, 0x007A, 0x007A, 0x007A, 0x0079, 0x0079, 0x0079, 0x0079, 0x0078, 0x0078, 0x0078, 0x0078, 0x0078, 0x0077, 0x0077, 0x0077, 0x0077, 0x0076, 0x0076, 0x0076, 0x0076, 0x0076, 0x0075, 0x0075, 0x0075, 0x0075, 0x0075, 0x0074, 0x0074, 0x0074, 0x0074, 0x0073, 0x0073, 0x0073, 0x0073, 0x0073, 0x0072, 0x0072, 0x0072, 0x0072, 0x0072, 0x0071, 0x0071, 0x0071, 0x0071, 0x0071, 0x0070, 0x0070, 0x0070, 0x0070, 0x0070, 0x0070, 0x006F, 0x006F, 0x006F, 0x006F, 0x006F, 0x006E, 0x006E, 0x006E, 0x006E, 0x006E, 0x006D, 0x006D, 0x006D, 0x006D, 0x006D, 0x006D, 0x006C, 0x006C, 0x006C, 0x006C, 0x006C, 0x006B, 0x006B, 0x006B, 0x006B, 0x006B, 0x006B, 0x006A, 0x006A, 0x006A, 0x006A, 0x006A, 0x006A, 0x0069, 0x0069, 0x0069, 0x0069, 0x0069, 0x0069, 0x0068, 0x0068, 0x0068, 0x0068, 0x0068, 0x0068, 0x0067, 0x0067, 0x0067, 0x0067, 0x0067, 0x0067, 0x0066, 0x0066, 0x0066, 0x0066, 0x0066, 0x0066, 0x0065, 0x0065, 0x0065, 0x0065, 0x0065, 0x0065, 0x0064, 0x0064, 0x0064, 0x0064, 0x0064, 0x0064, 0x0064, 0x0063, 0x0063, 0x0063, 0x0063, 0x0063, 0x0063, 0x0062, 0x0062, 0x0062, 0x0062, 0x0062, 0x0062, 0x0062, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0060, 0x0060, 0x0060, 0x0060, 0x0060, 0x0060, 0x0060, 0x005F, 0x005F, 0x005F, 0x005F, 0x005F, 0x005F, 0x005F, 0x005E, 0x005E, 0x005E, 0x005E, 0x005E, 0x005E, 0x005E, 0x005E, 0x005D, 0x005D, 0x005D, 0x005D, 0x005D, 0x005D, 0x005D, 0x005C, 0x005C, 0x005C, 0x005C, 0x005C, 0x005C, 0x005C, 0x005C, 0x005B, 0x005B, 0x005B, 0x005B, 0x005B, 0x005B, 0x005B, 0x005B, 0x005A, 0x005A, 0x005A, 0x005A, 0x005A, 0x005A, 0x005A, 0x005A, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0059, 0x0058, 0x0058, 0x0058, 0x0058, 0x0058, 0x0058, 0x0058, 0x0058, 0x0057, 0x0057, 0x0057, 0x0057, 0x0057, 0x0057, 0x0057, 0x0057, 0x0057, 0x0056, 0x0056, 0x0056, 0x0056, 0x0056, 0x0056, 0x0056, 0x0056, 0x0056, 0x0055, 0x0055, 0x0055, 0x0055, 0x0055, 0x0055, 0x0055, 0x0055, 0x0055, 0x0054, 0x0054, 0x0054, 0x0054, 0x0054, 0x0054, 0x0054, 0x0054, 0x0054, 0x0053, 0x0053, 0x0053, 0x0053, 0x0053, 0x0053, 0x0053, 0x0053, 0x0053, 0x0052, 0x0052, 0x0052, 0x0052, 0x0052, 0x0052, 0x0052, 0x0052, 0x0052, 0x0052, 0x0051, 0x0051, 0x0051, 0x0051, 0x0051, 0x0051, 0x0051, 0x0051, 0x0051, 0x0051, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x004F, 0x004F, 0x004F, 0x004F, 0x004F, 0x004F, 0x004F, 0x004F, 0x004F, 0x004F, 0x004E, 0x004E, 0x004E, 0x004E, 0x004E, 0x004E, 0x004E, 0x004E, 0x004E, 0x004E, 0x004E, 0x004D, 0x004D, 0x004D, 0x004D, 0x004D, 0x004D, 0x004D, 0x004D, 0x004D, 0x004D, 0x004D, 0x004C, 0x004C, 0x004C, 0x004C, 0x004C, 0x004C, 0x004C, 0x004C, 0x004C, 0x004C, 0x004C, 0x004B, 0x004B, 0x004B, 0x004B, 0x004B, 0x004B, 0x004B, 0x004B, 0x004B, 0x004B, 0x004B, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x004A, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0049, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0048, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0047, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0046, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0045, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0044, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0043, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0042, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040, 0x0040 }; #endif const uint32 gSinCosTable[4096] = { // ROM 0x00004000, 0x00194000, 0x00324000, 0x004B4000, 0x00654000, 0x007E4000, 0x00973FFF, 0x00B03FFF, 0x00C93FFF, 0x00E23FFE, 0x00FB3FFE, 0x01143FFE, 0x012E3FFD, 0x01473FFD, 0x01603FFC, 0x01793FFC, 0x01923FFB, 0x01AB3FFA, 0x01C43FFA, 0x01DD3FF9, 0x01F73FF8, 0x02103FF7, 0x02293FF7, 0x02423FF6, 0x025B3FF5, 0x02743FF4, 0x028D3FF3, 0x02A63FF2, 0x02C03FF1, 0x02D93FF0, 0x02F23FEF, 0x030B3FED, 0x03243FEC, 0x033D3FEB, 0x03563FEA, 0x036F3FE8, 0x03883FE7, 0x03A13FE6, 0x03BB3FE4, 0x03D43FE3, 0x03ED3FE1, 0x04063FE0, 0x041F3FDE, 0x04383FDC, 0x04513FDB, 0x046A3FD9, 0x04833FD7, 0x049C3FD5, 0x04B53FD4, 0x04CE3FD2, 0x04E73FD0, 0x05003FCE, 0x051A3FCC, 0x05333FCA, 0x054C3FC8, 0x05653FC6, 0x057E3FC4, 0x05973FC1, 0x05B03FBF, 0x05C93FBD, 0x05E23FBB, 0x05FB3FB8, 0x06143FB6, 0x062D3FB4, 0x06463FB1, 0x065F3FAF, 0x06783FAC, 0x06913FAA, 0x06AA3FA7, 0x06C33FA4, 0x06DC3FA2, 0x06F53F9F, 0x070E3F9C, 0x07273F99, 0x07403F97, 0x07593F94, 0x07723F91, 0x078B3F8E, 0x07A43F8B, 0x07BD3F88, 0x07D63F85, 0x07EF3F82, 0x08073F7F, 0x08203F7B, 0x08393F78, 0x08523F75, 0x086B3F72, 0x08843F6E, 0x089D3F6B, 0x08B63F68, 0x08CF3F64, 0x08E83F61, 0x09013F5D, 0x09193F5A, 0x09323F56, 0x094B3F52, 0x09643F4F, 0x097D3F4B, 0x09963F47, 0x09AF3F43, 0x09C73F40, 0x09E03F3C, 0x09F93F38, 0x0A123F34, 0x0A2B3F30, 0x0A443F2C, 0x0A5C3F28, 0x0A753F24, 0x0A8E3F20, 0x0AA73F1C, 0x0AC03F17, 0x0AD83F13, 0x0AF13F0F, 0x0B0A3F0A, 0x0B233F06, 0x0B3B3F02, 0x0B543EFD, 0x0B6D3EF9, 0x0B853EF4, 0x0B9E3EF0, 0x0BB73EEB, 0x0BD03EE7, 0x0BE83EE2, 0x0C013EDD, 0x0C1A3ED8, 0x0C323ED4, 0x0C4B3ECF, 0x0C643ECA, 0x0C7C3EC5, 0x0C953EC0, 0x0CAE3EBB, 0x0CC63EB6, 0x0CDF3EB1, 0x0CF83EAC, 0x0D103EA7, 0x0D293EA2, 0x0D413E9D, 0x0D5A3E98, 0x0D723E92, 0x0D8B3E8D, 0x0DA43E88, 0x0DBC3E82, 0x0DD53E7D, 0x0DED3E77, 0x0E063E72, 0x0E1E3E6C, 0x0E373E67, 0x0E4F3E61, 0x0E683E5C, 0x0E803E56, 0x0E993E50, 0x0EB13E4A, 0x0ECA3E45, 0x0EE23E3F, 0x0EFB3E39, 0x0F133E33, 0x0F2B3E2D, 0x0F443E27, 0x0F5C3E21, 0x0F753E1B, 0x0F8D3E15, 0x0FA53E0F, 0x0FBE3E09, 0x0FD63E03, 0x0FEE3DFC, 0x10073DF6, 0x101F3DF0, 0x10373DE9, 0x10503DE3, 0x10683DDD, 0x10803DD6, 0x10993DD0, 0x10B13DC9, 0x10C93DC2, 0x10E13DBC, 0x10FA3DB5, 0x11123DAF, 0x112A3DA8, 0x11423DA1, 0x115A3D9A, 0x11733D93, 0x118B3D8D, 0x11A33D86, 0x11BB3D7F, 0x11D33D78, 0x11EB3D71, 0x12043D6A, 0x121C3D63, 0x12343D5B, 0x124C3D54, 0x12643D4D, 0x127C3D46, 0x12943D3F, 0x12AC3D37, 0x12C43D30, 0x12DC3D28, 0x12F43D21, 0x130C3D1A, 0x13243D12, 0x133C3D0B, 0x13543D03, 0x136C3CFB, 0x13843CF4, 0x139C3CEC, 0x13B43CE4, 0x13CC3CDD, 0x13E43CD5, 0x13FB3CCD, 0x14133CC5, 0x142B3CBD, 0x14433CB5, 0x145B3CAD, 0x14733CA5, 0x148B3C9D, 0x14A23C95, 0x14BA3C8D, 0x14D23C85, 0x14EA3C7D, 0x15013C74, 0x15193C6C, 0x15313C64, 0x15493C5B, 0x15603C53, 0x15783C4B, 0x15903C42, 0x15A73C3A, 0x15BF3C31, 0x15D73C29, 0x15EE3C20, 0x16063C17, 0x161D3C0F, 0x16353C06, 0x164C3BFD, 0x16643BF5, 0x167C3BEC, 0x16933BE3, 0x16AB3BDA, 0x16C23BD1, 0x16DA3BC8, 0x16F13BBF, 0x17093BB6, 0x17203BAD, 0x17373BA4, 0x174F3B9B, 0x17663B92, 0x177E3B88, 0x17953B7F, 0x17AC3B76, 0x17C43B6D, 0x17DB3B63, 0x17F23B5A, 0x180A3B50, 0x18213B47, 0x18383B3E, 0x184F3B34, 0x18673B2A, 0x187E3B21, 0x18953B17, 0x18AC3B0E, 0x18C33B04, 0x18DB3AFA, 0x18F23AF0, 0x19093AE6, 0x19203ADD, 0x19373AD3, 0x194E3AC9, 0x19653ABF, 0x197C3AB5, 0x19933AAB, 0x19AA3AA1, 0x19C13A97, 0x19D83A8D, 0x19EF3A82, 0x1A063A78, 0x1A1D3A6E, 0x1A343A64, 0x1A4B3A59, 0x1A623A4F, 0x1A793A45, 0x1A903A3A, 0x1AA73A30, 0x1ABE3A25, 0x1AD43A1B, 0x1AEB3A10, 0x1B023A06, 0x1B1939FB, 0x1B3039F0, 0x1B4639E6, 0x1B5D39DB, 0x1B7439D0, 0x1B8A39C5, 0x1BA139BB, 0x1BB839B0, 0x1BCE39A5, 0x1BE5399A, 0x1BFC398F, 0x1C123984, 0x1C293979, 0x1C3F396E, 0x1C563963, 0x1C6C3958, 0x1C83394C, 0x1C993941, 0x1CB03936, 0x1CC6392B, 0x1CDD391F, 0x1CF33914, 0x1D0A3909, 0x1D2038FD, 0x1D3638F2, 0x1D4D38E6, 0x1D6338DB, 0x1D7938CF, 0x1D9038C3, 0x1DA638B8, 0x1DBC38AC, 0x1DD338A1, 0x1DE93895, 0x1DFF3889, 0x1E15387D, 0x1E2B3871, 0x1E423866, 0x1E58385A, 0x1E6E384E, 0x1E843842, 0x1E9A3836, 0x1EB0382A, 0x1EC6381E, 0x1EDC3812, 0x1EF23805, 0x1F0837F9, 0x1F1E37ED, 0x1F3437E1, 0x1F4A37D5, 0x1F6037C8, 0x1F7637BC, 0x1F8C37B0, 0x1FA237A3, 0x1FB73797, 0x1FCD378A, 0x1FE3377E, 0x1FF93771, 0x200F3765, 0x20243758, 0x203A374B, 0x2050373F, 0x20653732, 0x207B3725, 0x20913718, 0x20A6370C, 0x20BC36FF, 0x20D136F2, 0x20E736E5, 0x20FD36D8, 0x211236CB, 0x212836BE, 0x213D36B1, 0x215336A4, 0x21683697, 0x217D368A, 0x2193367D, 0x21A8366F, 0x21BE3662, 0x21D33655, 0x21E83648, 0x21FE363A, 0x2213362D, 0x22283620, 0x223D3612, 0x22533605, 0x226835F7, 0x227D35EA, 0x229235DC, 0x22A735CE, 0x22BC35C1, 0x22D235B3, 0x22E735A5, 0x22FC3598, 0x2311358A, 0x2326357C, 0x233B356E, 0x23503561, 0x23653553, 0x237A3545, 0x238E3537, 0x23A33529, 0x23B8351B, 0x23CD350D, 0x23E234FF, 0x23F734F1, 0x240B34E2, 0x242034D4, 0x243534C6, 0x244A34B8, 0x245E34AA, 0x2473349B, 0x2488348D, 0x249C347F, 0x24B13470, 0x24C53462, 0x24DA3453, 0x24EF3445, 0x25033436, 0x25183428, 0x252C3419, 0x2541340B, 0x255533FC, 0x256933ED, 0x257E33DF, 0x259233D0, 0x25A633C1, 0x25BB33B2, 0x25CF33A3, 0x25E33395, 0x25F83386, 0x260C3377, 0x26203368, 0x26343359, 0x2648334A, 0x265C333B, 0x2671332C, 0x2685331D, 0x2699330D, 0x26AD32FE, 0x26C132EF, 0x26D532E0, 0x26E932D0, 0x26FD32C1, 0x271132B2, 0x272432A3, 0x27383293, 0x274C3284, 0x27603274, 0x27743265, 0x27883255, 0x279B3246, 0x27AF3236, 0x27C33227, 0x27D63217, 0x27EA3207, 0x27FE31F8, 0x281131E8, 0x282531D8, 0x283831C8, 0x284C31B9, 0x286031A9, 0x28733199, 0x28863189, 0x289A3179, 0x28AD3169, 0x28C13159, 0x28D43149, 0x28E73139, 0x28FB3129, 0x290E3119, 0x29213109, 0x293530F9, 0x294830E8, 0x295B30D8, 0x296E30C8, 0x298130B8, 0x299430A7, 0x29A73097, 0x29BB3087, 0x29CE3076, 0x29E13066, 0x29F43055, 0x2A073045, 0x2A1A3034, 0x2A2C3024, 0x2A3F3013, 0x2A523002, 0x2A652FF2, 0x2A782FE1, 0x2A8B2FD0, 0x2A9D2FC0, 0x2AB02FAF, 0x2AC32F9E, 0x2AD62F8D, 0x2AE82F7D, 0x2AFB2F6C, 0x2B0D2F5B, 0x2B202F4A, 0x2B332F39, 0x2B452F28, 0x2B582F17, 0x2B6A2F06, 0x2B7D2EF5, 0x2B8F2EE4, 0x2BA12ED3, 0x2BB42EC2, 0x2BC62EB0, 0x2BD82E9F, 0x2BEB2E8E, 0x2BFD2E7D, 0x2C0F2E6B, 0x2C212E5A, 0x2C342E49, 0x2C462E37, 0x2C582E26, 0x2C6A2E15, 0x2C7C2E03, 0x2C8E2DF2, 0x2CA02DE0, 0x2CB22DCF, 0x2CC42DBD, 0x2CD62DAB, 0x2CE82D9A, 0x2CFA2D88, 0x2D0C2D76, 0x2D1E2D65, 0x2D2F2D53, 0x2D412D41, 0x2D532D2F, 0x2D652D1E, 0x2D762D0C, 0x2D882CFA, 0x2D9A2CE8, 0x2DAB2CD6, 0x2DBD2CC4, 0x2DCF2CB2, 0x2DE02CA0, 0x2DF22C8E, 0x2E032C7C, 0x2E152C6A, 0x2E262C58, 0x2E372C46, 0x2E492C34, 0x2E5A2C21, 0x2E6B2C0F, 0x2E7D2BFD, 0x2E8E2BEB, 0x2E9F2BD8, 0x2EB02BC6, 0x2EC22BB4, 0x2ED32BA1, 0x2EE42B8F, 0x2EF52B7D, 0x2F062B6A, 0x2F172B58, 0x2F282B45, 0x2F392B33, 0x2F4A2B20, 0x2F5B2B0D, 0x2F6C2AFB, 0x2F7D2AE8, 0x2F8D2AD6, 0x2F9E2AC3, 0x2FAF2AB0, 0x2FC02A9D, 0x2FD02A8B, 0x2FE12A78, 0x2FF22A65, 0x30022A52, 0x30132A3F, 0x30242A2C, 0x30342A1A, 0x30452A07, 0x305529F4, 0x306629E1, 0x307629CE, 0x308729BB, 0x309729A7, 0x30A72994, 0x30B82981, 0x30C8296E, 0x30D8295B, 0x30E82948, 0x30F92935, 0x31092921, 0x3119290E, 0x312928FB, 0x313928E7, 0x314928D4, 0x315928C1, 0x316928AD, 0x3179289A, 0x31892886, 0x31992873, 0x31A92860, 0x31B9284C, 0x31C82838, 0x31D82825, 0x31E82811, 0x31F827FE, 0x320727EA, 0x321727D6, 0x322727C3, 0x323627AF, 0x3246279B, 0x32552788, 0x32652774, 0x32742760, 0x3284274C, 0x32932738, 0x32A32724, 0x32B22711, 0x32C126FD, 0x32D026E9, 0x32E026D5, 0x32EF26C1, 0x32FE26AD, 0x330D2699, 0x331D2685, 0x332C2671, 0x333B265C, 0x334A2648, 0x33592634, 0x33682620, 0x3377260C, 0x338625F8, 0x339525E3, 0x33A325CF, 0x33B225BB, 0x33C125A6, 0x33D02592, 0x33DF257E, 0x33ED2569, 0x33FC2555, 0x340B2541, 0x3419252C, 0x34282518, 0x34362503, 0x344524EF, 0x345324DA, 0x346224C5, 0x347024B1, 0x347F249C, 0x348D2488, 0x349B2473, 0x34AA245E, 0x34B8244A, 0x34C62435, 0x34D42420, 0x34E2240B, 0x34F123F7, 0x34FF23E2, 0x350D23CD, 0x351B23B8, 0x352923A3, 0x3537238E, 0x3545237A, 0x35532365, 0x35612350, 0x356E233B, 0x357C2326, 0x358A2311, 0x359822FC, 0x35A522E7, 0x35B322D2, 0x35C122BC, 0x35CE22A7, 0x35DC2292, 0x35EA227D, 0x35F72268, 0x36052253, 0x3612223D, 0x36202228, 0x362D2213, 0x363A21FE, 0x364821E8, 0x365521D3, 0x366221BE, 0x366F21A8, 0x367D2193, 0x368A217D, 0x36972168, 0x36A42153, 0x36B1213D, 0x36BE2128, 0x36CB2112, 0x36D820FD, 0x36E520E7, 0x36F220D1, 0x36FF20BC, 0x370C20A6, 0x37182091, 0x3725207B, 0x37322065, 0x373F2050, 0x374B203A, 0x37582024, 0x3765200F, 0x37711FF9, 0x377E1FE3, 0x378A1FCD, 0x37971FB7, 0x37A31FA2, 0x37B01F8C, 0x37BC1F76, 0x37C81F60, 0x37D51F4A, 0x37E11F34, 0x37ED1F1E, 0x37F91F08, 0x38051EF2, 0x38121EDC, 0x381E1EC6, 0x382A1EB0, 0x38361E9A, 0x38421E84, 0x384E1E6E, 0x385A1E58, 0x38661E42, 0x38711E2B, 0x387D1E15, 0x38891DFF, 0x38951DE9, 0x38A11DD3, 0x38AC1DBC, 0x38B81DA6, 0x38C31D90, 0x38CF1D79, 0x38DB1D63, 0x38E61D4D, 0x38F21D36, 0x38FD1D20, 0x39091D0A, 0x39141CF3, 0x391F1CDD, 0x392B1CC6, 0x39361CB0, 0x39411C99, 0x394C1C83, 0x39581C6C, 0x39631C56, 0x396E1C3F, 0x39791C29, 0x39841C12, 0x398F1BFC, 0x399A1BE5, 0x39A51BCE, 0x39B01BB8, 0x39BB1BA1, 0x39C51B8A, 0x39D01B74, 0x39DB1B5D, 0x39E61B46, 0x39F01B30, 0x39FB1B19, 0x3A061B02, 0x3A101AEB, 0x3A1B1AD4, 0x3A251ABE, 0x3A301AA7, 0x3A3A1A90, 0x3A451A79, 0x3A4F1A62, 0x3A591A4B, 0x3A641A34, 0x3A6E1A1D, 0x3A781A06, 0x3A8219EF, 0x3A8D19D8, 0x3A9719C1, 0x3AA119AA, 0x3AAB1993, 0x3AB5197C, 0x3ABF1965, 0x3AC9194E, 0x3AD31937, 0x3ADD1920, 0x3AE61909, 0x3AF018F2, 0x3AFA18DB, 0x3B0418C3, 0x3B0E18AC, 0x3B171895, 0x3B21187E, 0x3B2A1867, 0x3B34184F, 0x3B3E1838, 0x3B471821, 0x3B50180A, 0x3B5A17F2, 0x3B6317DB, 0x3B6D17C4, 0x3B7617AC, 0x3B7F1795, 0x3B88177E, 0x3B921766, 0x3B9B174F, 0x3BA41737, 0x3BAD1720, 0x3BB61709, 0x3BBF16F1, 0x3BC816DA, 0x3BD116C2, 0x3BDA16AB, 0x3BE31693, 0x3BEC167C, 0x3BF51664, 0x3BFD164C, 0x3C061635, 0x3C0F161D, 0x3C171606, 0x3C2015EE, 0x3C2915D7, 0x3C3115BF, 0x3C3A15A7, 0x3C421590, 0x3C4B1578, 0x3C531560, 0x3C5B1549, 0x3C641531, 0x3C6C1519, 0x3C741501, 0x3C7D14EA, 0x3C8514D2, 0x3C8D14BA, 0x3C9514A2, 0x3C9D148B, 0x3CA51473, 0x3CAD145B, 0x3CB51443, 0x3CBD142B, 0x3CC51413, 0x3CCD13FB, 0x3CD513E4, 0x3CDD13CC, 0x3CE413B4, 0x3CEC139C, 0x3CF41384, 0x3CFB136C, 0x3D031354, 0x3D0B133C, 0x3D121324, 0x3D1A130C, 0x3D2112F4, 0x3D2812DC, 0x3D3012C4, 0x3D3712AC, 0x3D3F1294, 0x3D46127C, 0x3D4D1264, 0x3D54124C, 0x3D5B1234, 0x3D63121C, 0x3D6A1204, 0x3D7111EB, 0x3D7811D3, 0x3D7F11BB, 0x3D8611A3, 0x3D8D118B, 0x3D931173, 0x3D9A115A, 0x3DA11142, 0x3DA8112A, 0x3DAF1112, 0x3DB510FA, 0x3DBC10E1, 0x3DC210C9, 0x3DC910B1, 0x3DD01099, 0x3DD61080, 0x3DDD1068, 0x3DE31050, 0x3DE91037, 0x3DF0101F, 0x3DF61007, 0x3DFC0FEE, 0x3E030FD6, 0x3E090FBE, 0x3E0F0FA5, 0x3E150F8D, 0x3E1B0F75, 0x3E210F5C, 0x3E270F44, 0x3E2D0F2B, 0x3E330F13, 0x3E390EFB, 0x3E3F0EE2, 0x3E450ECA, 0x3E4A0EB1, 0x3E500E99, 0x3E560E80, 0x3E5C0E68, 0x3E610E4F, 0x3E670E37, 0x3E6C0E1E, 0x3E720E06, 0x3E770DED, 0x3E7D0DD5, 0x3E820DBC, 0x3E880DA4, 0x3E8D0D8B, 0x3E920D72, 0x3E980D5A, 0x3E9D0D41, 0x3EA20D29, 0x3EA70D10, 0x3EAC0CF8, 0x3EB10CDF, 0x3EB60CC6, 0x3EBB0CAE, 0x3EC00C95, 0x3EC50C7C, 0x3ECA0C64, 0x3ECF0C4B, 0x3ED40C32, 0x3ED80C1A, 0x3EDD0C01, 0x3EE20BE8, 0x3EE70BD0, 0x3EEB0BB7, 0x3EF00B9E, 0x3EF40B85, 0x3EF90B6D, 0x3EFD0B54, 0x3F020B3B, 0x3F060B23, 0x3F0A0B0A, 0x3F0F0AF1, 0x3F130AD8, 0x3F170AC0, 0x3F1C0AA7, 0x3F200A8E, 0x3F240A75, 0x3F280A5C, 0x3F2C0A44, 0x3F300A2B, 0x3F340A12, 0x3F3809F9, 0x3F3C09E0, 0x3F4009C7, 0x3F4309AF, 0x3F470996, 0x3F4B097D, 0x3F4F0964, 0x3F52094B, 0x3F560932, 0x3F5A0919, 0x3F5D0901, 0x3F6108E8, 0x3F6408CF, 0x3F6808B6, 0x3F6B089D, 0x3F6E0884, 0x3F72086B, 0x3F750852, 0x3F780839, 0x3F7B0820, 0x3F7F0807, 0x3F8207EF, 0x3F8507D6, 0x3F8807BD, 0x3F8B07A4, 0x3F8E078B, 0x3F910772, 0x3F940759, 0x3F970740, 0x3F990727, 0x3F9C070E, 0x3F9F06F5, 0x3FA206DC, 0x3FA406C3, 0x3FA706AA, 0x3FAA0691, 0x3FAC0678, 0x3FAF065F, 0x3FB10646, 0x3FB4062D, 0x3FB60614, 0x3FB805FB, 0x3FBB05E2, 0x3FBD05C9, 0x3FBF05B0, 0x3FC10597, 0x3FC4057E, 0x3FC60565, 0x3FC8054C, 0x3FCA0533, 0x3FCC051A, 0x3FCE0500, 0x3FD004E7, 0x3FD204CE, 0x3FD404B5, 0x3FD5049C, 0x3FD70483, 0x3FD9046A, 0x3FDB0451, 0x3FDC0438, 0x3FDE041F, 0x3FE00406, 0x3FE103ED, 0x3FE303D4, 0x3FE403BB, 0x3FE603A1, 0x3FE70388, 0x3FE8036F, 0x3FEA0356, 0x3FEB033D, 0x3FEC0324, 0x3FED030B, 0x3FEF02F2, 0x3FF002D9, 0x3FF102C0, 0x3FF202A6, 0x3FF3028D, 0x3FF40274, 0x3FF5025B, 0x3FF60242, 0x3FF70229, 0x3FF70210, 0x3FF801F7, 0x3FF901DD, 0x3FFA01C4, 0x3FFA01AB, 0x3FFB0192, 0x3FFC0179, 0x3FFC0160, 0x3FFD0147, 0x3FFD012E, 0x3FFE0114, 0x3FFE00FB, 0x3FFE00E2, 0x3FFF00C9, 0x3FFF00B0, 0x3FFF0097, 0x4000007E, 0x40000065, 0x4000004B, 0x40000032, 0x40000019, 0x40000000, 0x4000FFE7, 0x4000FFCE, 0x4000FFB5, 0x4000FF9B, 0x4000FF82, 0x3FFFFF69, 0x3FFFFF50, 0x3FFFFF37, 0x3FFEFF1E, 0x3FFEFF05, 0x3FFEFEEC, 0x3FFDFED2, 0x3FFDFEB9, 0x3FFCFEA0, 0x3FFCFE87, 0x3FFBFE6E, 0x3FFAFE55, 0x3FFAFE3C, 0x3FF9FE23, 0x3FF8FE09, 0x3FF7FDF0, 0x3FF7FDD7, 0x3FF6FDBE, 0x3FF5FDA5, 0x3FF4FD8C, 0x3FF3FD73, 0x3FF2FD5A, 0x3FF1FD40, 0x3FF0FD27, 0x3FEFFD0E, 0x3FEDFCF5, 0x3FECFCDC, 0x3FEBFCC3, 0x3FEAFCAA, 0x3FE8FC91, 0x3FE7FC78, 0x3FE6FC5F, 0x3FE4FC45, 0x3FE3FC2C, 0x3FE1FC13, 0x3FE0FBFA, 0x3FDEFBE1, 0x3FDCFBC8, 0x3FDBFBAF, 0x3FD9FB96, 0x3FD7FB7D, 0x3FD5FB64, 0x3FD4FB4B, 0x3FD2FB32, 0x3FD0FB19, 0x3FCEFB00, 0x3FCCFAE6, 0x3FCAFACD, 0x3FC8FAB4, 0x3FC6FA9B, 0x3FC4FA82, 0x3FC1FA69, 0x3FBFFA50, 0x3FBDFA37, 0x3FBBFA1E, 0x3FB8FA05, 0x3FB6F9EC, 0x3FB4F9D3, 0x3FB1F9BA, 0x3FAFF9A1, 0x3FACF988, 0x3FAAF96F, 0x3FA7F956, 0x3FA4F93D, 0x3FA2F924, 0x3F9FF90B, 0x3F9CF8F2, 0x3F99F8D9, 0x3F97F8C0, 0x3F94F8A7, 0x3F91F88E, 0x3F8EF875, 0x3F8BF85C, 0x3F88F843, 0x3F85F82A, 0x3F82F811, 0x3F7FF7F9, 0x3F7BF7E0, 0x3F78F7C7, 0x3F75F7AE, 0x3F72F795, 0x3F6EF77C, 0x3F6BF763, 0x3F68F74A, 0x3F64F731, 0x3F61F718, 0x3F5DF6FF, 0x3F5AF6E7, 0x3F56F6CE, 0x3F52F6B5, 0x3F4FF69C, 0x3F4BF683, 0x3F47F66A, 0x3F43F651, 0x3F40F639, 0x3F3CF620, 0x3F38F607, 0x3F34F5EE, 0x3F30F5D5, 0x3F2CF5BC, 0x3F28F5A4, 0x3F24F58B, 0x3F20F572, 0x3F1CF559, 0x3F17F540, 0x3F13F528, 0x3F0FF50F, 0x3F0AF4F6, 0x3F06F4DD, 0x3F02F4C5, 0x3EFDF4AC, 0x3EF9F493, 0x3EF4F47B, 0x3EF0F462, 0x3EEBF449, 0x3EE7F430, 0x3EE2F418, 0x3EDDF3FF, 0x3ED8F3E6, 0x3ED4F3CE, 0x3ECFF3B5, 0x3ECAF39C, 0x3EC5F384, 0x3EC0F36B, 0x3EBBF352, 0x3EB6F33A, 0x3EB1F321, 0x3EACF308, 0x3EA7F2F0, 0x3EA2F2D7, 0x3E9DF2BF, 0x3E98F2A6, 0x3E92F28E, 0x3E8DF275, 0x3E88F25C, 0x3E82F244, 0x3E7DF22B, 0x3E77F213, 0x3E72F1FA, 0x3E6CF1E2, 0x3E67F1C9, 0x3E61F1B1, 0x3E5CF198, 0x3E56F180, 0x3E50F167, 0x3E4AF14F, 0x3E45F136, 0x3E3FF11E, 0x3E39F105, 0x3E33F0ED, 0x3E2DF0D5, 0x3E27F0BC, 0x3E21F0A4, 0x3E1BF08B, 0x3E15F073, 0x3E0FF05B, 0x3E09F042, 0x3E03F02A, 0x3DFCF012, 0x3DF6EFF9, 0x3DF0EFE1, 0x3DE9EFC9, 0x3DE3EFB0, 0x3DDDEF98, 0x3DD6EF80, 0x3DD0EF67, 0x3DC9EF4F, 0x3DC2EF37, 0x3DBCEF1F, 0x3DB5EF06, 0x3DAFEEEE, 0x3DA8EED6, 0x3DA1EEBE, 0x3D9AEEA6, 0x3D93EE8D, 0x3D8DEE75, 0x3D86EE5D, 0x3D7FEE45, 0x3D78EE2D, 0x3D71EE15, 0x3D6AEDFC, 0x3D63EDE4, 0x3D5BEDCC, 0x3D54EDB4, 0x3D4DED9C, 0x3D46ED84, 0x3D3FED6C, 0x3D37ED54, 0x3D30ED3C, 0x3D28ED24, 0x3D21ED0C, 0x3D1AECF4, 0x3D12ECDC, 0x3D0BECC4, 0x3D03ECAC, 0x3CFBEC94, 0x3CF4EC7C, 0x3CECEC64, 0x3CE4EC4C, 0x3CDDEC34, 0x3CD5EC1C, 0x3CCDEC05, 0x3CC5EBED, 0x3CBDEBD5, 0x3CB5EBBD, 0x3CADEBA5, 0x3CA5EB8D, 0x3C9DEB75, 0x3C95EB5E, 0x3C8DEB46, 0x3C85EB2E, 0x3C7DEB16, 0x3C74EAFF, 0x3C6CEAE7, 0x3C64EACF, 0x3C5BEAB7, 0x3C53EAA0, 0x3C4BEA88, 0x3C42EA70, 0x3C3AEA59, 0x3C31EA41, 0x3C29EA29, 0x3C20EA12, 0x3C17E9FA, 0x3C0FE9E3, 0x3C06E9CB, 0x3BFDE9B4, 0x3BF5E99C, 0x3BECE984, 0x3BE3E96D, 0x3BDAE955, 0x3BD1E93E, 0x3BC8E926, 0x3BBFE90F, 0x3BB6E8F7, 0x3BADE8E0, 0x3BA4E8C9, 0x3B9BE8B1, 0x3B92E89A, 0x3B88E882, 0x3B7FE86B, 0x3B76E854, 0x3B6DE83C, 0x3B63E825, 0x3B5AE80E, 0x3B50E7F6, 0x3B47E7DF, 0x3B3EE7C8, 0x3B34E7B1, 0x3B2AE799, 0x3B21E782, 0x3B17E76B, 0x3B0EE754, 0x3B04E73D, 0x3AFAE725, 0x3AF0E70E, 0x3AE6E6F7, 0x3ADDE6E0, 0x3AD3E6C9, 0x3AC9E6B2, 0x3ABFE69B, 0x3AB5E684, 0x3AABE66D, 0x3AA1E656, 0x3A97E63F, 0x3A8DE628, 0x3A82E611, 0x3A78E5FA, 0x3A6EE5E3, 0x3A64E5CC, 0x3A59E5B5, 0x3A4FE59E, 0x3A45E587, 0x3A3AE570, 0x3A30E559, 0x3A25E542, 0x3A1BE52C, 0x3A10E515, 0x3A06E4FE, 0x39FBE4E7, 0x39F0E4D0, 0x39E6E4BA, 0x39DBE4A3, 0x39D0E48C, 0x39C5E476, 0x39BBE45F, 0x39B0E448, 0x39A5E432, 0x399AE41B, 0x398FE404, 0x3984E3EE, 0x3979E3D7, 0x396EE3C1, 0x3963E3AA, 0x3958E394, 0x394CE37D, 0x3941E367, 0x3936E350, 0x392BE33A, 0x391FE323, 0x3914E30D, 0x3909E2F6, 0x38FDE2E0, 0x38F2E2CA, 0x38E6E2B3, 0x38DBE29D, 0x38CFE287, 0x38C3E270, 0x38B8E25A, 0x38ACE244, 0x38A1E22D, 0x3895E217, 0x3889E201, 0x387DE1EB, 0x3871E1D5, 0x3866E1BE, 0x385AE1A8, 0x384EE192, 0x3842E17C, 0x3836E166, 0x382AE150, 0x381EE13A, 0x3812E124, 0x3805E10E, 0x37F9E0F8, 0x37EDE0E2, 0x37E1E0CC, 0x37D5E0B6, 0x37C8E0A0, 0x37BCE08A, 0x37B0E074, 0x37A3E05E, 0x3797E049, 0x378AE033, 0x377EE01D, 0x3771E007, 0x3765DFF1, 0x3758DFDC, 0x374BDFC6, 0x373FDFB0, 0x3732DF9B, 0x3725DF85, 0x3718DF6F, 0x370CDF5A, 0x36FFDF44, 0x36F2DF2F, 0x36E5DF19, 0x36D8DF03, 0x36CBDEEE, 0x36BEDED8, 0x36B1DEC3, 0x36A4DEAD, 0x3697DE98, 0x368ADE83, 0x367DDE6D, 0x366FDE58, 0x3662DE42, 0x3655DE2D, 0x3648DE18, 0x363ADE02, 0x362DDDED, 0x3620DDD8, 0x3612DDC3, 0x3605DDAD, 0x35F7DD98, 0x35EADD83, 0x35DCDD6E, 0x35CEDD59, 0x35C1DD44, 0x35B3DD2E, 0x35A5DD19, 0x3598DD04, 0x358ADCEF, 0x357CDCDA, 0x356EDCC5, 0x3561DCB0, 0x3553DC9B, 0x3545DC86, 0x3537DC72, 0x3529DC5D, 0x351BDC48, 0x350DDC33, 0x34FFDC1E, 0x34F1DC09, 0x34E2DBF5, 0x34D4DBE0, 0x34C6DBCB, 0x34B8DBB6, 0x34AADBA2, 0x349BDB8D, 0x348DDB78, 0x347FDB64, 0x3470DB4F, 0x3462DB3B, 0x3453DB26, 0x3445DB11, 0x3436DAFD, 0x3428DAE8, 0x3419DAD4, 0x340BDABF, 0x33FCDAAB, 0x33EDDA97, 0x33DFDA82, 0x33D0DA6E, 0x33C1DA5A, 0x33B2DA45, 0x33A3DA31, 0x3395DA1D, 0x3386DA08, 0x3377D9F4, 0x3368D9E0, 0x3359D9CC, 0x334AD9B8, 0x333BD9A4, 0x332CD98F, 0x331DD97B, 0x330DD967, 0x32FED953, 0x32EFD93F, 0x32E0D92B, 0x32D0D917, 0x32C1D903, 0x32B2D8EF, 0x32A3D8DC, 0x3293D8C8, 0x3284D8B4, 0x3274D8A0, 0x3265D88C, 0x3255D878, 0x3246D865, 0x3236D851, 0x3227D83D, 0x3217D82A, 0x3207D816, 0x31F8D802, 0x31E8D7EF, 0x31D8D7DB, 0x31C8D7C8, 0x31B9D7B4, 0x31A9D7A0, 0x3199D78D, 0x3189D77A, 0x3179D766, 0x3169D753, 0x3159D73F, 0x3149D72C, 0x3139D719, 0x3129D705, 0x3119D6F2, 0x3109D6DF, 0x30F9D6CB, 0x30E8D6B8, 0x30D8D6A5, 0x30C8D692, 0x30B8D67F, 0x30A7D66C, 0x3097D659, 0x3087D645, 0x3076D632, 0x3066D61F, 0x3055D60C, 0x3045D5F9, 0x3034D5E6, 0x3024D5D4, 0x3013D5C1, 0x3002D5AE, 0x2FF2D59B, 0x2FE1D588, 0x2FD0D575, 0x2FC0D563, 0x2FAFD550, 0x2F9ED53D, 0x2F8DD52A, 0x2F7DD518, 0x2F6CD505, 0x2F5BD4F3, 0x2F4AD4E0, 0x2F39D4CD, 0x2F28D4BB, 0x2F17D4A8, 0x2F06D496, 0x2EF5D483, 0x2EE4D471, 0x2ED3D45F, 0x2EC2D44C, 0x2EB0D43A, 0x2E9FD428, 0x2E8ED415, 0x2E7DD403, 0x2E6BD3F1, 0x2E5AD3DF, 0x2E49D3CC, 0x2E37D3BA, 0x2E26D3A8, 0x2E15D396, 0x2E03D384, 0x2DF2D372, 0x2DE0D360, 0x2DCFD34E, 0x2DBDD33C, 0x2DABD32A, 0x2D9AD318, 0x2D88D306, 0x2D76D2F4, 0x2D65D2E2, 0x2D53D2D1, 0x2D41D2BF, 0x2D2FD2AD, 0x2D1ED29B, 0x2D0CD28A, 0x2CFAD278, 0x2CE8D266, 0x2CD6D255, 0x2CC4D243, 0x2CB2D231, 0x2CA0D220, 0x2C8ED20E, 0x2C7CD1FD, 0x2C6AD1EB, 0x2C58D1DA, 0x2C46D1C9, 0x2C34D1B7, 0x2C21D1A6, 0x2C0FD195, 0x2BFDD183, 0x2BEBD172, 0x2BD8D161, 0x2BC6D150, 0x2BB4D13E, 0x2BA1D12D, 0x2B8FD11C, 0x2B7DD10B, 0x2B6AD0FA, 0x2B58D0E9, 0x2B45D0D8, 0x2B33D0C7, 0x2B20D0B6, 0x2B0DD0A5, 0x2AFBD094, 0x2AE8D083, 0x2AD6D073, 0x2AC3D062, 0x2AB0D051, 0x2A9DD040, 0x2A8BD030, 0x2A78D01F, 0x2A65D00E, 0x2A52CFFE, 0x2A3FCFED, 0x2A2CCFDC, 0x2A1ACFCC, 0x2A07CFBB, 0x29F4CFAB, 0x29E1CF9A, 0x29CECF8A, 0x29BBCF79, 0x29A7CF69, 0x2994CF59, 0x2981CF48, 0x296ECF38, 0x295BCF28, 0x2948CF18, 0x2935CF07, 0x2921CEF7, 0x290ECEE7, 0x28FBCED7, 0x28E7CEC7, 0x28D4CEB7, 0x28C1CEA7, 0x28ADCE97, 0x289ACE87, 0x2886CE77, 0x2873CE67, 0x2860CE57, 0x284CCE47, 0x2838CE38, 0x2825CE28, 0x2811CE18, 0x27FECE08, 0x27EACDF9, 0x27D6CDE9, 0x27C3CDD9, 0x27AFCDCA, 0x279BCDBA, 0x2788CDAB, 0x2774CD9B, 0x2760CD8C, 0x274CCD7C, 0x2738CD6D, 0x2724CD5D, 0x2711CD4E, 0x26FDCD3F, 0x26E9CD30, 0x26D5CD20, 0x26C1CD11, 0x26ADCD02, 0x2699CCF3, 0x2685CCE3, 0x2671CCD4, 0x265CCCC5, 0x2648CCB6, 0x2634CCA7, 0x2620CC98, 0x260CCC89, 0x25F8CC7A, 0x25E3CC6B, 0x25CFCC5D, 0x25BBCC4E, 0x25A6CC3F, 0x2592CC30, 0x257ECC21, 0x2569CC13, 0x2555CC04, 0x2541CBF5, 0x252CCBE7, 0x2518CBD8, 0x2503CBCA, 0x24EFCBBB, 0x24DACBAD, 0x24C5CB9E, 0x24B1CB90, 0x249CCB81, 0x2488CB73, 0x2473CB65, 0x245ECB56, 0x244ACB48, 0x2435CB3A, 0x2420CB2C, 0x240BCB1E, 0x23F7CB0F, 0x23E2CB01, 0x23CDCAF3, 0x23B8CAE5, 0x23A3CAD7, 0x238ECAC9, 0x237ACABB, 0x2365CAAD, 0x2350CA9F, 0x233BCA92, 0x2326CA84, 0x2311CA76, 0x22FCCA68, 0x22E7CA5B, 0x22D2CA4D, 0x22BCCA3F, 0x22A7CA32, 0x2292CA24, 0x227DCA16, 0x2268CA09, 0x2253C9FB, 0x223DC9EE, 0x2228C9E0, 0x2213C9D3, 0x21FEC9C6, 0x21E8C9B8, 0x21D3C9AB, 0x21BEC99E, 0x21A8C991, 0x2193C983, 0x217DC976, 0x2168C969, 0x2153C95C, 0x213DC94F, 0x2128C942, 0x2112C935, 0x20FDC928, 0x20E7C91B, 0x20D1C90E, 0x20BCC901, 0x20A6C8F4, 0x2091C8E8, 0x207BC8DB, 0x2065C8CE, 0x2050C8C1, 0x203AC8B5, 0x2024C8A8, 0x200FC89B, 0x1FF9C88F, 0x1FE3C882, 0x1FCDC876, 0x1FB7C869, 0x1FA2C85D, 0x1F8CC850, 0x1F76C844, 0x1F60C838, 0x1F4AC82B, 0x1F34C81F, 0x1F1EC813, 0x1F08C807, 0x1EF2C7FB, 0x1EDCC7EE, 0x1EC6C7E2, 0x1EB0C7D6, 0x1E9AC7CA, 0x1E84C7BE, 0x1E6EC7B2, 0x1E58C7A6, 0x1E42C79A, 0x1E2BC78F, 0x1E15C783, 0x1DFFC777, 0x1DE9C76B, 0x1DD3C75F, 0x1DBCC754, 0x1DA6C748, 0x1D90C73D, 0x1D79C731, 0x1D63C725, 0x1D4DC71A, 0x1D36C70E, 0x1D20C703, 0x1D0AC6F7, 0x1CF3C6EC, 0x1CDDC6E1, 0x1CC6C6D5, 0x1CB0C6CA, 0x1C99C6BF, 0x1C83C6B4, 0x1C6CC6A8, 0x1C56C69D, 0x1C3FC692, 0x1C29C687, 0x1C12C67C, 0x1BFCC671, 0x1BE5C666, 0x1BCEC65B, 0x1BB8C650, 0x1BA1C645, 0x1B8AC63B, 0x1B74C630, 0x1B5DC625, 0x1B46C61A, 0x1B30C610, 0x1B19C605, 0x1B02C5FA, 0x1AEBC5F0, 0x1AD4C5E5, 0x1ABEC5DB, 0x1AA7C5D0, 0x1A90C5C6, 0x1A79C5BB, 0x1A62C5B1, 0x1A4BC5A7, 0x1A34C59C, 0x1A1DC592, 0x1A06C588, 0x19EFC57E, 0x19D8C573, 0x19C1C569, 0x19AAC55F, 0x1993C555, 0x197CC54B, 0x1965C541, 0x194EC537, 0x1937C52D, 0x1920C523, 0x1909C51A, 0x18F2C510, 0x18DBC506, 0x18C3C4FC, 0x18ACC4F2, 0x1895C4E9, 0x187EC4DF, 0x1867C4D6, 0x184FC4CC, 0x1838C4C2, 0x1821C4B9, 0x180AC4B0, 0x17F2C4A6, 0x17DBC49D, 0x17C4C493, 0x17ACC48A, 0x1795C481, 0x177EC478, 0x1766C46E, 0x174FC465, 0x1737C45C, 0x1720C453, 0x1709C44A, 0x16F1C441, 0x16DAC438, 0x16C2C42F, 0x16ABC426, 0x1693C41D, 0x167CC414, 0x1664C40B, 0x164CC403, 0x1635C3FA, 0x161DC3F1, 0x1606C3E9, 0x15EEC3E0, 0x15D7C3D7, 0x15BFC3CF, 0x15A7C3C6, 0x1590C3BE, 0x1578C3B5, 0x1560C3AD, 0x1549C3A5, 0x1531C39C, 0x1519C394, 0x1501C38C, 0x14EAC383, 0x14D2C37B, 0x14BAC373, 0x14A2C36B, 0x148BC363, 0x1473C35B, 0x145BC353, 0x1443C34B, 0x142BC343, 0x1413C33B, 0x13FBC333, 0x13E4C32B, 0x13CCC323, 0x13B4C31C, 0x139CC314, 0x1384C30C, 0x136CC305, 0x1354C2FD, 0x133CC2F5, 0x1324C2EE, 0x130CC2E6, 0x12F4C2DF, 0x12DCC2D8, 0x12C4C2D0, 0x12ACC2C9, 0x1294C2C1, 0x127CC2BA, 0x1264C2B3, 0x124CC2AC, 0x1234C2A5, 0x121CC29D, 0x1204C296, 0x11EBC28F, 0x11D3C288, 0x11BBC281, 0x11A3C27A, 0x118BC273, 0x1173C26D, 0x115AC266, 0x1142C25F, 0x112AC258, 0x1112C251, 0x10FAC24B, 0x10E1C244, 0x10C9C23E, 0x10B1C237, 0x1099C230, 0x1080C22A, 0x1068C223, 0x1050C21D, 0x1037C217, 0x101FC210, 0x1007C20A, 0x0FEEC204, 0x0FD6C1FD, 0x0FBEC1F7, 0x0FA5C1F1, 0x0F8DC1EB, 0x0F75C1E5, 0x0F5CC1DF, 0x0F44C1D9, 0x0F2BC1D3, 0x0F13C1CD, 0x0EFBC1C7, 0x0EE2C1C1, 0x0ECAC1BB, 0x0EB1C1B6, 0x0E99C1B0, 0x0E80C1AA, 0x0E68C1A4, 0x0E4FC19F, 0x0E37C199, 0x0E1EC194, 0x0E06C18E, 0x0DEDC189, 0x0DD5C183, 0x0DBCC17E, 0x0DA4C178, 0x0D8BC173, 0x0D72C16E, 0x0D5AC168, 0x0D41C163, 0x0D29C15E, 0x0D10C159, 0x0CF8C154, 0x0CDFC14F, 0x0CC6C14A, 0x0CAEC145, 0x0C95C140, 0x0C7CC13B, 0x0C64C136, 0x0C4BC131, 0x0C32C12C, 0x0C1AC128, 0x0C01C123, 0x0BE8C11E, 0x0BD0C119, 0x0BB7C115, 0x0B9EC110, 0x0B85C10C, 0x0B6DC107, 0x0B54C103, 0x0B3BC0FE, 0x0B23C0FA, 0x0B0AC0F6, 0x0AF1C0F1, 0x0AD8C0ED, 0x0AC0C0E9, 0x0AA7C0E4, 0x0A8EC0E0, 0x0A75C0DC, 0x0A5CC0D8, 0x0A44C0D4, 0x0A2BC0D0, 0x0A12C0CC, 0x09F9C0C8, 0x09E0C0C4, 0x09C7C0C0, 0x09AFC0BD, 0x0996C0B9, 0x097DC0B5, 0x0964C0B1, 0x094BC0AE, 0x0932C0AA, 0x0919C0A6, 0x0901C0A3, 0x08E8C09F, 0x08CFC09C, 0x08B6C098, 0x089DC095, 0x0884C092, 0x086BC08E, 0x0852C08B, 0x0839C088, 0x0820C085, 0x0807C081, 0x07EFC07E, 0x07D6C07B, 0x07BDC078, 0x07A4C075, 0x078BC072, 0x0772C06F, 0x0759C06C, 0x0740C069, 0x0727C067, 0x070EC064, 0x06F5C061, 0x06DCC05E, 0x06C3C05C, 0x06AAC059, 0x0691C056, 0x0678C054, 0x065FC051, 0x0646C04F, 0x062DC04C, 0x0614C04A, 0x05FBC048, 0x05E2C045, 0x05C9C043, 0x05B0C041, 0x0597C03F, 0x057EC03C, 0x0565C03A, 0x054CC038, 0x0533C036, 0x051AC034, 0x0500C032, 0x04E7C030, 0x04CEC02E, 0x04B5C02C, 0x049CC02B, 0x0483C029, 0x046AC027, 0x0451C025, 0x0438C024, 0x041FC022, 0x0406C020, 0x03EDC01F, 0x03D4C01D, 0x03BBC01C, 0x03A1C01A, 0x0388C019, 0x036FC018, 0x0356C016, 0x033DC015, 0x0324C014, 0x030BC013, 0x02F2C011, 0x02D9C010, 0x02C0C00F, 0x02A6C00E, 0x028DC00D, 0x0274C00C, 0x025BC00B, 0x0242C00A, 0x0229C009, 0x0210C009, 0x01F7C008, 0x01DDC007, 0x01C4C006, 0x01ABC006, 0x0192C005, 0x0179C004, 0x0160C004, 0x0147C003, 0x012EC003, 0x0114C002, 0x00FBC002, 0x00E2C002, 0x00C9C001, 0x00B0C001, 0x0097C001, 0x007EC000, 0x0065C000, 0x004BC000, 0x0032C000, 0x0019C000, 0x0000C000, 0xFFE7C000, 0xFFCEC000, 0xFFB5C000, 0xFF9BC000, 0xFF82C000, 0xFF69C001, 0xFF50C001, 0xFF37C001, 0xFF1EC002, 0xFF05C002, 0xFEECC002, 0xFED2C003, 0xFEB9C003, 0xFEA0C004, 0xFE87C004, 0xFE6EC005, 0xFE55C006, 0xFE3CC006, 0xFE23C007, 0xFE09C008, 0xFDF0C009, 0xFDD7C009, 0xFDBEC00A, 0xFDA5C00B, 0xFD8CC00C, 0xFD73C00D, 0xFD5AC00E, 0xFD40C00F, 0xFD27C010, 0xFD0EC011, 0xFCF5C013, 0xFCDCC014, 0xFCC3C015, 0xFCAAC016, 0xFC91C018, 0xFC78C019, 0xFC5FC01A, 0xFC45C01C, 0xFC2CC01D, 0xFC13C01F, 0xFBFAC020, 0xFBE1C022, 0xFBC8C024, 0xFBAFC025, 0xFB96C027, 0xFB7DC029, 0xFB64C02B, 0xFB4BC02C, 0xFB32C02E, 0xFB19C030, 0xFB00C032, 0xFAE6C034, 0xFACDC036, 0xFAB4C038, 0xFA9BC03A, 0xFA82C03C, 0xFA69C03F, 0xFA50C041, 0xFA37C043, 0xFA1EC045, 0xFA05C048, 0xF9ECC04A, 0xF9D3C04C, 0xF9BAC04F, 0xF9A1C051, 0xF988C054, 0xF96FC056, 0xF956C059, 0xF93DC05C, 0xF924C05E, 0xF90BC061, 0xF8F2C064, 0xF8D9C067, 0xF8C0C069, 0xF8A7C06C, 0xF88EC06F, 0xF875C072, 0xF85CC075, 0xF843C078, 0xF82AC07B, 0xF811C07E, 0xF7F9C081, 0xF7E0C085, 0xF7C7C088, 0xF7AEC08B, 0xF795C08E, 0xF77CC092, 0xF763C095, 0xF74AC098, 0xF731C09C, 0xF718C09F, 0xF6FFC0A3, 0xF6E7C0A6, 0xF6CEC0AA, 0xF6B5C0AE, 0xF69CC0B1, 0xF683C0B5, 0xF66AC0B9, 0xF651C0BD, 0xF639C0C0, 0xF620C0C4, 0xF607C0C8, 0xF5EEC0CC, 0xF5D5C0D0, 0xF5BCC0D4, 0xF5A4C0D8, 0xF58BC0DC, 0xF572C0E0, 0xF559C0E4, 0xF540C0E9, 0xF528C0ED, 0xF50FC0F1, 0xF4F6C0F6, 0xF4DDC0FA, 0xF4C5C0FE, 0xF4ACC103, 0xF493C107, 0xF47BC10C, 0xF462C110, 0xF449C115, 0xF430C119, 0xF418C11E, 0xF3FFC123, 0xF3E6C128, 0xF3CEC12C, 0xF3B5C131, 0xF39CC136, 0xF384C13B, 0xF36BC140, 0xF352C145, 0xF33AC14A, 0xF321C14F, 0xF308C154, 0xF2F0C159, 0xF2D7C15E, 0xF2BFC163, 0xF2A6C168, 0xF28EC16E, 0xF275C173, 0xF25CC178, 0xF244C17E, 0xF22BC183, 0xF213C189, 0xF1FAC18E, 0xF1E2C194, 0xF1C9C199, 0xF1B1C19F, 0xF198C1A4, 0xF180C1AA, 0xF167C1B0, 0xF14FC1B6, 0xF136C1BB, 0xF11EC1C1, 0xF105C1C7, 0xF0EDC1CD, 0xF0D5C1D3, 0xF0BCC1D9, 0xF0A4C1DF, 0xF08BC1E5, 0xF073C1EB, 0xF05BC1F1, 0xF042C1F7, 0xF02AC1FD, 0xF012C204, 0xEFF9C20A, 0xEFE1C210, 0xEFC9C217, 0xEFB0C21D, 0xEF98C223, 0xEF80C22A, 0xEF67C230, 0xEF4FC237, 0xEF37C23E, 0xEF1FC244, 0xEF06C24B, 0xEEEEC251, 0xEED6C258, 0xEEBEC25F, 0xEEA6C266, 0xEE8DC26D, 0xEE75C273, 0xEE5DC27A, 0xEE45C281, 0xEE2DC288, 0xEE15C28F, 0xEDFCC296, 0xEDE4C29D, 0xEDCCC2A5, 0xEDB4C2AC, 0xED9CC2B3, 0xED84C2BA, 0xED6CC2C1, 0xED54C2C9, 0xED3CC2D0, 0xED24C2D8, 0xED0CC2DF, 0xECF4C2E6, 0xECDCC2EE, 0xECC4C2F5, 0xECACC2FD, 0xEC94C305, 0xEC7CC30C, 0xEC64C314, 0xEC4CC31C, 0xEC34C323, 0xEC1CC32B, 0xEC05C333, 0xEBEDC33B, 0xEBD5C343, 0xEBBDC34B, 0xEBA5C353, 0xEB8DC35B, 0xEB75C363, 0xEB5EC36B, 0xEB46C373, 0xEB2EC37B, 0xEB16C383, 0xEAFFC38C, 0xEAE7C394, 0xEACFC39C, 0xEAB7C3A5, 0xEAA0C3AD, 0xEA88C3B5, 0xEA70C3BE, 0xEA59C3C6, 0xEA41C3CF, 0xEA29C3D7, 0xEA12C3E0, 0xE9FAC3E9, 0xE9E3C3F1, 0xE9CBC3FA, 0xE9B4C403, 0xE99CC40B, 0xE984C414, 0xE96DC41D, 0xE955C426, 0xE93EC42F, 0xE926C438, 0xE90FC441, 0xE8F7C44A, 0xE8E0C453, 0xE8C9C45C, 0xE8B1C465, 0xE89AC46E, 0xE882C478, 0xE86BC481, 0xE854C48A, 0xE83CC493, 0xE825C49D, 0xE80EC4A6, 0xE7F6C4B0, 0xE7DFC4B9, 0xE7C8C4C2, 0xE7B1C4CC, 0xE799C4D6, 0xE782C4DF, 0xE76BC4E9, 0xE754C4F2, 0xE73DC4FC, 0xE725C506, 0xE70EC510, 0xE6F7C51A, 0xE6E0C523, 0xE6C9C52D, 0xE6B2C537, 0xE69BC541, 0xE684C54B, 0xE66DC555, 0xE656C55F, 0xE63FC569, 0xE628C573, 0xE611C57E, 0xE5FAC588, 0xE5E3C592, 0xE5CCC59C, 0xE5B5C5A7, 0xE59EC5B1, 0xE587C5BB, 0xE570C5C6, 0xE559C5D0, 0xE542C5DB, 0xE52CC5E5, 0xE515C5F0, 0xE4FEC5FA, 0xE4E7C605, 0xE4D0C610, 0xE4BAC61A, 0xE4A3C625, 0xE48CC630, 0xE476C63B, 0xE45FC645, 0xE448C650, 0xE432C65B, 0xE41BC666, 0xE404C671, 0xE3EEC67C, 0xE3D7C687, 0xE3C1C692, 0xE3AAC69D, 0xE394C6A8, 0xE37DC6B4, 0xE367C6BF, 0xE350C6CA, 0xE33AC6D5, 0xE323C6E1, 0xE30DC6EC, 0xE2F6C6F7, 0xE2E0C703, 0xE2CAC70E, 0xE2B3C71A, 0xE29DC725, 0xE287C731, 0xE270C73D, 0xE25AC748, 0xE244C754, 0xE22DC75F, 0xE217C76B, 0xE201C777, 0xE1EBC783, 0xE1D5C78F, 0xE1BEC79A, 0xE1A8C7A6, 0xE192C7B2, 0xE17CC7BE, 0xE166C7CA, 0xE150C7D6, 0xE13AC7E2, 0xE124C7EE, 0xE10EC7FB, 0xE0F8C807, 0xE0E2C813, 0xE0CCC81F, 0xE0B6C82B, 0xE0A0C838, 0xE08AC844, 0xE074C850, 0xE05EC85D, 0xE049C869, 0xE033C876, 0xE01DC882, 0xE007C88F, 0xDFF1C89B, 0xDFDCC8A8, 0xDFC6C8B5, 0xDFB0C8C1, 0xDF9BC8CE, 0xDF85C8DB, 0xDF6FC8E8, 0xDF5AC8F4, 0xDF44C901, 0xDF2FC90E, 0xDF19C91B, 0xDF03C928, 0xDEEEC935, 0xDED8C942, 0xDEC3C94F, 0xDEADC95C, 0xDE98C969, 0xDE83C976, 0xDE6DC983, 0xDE58C991, 0xDE42C99E, 0xDE2DC9AB, 0xDE18C9B8, 0xDE02C9C6, 0xDDEDC9D3, 0xDDD8C9E0, 0xDDC3C9EE, 0xDDADC9FB, 0xDD98CA09, 0xDD83CA16, 0xDD6ECA24, 0xDD59CA32, 0xDD44CA3F, 0xDD2ECA4D, 0xDD19CA5B, 0xDD04CA68, 0xDCEFCA76, 0xDCDACA84, 0xDCC5CA92, 0xDCB0CA9F, 0xDC9BCAAD, 0xDC86CABB, 0xDC72CAC9, 0xDC5DCAD7, 0xDC48CAE5, 0xDC33CAF3, 0xDC1ECB01, 0xDC09CB0F, 0xDBF5CB1E, 0xDBE0CB2C, 0xDBCBCB3A, 0xDBB6CB48, 0xDBA2CB56, 0xDB8DCB65, 0xDB78CB73, 0xDB64CB81, 0xDB4FCB90, 0xDB3BCB9E, 0xDB26CBAD, 0xDB11CBBB, 0xDAFDCBCA, 0xDAE8CBD8, 0xDAD4CBE7, 0xDABFCBF5, 0xDAABCC04, 0xDA97CC13, 0xDA82CC21, 0xDA6ECC30, 0xDA5ACC3F, 0xDA45CC4E, 0xDA31CC5D, 0xDA1DCC6B, 0xDA08CC7A, 0xD9F4CC89, 0xD9E0CC98, 0xD9CCCCA7, 0xD9B8CCB6, 0xD9A4CCC5, 0xD98FCCD4, 0xD97BCCE3, 0xD967CCF3, 0xD953CD02, 0xD93FCD11, 0xD92BCD20, 0xD917CD30, 0xD903CD3F, 0xD8EFCD4E, 0xD8DCCD5D, 0xD8C8CD6D, 0xD8B4CD7C, 0xD8A0CD8C, 0xD88CCD9B, 0xD878CDAB, 0xD865CDBA, 0xD851CDCA, 0xD83DCDD9, 0xD82ACDE9, 0xD816CDF9, 0xD802CE08, 0xD7EFCE18, 0xD7DBCE28, 0xD7C8CE38, 0xD7B4CE47, 0xD7A0CE57, 0xD78DCE67, 0xD77ACE77, 0xD766CE87, 0xD753CE97, 0xD73FCEA7, 0xD72CCEB7, 0xD719CEC7, 0xD705CED7, 0xD6F2CEE7, 0xD6DFCEF7, 0xD6CBCF07, 0xD6B8CF18, 0xD6A5CF28, 0xD692CF38, 0xD67FCF48, 0xD66CCF59, 0xD659CF69, 0xD645CF79, 0xD632CF8A, 0xD61FCF9A, 0xD60CCFAB, 0xD5F9CFBB, 0xD5E6CFCC, 0xD5D4CFDC, 0xD5C1CFED, 0xD5AECFFE, 0xD59BD00E, 0xD588D01F, 0xD575D030, 0xD563D040, 0xD550D051, 0xD53DD062, 0xD52AD073, 0xD518D083, 0xD505D094, 0xD4F3D0A5, 0xD4E0D0B6, 0xD4CDD0C7, 0xD4BBD0D8, 0xD4A8D0E9, 0xD496D0FA, 0xD483D10B, 0xD471D11C, 0xD45FD12D, 0xD44CD13E, 0xD43AD150, 0xD428D161, 0xD415D172, 0xD403D183, 0xD3F1D195, 0xD3DFD1A6, 0xD3CCD1B7, 0xD3BAD1C9, 0xD3A8D1DA, 0xD396D1EB, 0xD384D1FD, 0xD372D20E, 0xD360D220, 0xD34ED231, 0xD33CD243, 0xD32AD255, 0xD318D266, 0xD306D278, 0xD2F4D28A, 0xD2E2D29B, 0xD2D1D2AD, 0xD2BFD2BF, 0xD2ADD2D1, 0xD29BD2E2, 0xD28AD2F4, 0xD278D306, 0xD266D318, 0xD255D32A, 0xD243D33C, 0xD231D34E, 0xD220D360, 0xD20ED372, 0xD1FDD384, 0xD1EBD396, 0xD1DAD3A8, 0xD1C9D3BA, 0xD1B7D3CC, 0xD1A6D3DF, 0xD195D3F1, 0xD183D403, 0xD172D415, 0xD161D428, 0xD150D43A, 0xD13ED44C, 0xD12DD45F, 0xD11CD471, 0xD10BD483, 0xD0FAD496, 0xD0E9D4A8, 0xD0D8D4BB, 0xD0C7D4CD, 0xD0B6D4E0, 0xD0A5D4F3, 0xD094D505, 0xD083D518, 0xD073D52A, 0xD062D53D, 0xD051D550, 0xD040D563, 0xD030D575, 0xD01FD588, 0xD00ED59B, 0xCFFED5AE, 0xCFEDD5C1, 0xCFDCD5D4, 0xCFCCD5E6, 0xCFBBD5F9, 0xCFABD60C, 0xCF9AD61F, 0xCF8AD632, 0xCF79D645, 0xCF69D659, 0xCF59D66C, 0xCF48D67F, 0xCF38D692, 0xCF28D6A5, 0xCF18D6B8, 0xCF07D6CB, 0xCEF7D6DF, 0xCEE7D6F2, 0xCED7D705, 0xCEC7D719, 0xCEB7D72C, 0xCEA7D73F, 0xCE97D753, 0xCE87D766, 0xCE77D77A, 0xCE67D78D, 0xCE57D7A0, 0xCE47D7B4, 0xCE38D7C8, 0xCE28D7DB, 0xCE18D7EF, 0xCE08D802, 0xCDF9D816, 0xCDE9D82A, 0xCDD9D83D, 0xCDCAD851, 0xCDBAD865, 0xCDABD878, 0xCD9BD88C, 0xCD8CD8A0, 0xCD7CD8B4, 0xCD6DD8C8, 0xCD5DD8DC, 0xCD4ED8EF, 0xCD3FD903, 0xCD30D917, 0xCD20D92B, 0xCD11D93F, 0xCD02D953, 0xCCF3D967, 0xCCE3D97B, 0xCCD4D98F, 0xCCC5D9A4, 0xCCB6D9B8, 0xCCA7D9CC, 0xCC98D9E0, 0xCC89D9F4, 0xCC7ADA08, 0xCC6BDA1D, 0xCC5DDA31, 0xCC4EDA45, 0xCC3FDA5A, 0xCC30DA6E, 0xCC21DA82, 0xCC13DA97, 0xCC04DAAB, 0xCBF5DABF, 0xCBE7DAD4, 0xCBD8DAE8, 0xCBCADAFD, 0xCBBBDB11, 0xCBADDB26, 0xCB9EDB3B, 0xCB90DB4F, 0xCB81DB64, 0xCB73DB78, 0xCB65DB8D, 0xCB56DBA2, 0xCB48DBB6, 0xCB3ADBCB, 0xCB2CDBE0, 0xCB1EDBF5, 0xCB0FDC09, 0xCB01DC1E, 0xCAF3DC33, 0xCAE5DC48, 0xCAD7DC5D, 0xCAC9DC72, 0xCABBDC86, 0xCAADDC9B, 0xCA9FDCB0, 0xCA92DCC5, 0xCA84DCDA, 0xCA76DCEF, 0xCA68DD04, 0xCA5BDD19, 0xCA4DDD2E, 0xCA3FDD44, 0xCA32DD59, 0xCA24DD6E, 0xCA16DD83, 0xCA09DD98, 0xC9FBDDAD, 0xC9EEDDC3, 0xC9E0DDD8, 0xC9D3DDED, 0xC9C6DE02, 0xC9B8DE18, 0xC9ABDE2D, 0xC99EDE42, 0xC991DE58, 0xC983DE6D, 0xC976DE83, 0xC969DE98, 0xC95CDEAD, 0xC94FDEC3, 0xC942DED8, 0xC935DEEE, 0xC928DF03, 0xC91BDF19, 0xC90EDF2F, 0xC901DF44, 0xC8F4DF5A, 0xC8E8DF6F, 0xC8DBDF85, 0xC8CEDF9B, 0xC8C1DFB0, 0xC8B5DFC6, 0xC8A8DFDC, 0xC89BDFF1, 0xC88FE007, 0xC882E01D, 0xC876E033, 0xC869E049, 0xC85DE05E, 0xC850E074, 0xC844E08A, 0xC838E0A0, 0xC82BE0B6, 0xC81FE0CC, 0xC813E0E2, 0xC807E0F8, 0xC7FBE10E, 0xC7EEE124, 0xC7E2E13A, 0xC7D6E150, 0xC7CAE166, 0xC7BEE17C, 0xC7B2E192, 0xC7A6E1A8, 0xC79AE1BE, 0xC78FE1D5, 0xC783E1EB, 0xC777E201, 0xC76BE217, 0xC75FE22D, 0xC754E244, 0xC748E25A, 0xC73DE270, 0xC731E287, 0xC725E29D, 0xC71AE2B3, 0xC70EE2CA, 0xC703E2E0, 0xC6F7E2F6, 0xC6ECE30D, 0xC6E1E323, 0xC6D5E33A, 0xC6CAE350, 0xC6BFE367, 0xC6B4E37D, 0xC6A8E394, 0xC69DE3AA, 0xC692E3C1, 0xC687E3D7, 0xC67CE3EE, 0xC671E404, 0xC666E41B, 0xC65BE432, 0xC650E448, 0xC645E45F, 0xC63BE476, 0xC630E48C, 0xC625E4A3, 0xC61AE4BA, 0xC610E4D0, 0xC605E4E7, 0xC5FAE4FE, 0xC5F0E515, 0xC5E5E52C, 0xC5DBE542, 0xC5D0E559, 0xC5C6E570, 0xC5BBE587, 0xC5B1E59E, 0xC5A7E5B5, 0xC59CE5CC, 0xC592E5E3, 0xC588E5FA, 0xC57EE611, 0xC573E628, 0xC569E63F, 0xC55FE656, 0xC555E66D, 0xC54BE684, 0xC541E69B, 0xC537E6B2, 0xC52DE6C9, 0xC523E6E0, 0xC51AE6F7, 0xC510E70E, 0xC506E725, 0xC4FCE73D, 0xC4F2E754, 0xC4E9E76B, 0xC4DFE782, 0xC4D6E799, 0xC4CCE7B1, 0xC4C2E7C8, 0xC4B9E7DF, 0xC4B0E7F6, 0xC4A6E80E, 0xC49DE825, 0xC493E83C, 0xC48AE854, 0xC481E86B, 0xC478E882, 0xC46EE89A, 0xC465E8B1, 0xC45CE8C9, 0xC453E8E0, 0xC44AE8F7, 0xC441E90F, 0xC438E926, 0xC42FE93E, 0xC426E955, 0xC41DE96D, 0xC414E984, 0xC40BE99C, 0xC403E9B4, 0xC3FAE9CB, 0xC3F1E9E3, 0xC3E9E9FA, 0xC3E0EA12, 0xC3D7EA29, 0xC3CFEA41, 0xC3C6EA59, 0xC3BEEA70, 0xC3B5EA88, 0xC3ADEAA0, 0xC3A5EAB7, 0xC39CEACF, 0xC394EAE7, 0xC38CEAFF, 0xC383EB16, 0xC37BEB2E, 0xC373EB46, 0xC36BEB5E, 0xC363EB75, 0xC35BEB8D, 0xC353EBA5, 0xC34BEBBD, 0xC343EBD5, 0xC33BEBED, 0xC333EC05, 0xC32BEC1C, 0xC323EC34, 0xC31CEC4C, 0xC314EC64, 0xC30CEC7C, 0xC305EC94, 0xC2FDECAC, 0xC2F5ECC4, 0xC2EEECDC, 0xC2E6ECF4, 0xC2DFED0C, 0xC2D8ED24, 0xC2D0ED3C, 0xC2C9ED54, 0xC2C1ED6C, 0xC2BAED84, 0xC2B3ED9C, 0xC2ACEDB4, 0xC2A5EDCC, 0xC29DEDE4, 0xC296EDFC, 0xC28FEE15, 0xC288EE2D, 0xC281EE45, 0xC27AEE5D, 0xC273EE75, 0xC26DEE8D, 0xC266EEA6, 0xC25FEEBE, 0xC258EED6, 0xC251EEEE, 0xC24BEF06, 0xC244EF1F, 0xC23EEF37, 0xC237EF4F, 0xC230EF67, 0xC22AEF80, 0xC223EF98, 0xC21DEFB0, 0xC217EFC9, 0xC210EFE1, 0xC20AEFF9, 0xC204F012, 0xC1FDF02A, 0xC1F7F042, 0xC1F1F05B, 0xC1EBF073, 0xC1E5F08B, 0xC1DFF0A4, 0xC1D9F0BC, 0xC1D3F0D5, 0xC1CDF0ED, 0xC1C7F105, 0xC1C1F11E, 0xC1BBF136, 0xC1B6F14F, 0xC1B0F167, 0xC1AAF180, 0xC1A4F198, 0xC19FF1B1, 0xC199F1C9, 0xC194F1E2, 0xC18EF1FA, 0xC189F213, 0xC183F22B, 0xC17EF244, 0xC178F25C, 0xC173F275, 0xC16EF28E, 0xC168F2A6, 0xC163F2BF, 0xC15EF2D7, 0xC159F2F0, 0xC154F308, 0xC14FF321, 0xC14AF33A, 0xC145F352, 0xC140F36B, 0xC13BF384, 0xC136F39C, 0xC131F3B5, 0xC12CF3CE, 0xC128F3E6, 0xC123F3FF, 0xC11EF418, 0xC119F430, 0xC115F449, 0xC110F462, 0xC10CF47B, 0xC107F493, 0xC103F4AC, 0xC0FEF4C5, 0xC0FAF4DD, 0xC0F6F4F6, 0xC0F1F50F, 0xC0EDF528, 0xC0E9F540, 0xC0E4F559, 0xC0E0F572, 0xC0DCF58B, 0xC0D8F5A4, 0xC0D4F5BC, 0xC0D0F5D5, 0xC0CCF5EE, 0xC0C8F607, 0xC0C4F620, 0xC0C0F639, 0xC0BDF651, 0xC0B9F66A, 0xC0B5F683, 0xC0B1F69C, 0xC0AEF6B5, 0xC0AAF6CE, 0xC0A6F6E7, 0xC0A3F6FF, 0xC09FF718, 0xC09CF731, 0xC098F74A, 0xC095F763, 0xC092F77C, 0xC08EF795, 0xC08BF7AE, 0xC088F7C7, 0xC085F7E0, 0xC081F7F9, 0xC07EF811, 0xC07BF82A, 0xC078F843, 0xC075F85C, 0xC072F875, 0xC06FF88E, 0xC06CF8A7, 0xC069F8C0, 0xC067F8D9, 0xC064F8F2, 0xC061F90B, 0xC05EF924, 0xC05CF93D, 0xC059F956, 0xC056F96F, 0xC054F988, 0xC051F9A1, 0xC04FF9BA, 0xC04CF9D3, 0xC04AF9EC, 0xC048FA05, 0xC045FA1E, 0xC043FA37, 0xC041FA50, 0xC03FFA69, 0xC03CFA82, 0xC03AFA9B, 0xC038FAB4, 0xC036FACD, 0xC034FAE6, 0xC032FB00, 0xC030FB19, 0xC02EFB32, 0xC02CFB4B, 0xC02BFB64, 0xC029FB7D, 0xC027FB96, 0xC025FBAF, 0xC024FBC8, 0xC022FBE1, 0xC020FBFA, 0xC01FFC13, 0xC01DFC2C, 0xC01CFC45, 0xC01AFC5F, 0xC019FC78, 0xC018FC91, 0xC016FCAA, 0xC015FCC3, 0xC014FCDC, 0xC013FCF5, 0xC011FD0E, 0xC010FD27, 0xC00FFD40, 0xC00EFD5A, 0xC00DFD73, 0xC00CFD8C, 0xC00BFDA5, 0xC00AFDBE, 0xC009FDD7, 0xC009FDF0, 0xC008FE09, 0xC007FE23, 0xC006FE3C, 0xC006FE55, 0xC005FE6E, 0xC004FE87, 0xC004FEA0, 0xC003FEB9, 0xC003FED2, 0xC002FEEC, 0xC002FF05, 0xC002FF1E, 0xC001FF37, 0xC001FF50, 0xC001FF69, 0xC000FF82, 0xC000FF9B, 0xC000FFB5, 0xC000FFCE, 0xC000FFE7, 0xC0000000, 0xC0000019, 0xC0000032, 0xC000004B, 0xC0000065, 0xC000007E, 0xC0010097, 0xC00100B0, 0xC00100C9, 0xC00200E2, 0xC00200FB, 0xC0020114, 0xC003012E, 0xC0030147, 0xC0040160, 0xC0040179, 0xC0050192, 0xC00601AB, 0xC00601C4, 0xC00701DD, 0xC00801F7, 0xC0090210, 0xC0090229, 0xC00A0242, 0xC00B025B, 0xC00C0274, 0xC00D028D, 0xC00E02A6, 0xC00F02C0, 0xC01002D9, 0xC01102F2, 0xC013030B, 0xC0140324, 0xC015033D, 0xC0160356, 0xC018036F, 0xC0190388, 0xC01A03A1, 0xC01C03BB, 0xC01D03D4, 0xC01F03ED, 0xC0200406, 0xC022041F, 0xC0240438, 0xC0250451, 0xC027046A, 0xC0290483, 0xC02B049C, 0xC02C04B5, 0xC02E04CE, 0xC03004E7, 0xC0320500, 0xC034051A, 0xC0360533, 0xC038054C, 0xC03A0565, 0xC03C057E, 0xC03F0597, 0xC04105B0, 0xC04305C9, 0xC04505E2, 0xC04805FB, 0xC04A0614, 0xC04C062D, 0xC04F0646, 0xC051065F, 0xC0540678, 0xC0560691, 0xC05906AA, 0xC05C06C3, 0xC05E06DC, 0xC06106F5, 0xC064070E, 0xC0670727, 0xC0690740, 0xC06C0759, 0xC06F0772, 0xC072078B, 0xC07507A4, 0xC07807BD, 0xC07B07D6, 0xC07E07EF, 0xC0810807, 0xC0850820, 0xC0880839, 0xC08B0852, 0xC08E086B, 0xC0920884, 0xC095089D, 0xC09808B6, 0xC09C08CF, 0xC09F08E8, 0xC0A30901, 0xC0A60919, 0xC0AA0932, 0xC0AE094B, 0xC0B10964, 0xC0B5097D, 0xC0B90996, 0xC0BD09AF, 0xC0C009C7, 0xC0C409E0, 0xC0C809F9, 0xC0CC0A12, 0xC0D00A2B, 0xC0D40A44, 0xC0D80A5C, 0xC0DC0A75, 0xC0E00A8E, 0xC0E40AA7, 0xC0E90AC0, 0xC0ED0AD8, 0xC0F10AF1, 0xC0F60B0A, 0xC0FA0B23, 0xC0FE0B3B, 0xC1030B54, 0xC1070B6D, 0xC10C0B85, 0xC1100B9E, 0xC1150BB7, 0xC1190BD0, 0xC11E0BE8, 0xC1230C01, 0xC1280C1A, 0xC12C0C32, 0xC1310C4B, 0xC1360C64, 0xC13B0C7C, 0xC1400C95, 0xC1450CAE, 0xC14A0CC6, 0xC14F0CDF, 0xC1540CF8, 0xC1590D10, 0xC15E0D29, 0xC1630D41, 0xC1680D5A, 0xC16E0D72, 0xC1730D8B, 0xC1780DA4, 0xC17E0DBC, 0xC1830DD5, 0xC1890DED, 0xC18E0E06, 0xC1940E1E, 0xC1990E37, 0xC19F0E4F, 0xC1A40E68, 0xC1AA0E80, 0xC1B00E99, 0xC1B60EB1, 0xC1BB0ECA, 0xC1C10EE2, 0xC1C70EFB, 0xC1CD0F13, 0xC1D30F2B, 0xC1D90F44, 0xC1DF0F5C, 0xC1E50F75, 0xC1EB0F8D, 0xC1F10FA5, 0xC1F70FBE, 0xC1FD0FD6, 0xC2040FEE, 0xC20A1007, 0xC210101F, 0xC2171037, 0xC21D1050, 0xC2231068, 0xC22A1080, 0xC2301099, 0xC23710B1, 0xC23E10C9, 0xC24410E1, 0xC24B10FA, 0xC2511112, 0xC258112A, 0xC25F1142, 0xC266115A, 0xC26D1173, 0xC273118B, 0xC27A11A3, 0xC28111BB, 0xC28811D3, 0xC28F11EB, 0xC2961204, 0xC29D121C, 0xC2A51234, 0xC2AC124C, 0xC2B31264, 0xC2BA127C, 0xC2C11294, 0xC2C912AC, 0xC2D012C4, 0xC2D812DC, 0xC2DF12F4, 0xC2E6130C, 0xC2EE1324, 0xC2F5133C, 0xC2FD1354, 0xC305136C, 0xC30C1384, 0xC314139C, 0xC31C13B4, 0xC32313CC, 0xC32B13E4, 0xC33313FB, 0xC33B1413, 0xC343142B, 0xC34B1443, 0xC353145B, 0xC35B1473, 0xC363148B, 0xC36B14A2, 0xC37314BA, 0xC37B14D2, 0xC38314EA, 0xC38C1501, 0xC3941519, 0xC39C1531, 0xC3A51549, 0xC3AD1560, 0xC3B51578, 0xC3BE1590, 0xC3C615A7, 0xC3CF15BF, 0xC3D715D7, 0xC3E015EE, 0xC3E91606, 0xC3F1161D, 0xC3FA1635, 0xC403164C, 0xC40B1664, 0xC414167C, 0xC41D1693, 0xC42616AB, 0xC42F16C2, 0xC43816DA, 0xC44116F1, 0xC44A1709, 0xC4531720, 0xC45C1737, 0xC465174F, 0xC46E1766, 0xC478177E, 0xC4811795, 0xC48A17AC, 0xC49317C4, 0xC49D17DB, 0xC4A617F2, 0xC4B0180A, 0xC4B91821, 0xC4C21838, 0xC4CC184F, 0xC4D61867, 0xC4DF187E, 0xC4E91895, 0xC4F218AC, 0xC4FC18C3, 0xC50618DB, 0xC51018F2, 0xC51A1909, 0xC5231920, 0xC52D1937, 0xC537194E, 0xC5411965, 0xC54B197C, 0xC5551993, 0xC55F19AA, 0xC56919C1, 0xC57319D8, 0xC57E19EF, 0xC5881A06, 0xC5921A1D, 0xC59C1A34, 0xC5A71A4B, 0xC5B11A62, 0xC5BB1A79, 0xC5C61A90, 0xC5D01AA7, 0xC5DB1ABE, 0xC5E51AD4, 0xC5F01AEB, 0xC5FA1B02, 0xC6051B19, 0xC6101B30, 0xC61A1B46, 0xC6251B5D, 0xC6301B74, 0xC63B1B8A, 0xC6451BA1, 0xC6501BB8, 0xC65B1BCE, 0xC6661BE5, 0xC6711BFC, 0xC67C1C12, 0xC6871C29, 0xC6921C3F, 0xC69D1C56, 0xC6A81C6C, 0xC6B41C83, 0xC6BF1C99, 0xC6CA1CB0, 0xC6D51CC6, 0xC6E11CDD, 0xC6EC1CF3, 0xC6F71D0A, 0xC7031D20, 0xC70E1D36, 0xC71A1D4D, 0xC7251D63, 0xC7311D79, 0xC73D1D90, 0xC7481DA6, 0xC7541DBC, 0xC75F1DD3, 0xC76B1DE9, 0xC7771DFF, 0xC7831E15, 0xC78F1E2B, 0xC79A1E42, 0xC7A61E58, 0xC7B21E6E, 0xC7BE1E84, 0xC7CA1E9A, 0xC7D61EB0, 0xC7E21EC6, 0xC7EE1EDC, 0xC7FB1EF2, 0xC8071F08, 0xC8131F1E, 0xC81F1F34, 0xC82B1F4A, 0xC8381F60, 0xC8441F76, 0xC8501F8C, 0xC85D1FA2, 0xC8691FB7, 0xC8761FCD, 0xC8821FE3, 0xC88F1FF9, 0xC89B200F, 0xC8A82024, 0xC8B5203A, 0xC8C12050, 0xC8CE2065, 0xC8DB207B, 0xC8E82091, 0xC8F420A6, 0xC90120BC, 0xC90E20D1, 0xC91B20E7, 0xC92820FD, 0xC9352112, 0xC9422128, 0xC94F213D, 0xC95C2153, 0xC9692168, 0xC976217D, 0xC9832193, 0xC99121A8, 0xC99E21BE, 0xC9AB21D3, 0xC9B821E8, 0xC9C621FE, 0xC9D32213, 0xC9E02228, 0xC9EE223D, 0xC9FB2253, 0xCA092268, 0xCA16227D, 0xCA242292, 0xCA3222A7, 0xCA3F22BC, 0xCA4D22D2, 0xCA5B22E7, 0xCA6822FC, 0xCA762311, 0xCA842326, 0xCA92233B, 0xCA9F2350, 0xCAAD2365, 0xCABB237A, 0xCAC9238E, 0xCAD723A3, 0xCAE523B8, 0xCAF323CD, 0xCB0123E2, 0xCB0F23F7, 0xCB1E240B, 0xCB2C2420, 0xCB3A2435, 0xCB48244A, 0xCB56245E, 0xCB652473, 0xCB732488, 0xCB81249C, 0xCB9024B1, 0xCB9E24C5, 0xCBAD24DA, 0xCBBB24EF, 0xCBCA2503, 0xCBD82518, 0xCBE7252C, 0xCBF52541, 0xCC042555, 0xCC132569, 0xCC21257E, 0xCC302592, 0xCC3F25A6, 0xCC4E25BB, 0xCC5D25CF, 0xCC6B25E3, 0xCC7A25F8, 0xCC89260C, 0xCC982620, 0xCCA72634, 0xCCB62648, 0xCCC5265C, 0xCCD42671, 0xCCE32685, 0xCCF32699, 0xCD0226AD, 0xCD1126C1, 0xCD2026D5, 0xCD3026E9, 0xCD3F26FD, 0xCD4E2711, 0xCD5D2724, 0xCD6D2738, 0xCD7C274C, 0xCD8C2760, 0xCD9B2774, 0xCDAB2788, 0xCDBA279B, 0xCDCA27AF, 0xCDD927C3, 0xCDE927D6, 0xCDF927EA, 0xCE0827FE, 0xCE182811, 0xCE282825, 0xCE382838, 0xCE47284C, 0xCE572860, 0xCE672873, 0xCE772886, 0xCE87289A, 0xCE9728AD, 0xCEA728C1, 0xCEB728D4, 0xCEC728E7, 0xCED728FB, 0xCEE7290E, 0xCEF72921, 0xCF072935, 0xCF182948, 0xCF28295B, 0xCF38296E, 0xCF482981, 0xCF592994, 0xCF6929A7, 0xCF7929BB, 0xCF8A29CE, 0xCF9A29E1, 0xCFAB29F4, 0xCFBB2A07, 0xCFCC2A1A, 0xCFDC2A2C, 0xCFED2A3F, 0xCFFE2A52, 0xD00E2A65, 0xD01F2A78, 0xD0302A8B, 0xD0402A9D, 0xD0512AB0, 0xD0622AC3, 0xD0732AD6, 0xD0832AE8, 0xD0942AFB, 0xD0A52B0D, 0xD0B62B20, 0xD0C72B33, 0xD0D82B45, 0xD0E92B58, 0xD0FA2B6A, 0xD10B2B7D, 0xD11C2B8F, 0xD12D2BA1, 0xD13E2BB4, 0xD1502BC6, 0xD1612BD8, 0xD1722BEB, 0xD1832BFD, 0xD1952C0F, 0xD1A62C21, 0xD1B72C34, 0xD1C92C46, 0xD1DA2C58, 0xD1EB2C6A, 0xD1FD2C7C, 0xD20E2C8E, 0xD2202CA0, 0xD2312CB2, 0xD2432CC4, 0xD2552CD6, 0xD2662CE8, 0xD2782CFA, 0xD28A2D0C, 0xD29B2D1E, 0xD2AD2D2F, 0xD2BF2D41, 0xD2D12D53, 0xD2E22D65, 0xD2F42D76, 0xD3062D88, 0xD3182D9A, 0xD32A2DAB, 0xD33C2DBD, 0xD34E2DCF, 0xD3602DE0, 0xD3722DF2, 0xD3842E03, 0xD3962E15, 0xD3A82E26, 0xD3BA2E37, 0xD3CC2E49, 0xD3DF2E5A, 0xD3F12E6B, 0xD4032E7D, 0xD4152E8E, 0xD4282E9F, 0xD43A2EB0, 0xD44C2EC2, 0xD45F2ED3, 0xD4712EE4, 0xD4832EF5, 0xD4962F06, 0xD4A82F17, 0xD4BB2F28, 0xD4CD2F39, 0xD4E02F4A, 0xD4F32F5B, 0xD5052F6C, 0xD5182F7D, 0xD52A2F8D, 0xD53D2F9E, 0xD5502FAF, 0xD5632FC0, 0xD5752FD0, 0xD5882FE1, 0xD59B2FF2, 0xD5AE3002, 0xD5C13013, 0xD5D43024, 0xD5E63034, 0xD5F93045, 0xD60C3055, 0xD61F3066, 0xD6323076, 0xD6453087, 0xD6593097, 0xD66C30A7, 0xD67F30B8, 0xD69230C8, 0xD6A530D8, 0xD6B830E8, 0xD6CB30F9, 0xD6DF3109, 0xD6F23119, 0xD7053129, 0xD7193139, 0xD72C3149, 0xD73F3159, 0xD7533169, 0xD7663179, 0xD77A3189, 0xD78D3199, 0xD7A031A9, 0xD7B431B9, 0xD7C831C8, 0xD7DB31D8, 0xD7EF31E8, 0xD80231F8, 0xD8163207, 0xD82A3217, 0xD83D3227, 0xD8513236, 0xD8653246, 0xD8783255, 0xD88C3265, 0xD8A03274, 0xD8B43284, 0xD8C83293, 0xD8DC32A3, 0xD8EF32B2, 0xD90332C1, 0xD91732D0, 0xD92B32E0, 0xD93F32EF, 0xD95332FE, 0xD967330D, 0xD97B331D, 0xD98F332C, 0xD9A4333B, 0xD9B8334A, 0xD9CC3359, 0xD9E03368, 0xD9F43377, 0xDA083386, 0xDA1D3395, 0xDA3133A3, 0xDA4533B2, 0xDA5A33C1, 0xDA6E33D0, 0xDA8233DF, 0xDA9733ED, 0xDAAB33FC, 0xDABF340B, 0xDAD43419, 0xDAE83428, 0xDAFD3436, 0xDB113445, 0xDB263453, 0xDB3B3462, 0xDB4F3470, 0xDB64347F, 0xDB78348D, 0xDB8D349B, 0xDBA234AA, 0xDBB634B8, 0xDBCB34C6, 0xDBE034D4, 0xDBF534E2, 0xDC0934F1, 0xDC1E34FF, 0xDC33350D, 0xDC48351B, 0xDC5D3529, 0xDC723537, 0xDC863545, 0xDC9B3553, 0xDCB03561, 0xDCC5356E, 0xDCDA357C, 0xDCEF358A, 0xDD043598, 0xDD1935A5, 0xDD2E35B3, 0xDD4435C1, 0xDD5935CE, 0xDD6E35DC, 0xDD8335EA, 0xDD9835F7, 0xDDAD3605, 0xDDC33612, 0xDDD83620, 0xDDED362D, 0xDE02363A, 0xDE183648, 0xDE2D3655, 0xDE423662, 0xDE58366F, 0xDE6D367D, 0xDE83368A, 0xDE983697, 0xDEAD36A4, 0xDEC336B1, 0xDED836BE, 0xDEEE36CB, 0xDF0336D8, 0xDF1936E5, 0xDF2F36F2, 0xDF4436FF, 0xDF5A370C, 0xDF6F3718, 0xDF853725, 0xDF9B3732, 0xDFB0373F, 0xDFC6374B, 0xDFDC3758, 0xDFF13765, 0xE0073771, 0xE01D377E, 0xE033378A, 0xE0493797, 0xE05E37A3, 0xE07437B0, 0xE08A37BC, 0xE0A037C8, 0xE0B637D5, 0xE0CC37E1, 0xE0E237ED, 0xE0F837F9, 0xE10E3805, 0xE1243812, 0xE13A381E, 0xE150382A, 0xE1663836, 0xE17C3842, 0xE192384E, 0xE1A8385A, 0xE1BE3866, 0xE1D53871, 0xE1EB387D, 0xE2013889, 0xE2173895, 0xE22D38A1, 0xE24438AC, 0xE25A38B8, 0xE27038C3, 0xE28738CF, 0xE29D38DB, 0xE2B338E6, 0xE2CA38F2, 0xE2E038FD, 0xE2F63909, 0xE30D3914, 0xE323391F, 0xE33A392B, 0xE3503936, 0xE3673941, 0xE37D394C, 0xE3943958, 0xE3AA3963, 0xE3C1396E, 0xE3D73979, 0xE3EE3984, 0xE404398F, 0xE41B399A, 0xE43239A5, 0xE44839B0, 0xE45F39BB, 0xE47639C5, 0xE48C39D0, 0xE4A339DB, 0xE4BA39E6, 0xE4D039F0, 0xE4E739FB, 0xE4FE3A06, 0xE5153A10, 0xE52C3A1B, 0xE5423A25, 0xE5593A30, 0xE5703A3A, 0xE5873A45, 0xE59E3A4F, 0xE5B53A59, 0xE5CC3A64, 0xE5E33A6E, 0xE5FA3A78, 0xE6113A82, 0xE6283A8D, 0xE63F3A97, 0xE6563AA1, 0xE66D3AAB, 0xE6843AB5, 0xE69B3ABF, 0xE6B23AC9, 0xE6C93AD3, 0xE6E03ADD, 0xE6F73AE6, 0xE70E3AF0, 0xE7253AFA, 0xE73D3B04, 0xE7543B0E, 0xE76B3B17, 0xE7823B21, 0xE7993B2A, 0xE7B13B34, 0xE7C83B3E, 0xE7DF3B47, 0xE7F63B50, 0xE80E3B5A, 0xE8253B63, 0xE83C3B6D, 0xE8543B76, 0xE86B3B7F, 0xE8823B88, 0xE89A3B92, 0xE8B13B9B, 0xE8C93BA4, 0xE8E03BAD, 0xE8F73BB6, 0xE90F3BBF, 0xE9263BC8, 0xE93E3BD1, 0xE9553BDA, 0xE96D3BE3, 0xE9843BEC, 0xE99C3BF5, 0xE9B43BFD, 0xE9CB3C06, 0xE9E33C0F, 0xE9FA3C17, 0xEA123C20, 0xEA293C29, 0xEA413C31, 0xEA593C3A, 0xEA703C42, 0xEA883C4B, 0xEAA03C53, 0xEAB73C5B, 0xEACF3C64, 0xEAE73C6C, 0xEAFF3C74, 0xEB163C7D, 0xEB2E3C85, 0xEB463C8D, 0xEB5E3C95, 0xEB753C9D, 0xEB8D3CA5, 0xEBA53CAD, 0xEBBD3CB5, 0xEBD53CBD, 0xEBED3CC5, 0xEC053CCD, 0xEC1C3CD5, 0xEC343CDD, 0xEC4C3CE4, 0xEC643CEC, 0xEC7C3CF4, 0xEC943CFB, 0xECAC3D03, 0xECC43D0B, 0xECDC3D12, 0xECF43D1A, 0xED0C3D21, 0xED243D28, 0xED3C3D30, 0xED543D37, 0xED6C3D3F, 0xED843D46, 0xED9C3D4D, 0xEDB43D54, 0xEDCC3D5B, 0xEDE43D63, 0xEDFC3D6A, 0xEE153D71, 0xEE2D3D78, 0xEE453D7F, 0xEE5D3D86, 0xEE753D8D, 0xEE8D3D93, 0xEEA63D9A, 0xEEBE3DA1, 0xEED63DA8, 0xEEEE3DAF, 0xEF063DB5, 0xEF1F3DBC, 0xEF373DC2, 0xEF4F3DC9, 0xEF673DD0, 0xEF803DD6, 0xEF983DDD, 0xEFB03DE3, 0xEFC93DE9, 0xEFE13DF0, 0xEFF93DF6, 0xF0123DFC, 0xF02A3E03, 0xF0423E09, 0xF05B3E0F, 0xF0733E15, 0xF08B3E1B, 0xF0A43E21, 0xF0BC3E27, 0xF0D53E2D, 0xF0ED3E33, 0xF1053E39, 0xF11E3E3F, 0xF1363E45, 0xF14F3E4A, 0xF1673E50, 0xF1803E56, 0xF1983E5C, 0xF1B13E61, 0xF1C93E67, 0xF1E23E6C, 0xF1FA3E72, 0xF2133E77, 0xF22B3E7D, 0xF2443E82, 0xF25C3E88, 0xF2753E8D, 0xF28E3E92, 0xF2A63E98, 0xF2BF3E9D, 0xF2D73EA2, 0xF2F03EA7, 0xF3083EAC, 0xF3213EB1, 0xF33A3EB6, 0xF3523EBB, 0xF36B3EC0, 0xF3843EC5, 0xF39C3ECA, 0xF3B53ECF, 0xF3CE3ED4, 0xF3E63ED8, 0xF3FF3EDD, 0xF4183EE2, 0xF4303EE7, 0xF4493EEB, 0xF4623EF0, 0xF47B3EF4, 0xF4933EF9, 0xF4AC3EFD, 0xF4C53F02, 0xF4DD3F06, 0xF4F63F0A, 0xF50F3F0F, 0xF5283F13, 0xF5403F17, 0xF5593F1C, 0xF5723F20, 0xF58B3F24, 0xF5A43F28, 0xF5BC3F2C, 0xF5D53F30, 0xF5EE3F34, 0xF6073F38, 0xF6203F3C, 0xF6393F40, 0xF6513F43, 0xF66A3F47, 0xF6833F4B, 0xF69C3F4F, 0xF6B53F52, 0xF6CE3F56, 0xF6E73F5A, 0xF6FF3F5D, 0xF7183F61, 0xF7313F64, 0xF74A3F68, 0xF7633F6B, 0xF77C3F6E, 0xF7953F72, 0xF7AE3F75, 0xF7C73F78, 0xF7E03F7B, 0xF7F93F7F, 0xF8113F82, 0xF82A3F85, 0xF8433F88, 0xF85C3F8B, 0xF8753F8E, 0xF88E3F91, 0xF8A73F94, 0xF8C03F97, 0xF8D93F99, 0xF8F23F9C, 0xF90B3F9F, 0xF9243FA2, 0xF93D3FA4, 0xF9563FA7, 0xF96F3FAA, 0xF9883FAC, 0xF9A13FAF, 0xF9BA3FB1, 0xF9D33FB4, 0xF9EC3FB6, 0xFA053FB8, 0xFA1E3FBB, 0xFA373FBD, 0xFA503FBF, 0xFA693FC1, 0xFA823FC4, 0xFA9B3FC6, 0xFAB43FC8, 0xFACD3FCA, 0xFAE63FCC, 0xFB003FCE, 0xFB193FD0, 0xFB323FD2, 0xFB4B3FD4, 0xFB643FD5, 0xFB7D3FD7, 0xFB963FD9, 0xFBAF3FDB, 0xFBC83FDC, 0xFBE13FDE, 0xFBFA3FE0, 0xFC133FE1, 0xFC2C3FE3, 0xFC453FE4, 0xFC5F3FE6, 0xFC783FE7, 0xFC913FE8, 0xFCAA3FEA, 0xFCC33FEB, 0xFCDC3FEC, 0xFCF53FED, 0xFD0E3FEF, 0xFD273FF0, 0xFD403FF1, 0xFD5A3FF2, 0xFD733FF3, 0xFD8C3FF4, 0xFDA53FF5, 0xFDBE3FF6, 0xFDD73FF7, 0xFDF03FF7, 0xFE093FF8, 0xFE233FF9, 0xFE3C3FFA, 0xFE553FFA, 0xFE6E3FFB, 0xFE873FFC, 0xFEA03FFC, 0xFEB93FFD, 0xFED23FFD, 0xFEEC3FFE, 0xFF053FFE, 0xFF1E3FFE, 0xFF373FFF, 0xFF503FFF, 0xFF693FFF, 0xFF824000, 0xFF9B4000, 0xFFB54000, 0xFFCE4000, 0xFFE74000, }; const int16 atanTable[2050] = { // ROM 0x0000, 0x0005, 0x000A, 0x000F, 0x0014, 0x0019, 0x001F, 0x0024, 0x0029, 0x002E, 0x0033, 0x0038, 0x003D, 0x0042, 0x0047, 0x004C, 0x0051, 0x0057, 0x005C, 0x0061, 0x0066, 0x006B, 0x0070, 0x0075, 0x007A, 0x007F, 0x0084, 0x008A, 0x008F, 0x0094, 0x0099, 0x009E, 0x00A3, 0x00A8, 0x00AD, 0x00B2, 0x00B7, 0x00BC, 0x00C2, 0x00C7, 0x00CC, 0x00D1, 0x00D6, 0x00DB, 0x00E0, 0x00E5, 0x00EA, 0x00EF, 0x00F4, 0x00FA, 0x00FF, 0x0104, 0x0109, 0x010E, 0x0113, 0x0118, 0x011D, 0x0122, 0x0127, 0x012C, 0x0131, 0x0137, 0x013C, 0x0141, 0x0146, 0x014B, 0x0150, 0x0155, 0x015A, 0x015F, 0x0164, 0x0169, 0x016F, 0x0174, 0x0179, 0x017E, 0x0183, 0x0188, 0x018D, 0x0192, 0x0197, 0x019C, 0x01A1, 0x01A6, 0x01AC, 0x01B1, 0x01B6, 0x01BB, 0x01C0, 0x01C5, 0x01CA, 0x01CF, 0x01D4, 0x01D9, 0x01DE, 0x01E3, 0x01E9, 0x01EE, 0x01F3, 0x01F8, 0x01FD, 0x0202, 0x0207, 0x020C, 0x0211, 0x0216, 0x021B, 0x0220, 0x0226, 0x022B, 0x0230, 0x0235, 0x023A, 0x023F, 0x0244, 0x0249, 0x024E, 0x0253, 0x0258, 0x025D, 0x0262, 0x0268, 0x026D, 0x0272, 0x0277, 0x027C, 0x0281, 0x0286, 0x028B, 0x0290, 0x0295, 0x029A, 0x029F, 0x02A4, 0x02A9, 0x02AF, 0x02B4, 0x02B9, 0x02BE, 0x02C3, 0x02C8, 0x02CD, 0x02D2, 0x02D7, 0x02DC, 0x02E1, 0x02E6, 0x02EB, 0x02F0, 0x02F6, 0x02FB, 0x0300, 0x0305, 0x030A, 0x030F, 0x0314, 0x0319, 0x031E, 0x0323, 0x0328, 0x032D, 0x0332, 0x0337, 0x033C, 0x0341, 0x0347, 0x034C, 0x0351, 0x0356, 0x035B, 0x0360, 0x0365, 0x036A, 0x036F, 0x0374, 0x0379, 0x037E, 0x0383, 0x0388, 0x038D, 0x0392, 0x0397, 0x039C, 0x03A2, 0x03A7, 0x03AC, 0x03B1, 0x03B6, 0x03BB, 0x03C0, 0x03C5, 0x03CA, 0x03CF, 0x03D4, 0x03D9, 0x03DE, 0x03E3, 0x03E8, 0x03ED, 0x03F2, 0x03F7, 0x03FC, 0x0401, 0x0407, 0x040C, 0x0411, 0x0416, 0x041B, 0x0420, 0x0425, 0x042A, 0x042F, 0x0434, 0x0439, 0x043E, 0x0443, 0x0448, 0x044D, 0x0452, 0x0457, 0x045C, 0x0461, 0x0466, 0x046B, 0x0470, 0x0475, 0x047A, 0x047F, 0x0484, 0x0489, 0x048E, 0x0494, 0x0499, 0x049E, 0x04A3, 0x04A8, 0x04AD, 0x04B2, 0x04B7, 0x04BC, 0x04C1, 0x04C6, 0x04CB, 0x04D0, 0x04D5, 0x04DA, 0x04DF, 0x04E4, 0x04E9, 0x04EE, 0x04F3, 0x04F8, 0x04FD, 0x0502, 0x0507, 0x050C, 0x0511, 0x0516, 0x051B, 0x0520, 0x0525, 0x052A, 0x052F, 0x0534, 0x0539, 0x053E, 0x0543, 0x0548, 0x054D, 0x0552, 0x0557, 0x055C, 0x0561, 0x0566, 0x056B, 0x0570, 0x0575, 0x057A, 0x057F, 0x0584, 0x0589, 0x058E, 0x0593, 0x0598, 0x059D, 0x05A2, 0x05A7, 0x05AC, 0x05B1, 0x05B6, 0x05BB, 0x05C0, 0x05C5, 0x05CA, 0x05CF, 0x05D4, 0x05D9, 0x05DE, 0x05E3, 0x05E8, 0x05ED, 0x05F2, 0x05F7, 0x05FC, 0x0601, 0x0606, 0x060B, 0x0610, 0x0615, 0x061A, 0x061F, 0x0624, 0x0629, 0x062E, 0x0633, 0x0638, 0x063D, 0x0642, 0x0647, 0x064C, 0x0651, 0x0656, 0x065B, 0x0660, 0x0665, 0x066A, 0x066E, 0x0673, 0x0678, 0x067D, 0x0682, 0x0687, 0x068C, 0x0691, 0x0696, 0x069B, 0x06A0, 0x06A5, 0x06AA, 0x06AF, 0x06B4, 0x06B9, 0x06BE, 0x06C3, 0x06C8, 0x06CD, 0x06D2, 0x06D7, 0x06DC, 0x06E1, 0x06E5, 0x06EA, 0x06EF, 0x06F4, 0x06F9, 0x06FE, 0x0703, 0x0708, 0x070D, 0x0712, 0x0717, 0x071C, 0x0721, 0x0726, 0x072B, 0x0730, 0x0735, 0x0739, 0x073E, 0x0743, 0x0748, 0x074D, 0x0752, 0x0757, 0x075C, 0x0761, 0x0766, 0x076B, 0x0770, 0x0775, 0x077A, 0x077E, 0x0783, 0x0788, 0x078D, 0x0792, 0x0797, 0x079C, 0x07A1, 0x07A6, 0x07AB, 0x07B0, 0x07B5, 0x07B9, 0x07BE, 0x07C3, 0x07C8, 0x07CD, 0x07D2, 0x07D7, 0x07DC, 0x07E1, 0x07E6, 0x07EB, 0x07EF, 0x07F4, 0x07F9, 0x07FE, 0x0803, 0x0808, 0x080D, 0x0812, 0x0817, 0x081C, 0x0820, 0x0825, 0x082A, 0x082F, 0x0834, 0x0839, 0x083E, 0x0843, 0x0848, 0x084C, 0x0851, 0x0856, 0x085B, 0x0860, 0x0865, 0x086A, 0x086F, 0x0873, 0x0878, 0x087D, 0x0882, 0x0887, 0x088C, 0x0891, 0x0896, 0x089A, 0x089F, 0x08A4, 0x08A9, 0x08AE, 0x08B3, 0x08B8, 0x08BD, 0x08C1, 0x08C6, 0x08CB, 0x08D0, 0x08D5, 0x08DA, 0x08DF, 0x08E3, 0x08E8, 0x08ED, 0x08F2, 0x08F7, 0x08FC, 0x0901, 0x0905, 0x090A, 0x090F, 0x0914, 0x0919, 0x091E, 0x0922, 0x0927, 0x092C, 0x0931, 0x0936, 0x093B, 0x093F, 0x0944, 0x0949, 0x094E, 0x0953, 0x0958, 0x095C, 0x0961, 0x0966, 0x096B, 0x0970, 0x0975, 0x0979, 0x097E, 0x0983, 0x0988, 0x098D, 0x0992, 0x0996, 0x099B, 0x09A0, 0x09A5, 0x09AA, 0x09AE, 0x09B3, 0x09B8, 0x09BD, 0x09C2, 0x09C6, 0x09CB, 0x09D0, 0x09D5, 0x09DA, 0x09DE, 0x09E3, 0x09E8, 0x09ED, 0x09F2, 0x09F6, 0x09FB, 0x0A00, 0x0A05, 0x0A0A, 0x0A0E, 0x0A13, 0x0A18, 0x0A1D, 0x0A22, 0x0A26, 0x0A2B, 0x0A30, 0x0A35, 0x0A39, 0x0A3E, 0x0A43, 0x0A48, 0x0A4D, 0x0A51, 0x0A56, 0x0A5B, 0x0A60, 0x0A64, 0x0A69, 0x0A6E, 0x0A73, 0x0A77, 0x0A7C, 0x0A81, 0x0A86, 0x0A8B, 0x0A8F, 0x0A94, 0x0A99, 0x0A9E, 0x0AA2, 0x0AA7, 0x0AAC, 0x0AB1, 0x0AB5, 0x0ABA, 0x0ABF, 0x0AC4, 0x0AC8, 0x0ACD, 0x0AD2, 0x0AD7, 0x0ADB, 0x0AE0, 0x0AE5, 0x0AE9, 0x0AEE, 0x0AF3, 0x0AF8, 0x0AFC, 0x0B01, 0x0B06, 0x0B0B, 0x0B0F, 0x0B14, 0x0B19, 0x0B1E, 0x0B22, 0x0B27, 0x0B2C, 0x0B30, 0x0B35, 0x0B3A, 0x0B3F, 0x0B43, 0x0B48, 0x0B4D, 0x0B51, 0x0B56, 0x0B5B, 0x0B60, 0x0B64, 0x0B69, 0x0B6E, 0x0B72, 0x0B77, 0x0B7C, 0x0B80, 0x0B85, 0x0B8A, 0x0B8F, 0x0B93, 0x0B98, 0x0B9D, 0x0BA1, 0x0BA6, 0x0BAB, 0x0BAF, 0x0BB4, 0x0BB9, 0x0BBD, 0x0BC2, 0x0BC7, 0x0BCB, 0x0BD0, 0x0BD5, 0x0BD9, 0x0BDE, 0x0BE3, 0x0BE7, 0x0BEC, 0x0BF1, 0x0BF5, 0x0BFA, 0x0BFF, 0x0C03, 0x0C08, 0x0C0D, 0x0C11, 0x0C16, 0x0C1B, 0x0C1F, 0x0C24, 0x0C29, 0x0C2D, 0x0C32, 0x0C37, 0x0C3B, 0x0C40, 0x0C45, 0x0C49, 0x0C4E, 0x0C53, 0x0C57, 0x0C5C, 0x0C60, 0x0C65, 0x0C6A, 0x0C6E, 0x0C73, 0x0C78, 0x0C7C, 0x0C81, 0x0C86, 0x0C8A, 0x0C8F, 0x0C93, 0x0C98, 0x0C9D, 0x0CA1, 0x0CA6, 0x0CAB, 0x0CAF, 0x0CB4, 0x0CB8, 0x0CBD, 0x0CC2, 0x0CC6, 0x0CCB, 0x0CCF, 0x0CD4, 0x0CD9, 0x0CDD, 0x0CE2, 0x0CE6, 0x0CEB, 0x0CF0, 0x0CF4, 0x0CF9, 0x0CFD, 0x0D02, 0x0D07, 0x0D0B, 0x0D10, 0x0D14, 0x0D19, 0x0D1E, 0x0D22, 0x0D27, 0x0D2B, 0x0D30, 0x0D34, 0x0D39, 0x0D3E, 0x0D42, 0x0D47, 0x0D4B, 0x0D50, 0x0D54, 0x0D59, 0x0D5E, 0x0D62, 0x0D67, 0x0D6B, 0x0D70, 0x0D74, 0x0D79, 0x0D7D, 0x0D82, 0x0D87, 0x0D8B, 0x0D90, 0x0D94, 0x0D99, 0x0D9D, 0x0DA2, 0x0DA6, 0x0DAB, 0x0DAF, 0x0DB4, 0x0DB9, 0x0DBD, 0x0DC2, 0x0DC6, 0x0DCB, 0x0DCF, 0x0DD4, 0x0DD8, 0x0DDD, 0x0DE1, 0x0DE6, 0x0DEA, 0x0DEF, 0x0DF3, 0x0DF8, 0x0DFC, 0x0E01, 0x0E05, 0x0E0A, 0x0E0F, 0x0E13, 0x0E18, 0x0E1C, 0x0E21, 0x0E25, 0x0E2A, 0x0E2E, 0x0E33, 0x0E37, 0x0E3C, 0x0E40, 0x0E45, 0x0E49, 0x0E4E, 0x0E52, 0x0E56, 0x0E5B, 0x0E5F, 0x0E64, 0x0E68, 0x0E6D, 0x0E71, 0x0E76, 0x0E7A, 0x0E7F, 0x0E83, 0x0E88, 0x0E8C, 0x0E91, 0x0E95, 0x0E9A, 0x0E9E, 0x0EA3, 0x0EA7, 0x0EAC, 0x0EB0, 0x0EB4, 0x0EB9, 0x0EBD, 0x0EC2, 0x0EC6, 0x0ECB, 0x0ECF, 0x0ED4, 0x0ED8, 0x0EDC, 0x0EE1, 0x0EE5, 0x0EEA, 0x0EEE, 0x0EF3, 0x0EF7, 0x0EFC, 0x0F00, 0x0F04, 0x0F09, 0x0F0D, 0x0F12, 0x0F16, 0x0F1B, 0x0F1F, 0x0F23, 0x0F28, 0x0F2C, 0x0F31, 0x0F35, 0x0F3A, 0x0F3E, 0x0F42, 0x0F47, 0x0F4B, 0x0F50, 0x0F54, 0x0F58, 0x0F5D, 0x0F61, 0x0F66, 0x0F6A, 0x0F6E, 0x0F73, 0x0F77, 0x0F7C, 0x0F80, 0x0F84, 0x0F89, 0x0F8D, 0x0F91, 0x0F96, 0x0F9A, 0x0F9F, 0x0FA3, 0x0FA7, 0x0FAC, 0x0FB0, 0x0FB5, 0x0FB9, 0x0FBD, 0x0FC2, 0x0FC6, 0x0FCA, 0x0FCF, 0x0FD3, 0x0FD7, 0x0FDC, 0x0FE0, 0x0FE5, 0x0FE9, 0x0FED, 0x0FF2, 0x0FF6, 0x0FFA, 0x0FFF, 0x1003, 0x1007, 0x100C, 0x1010, 0x1014, 0x1019, 0x101D, 0x1021, 0x1026, 0x102A, 0x102E, 0x1033, 0x1037, 0x103B, 0x1040, 0x1044, 0x1048, 0x104D, 0x1051, 0x1055, 0x105A, 0x105E, 0x1062, 0x1067, 0x106B, 0x106F, 0x1073, 0x1078, 0x107C, 0x1080, 0x1085, 0x1089, 0x108D, 0x1092, 0x1096, 0x109A, 0x109E, 0x10A3, 0x10A7, 0x10AB, 0x10B0, 0x10B4, 0x10B8, 0x10BC, 0x10C1, 0x10C5, 0x10C9, 0x10CE, 0x10D2, 0x10D6, 0x10DA, 0x10DF, 0x10E3, 0x10E7, 0x10EB, 0x10F0, 0x10F4, 0x10F8, 0x10FD, 0x1101, 0x1105, 0x1109, 0x110E, 0x1112, 0x1116, 0x111A, 0x111F, 0x1123, 0x1127, 0x112B, 0x1130, 0x1134, 0x1138, 0x113C, 0x1140, 0x1145, 0x1149, 0x114D, 0x1151, 0x1156, 0x115A, 0x115E, 0x1162, 0x1166, 0x116B, 0x116F, 0x1173, 0x1177, 0x117C, 0x1180, 0x1184, 0x1188, 0x118C, 0x1191, 0x1195, 0x1199, 0x119D, 0x11A1, 0x11A6, 0x11AA, 0x11AE, 0x11B2, 0x11B6, 0x11BB, 0x11BF, 0x11C3, 0x11C7, 0x11CB, 0x11CF, 0x11D4, 0x11D8, 0x11DC, 0x11E0, 0x11E4, 0x11E9, 0x11ED, 0x11F1, 0x11F5, 0x11F9, 0x11FD, 0x1202, 0x1206, 0x120A, 0x120E, 0x1212, 0x1216, 0x121A, 0x121F, 0x1223, 0x1227, 0x122B, 0x122F, 0x1233, 0x1237, 0x123C, 0x1240, 0x1244, 0x1248, 0x124C, 0x1250, 0x1254, 0x1259, 0x125D, 0x1261, 0x1265, 0x1269, 0x126D, 0x1271, 0x1275, 0x127A, 0x127E, 0x1282, 0x1286, 0x128A, 0x128E, 0x1292, 0x1296, 0x129A, 0x129F, 0x12A3, 0x12A7, 0x12AB, 0x12AF, 0x12B3, 0x12B7, 0x12BB, 0x12BF, 0x12C3, 0x12C7, 0x12CC, 0x12D0, 0x12D4, 0x12D8, 0x12DC, 0x12E0, 0x12E4, 0x12E8, 0x12EC, 0x12F0, 0x12F4, 0x12F8, 0x12FC, 0x1301, 0x1305, 0x1309, 0x130D, 0x1311, 0x1315, 0x1319, 0x131D, 0x1321, 0x1325, 0x1329, 0x132D, 0x1331, 0x1335, 0x1339, 0x133D, 0x1341, 0x1345, 0x1349, 0x134D, 0x1351, 0x1355, 0x135A, 0x135E, 0x1362, 0x1366, 0x136A, 0x136E, 0x1372, 0x1376, 0x137A, 0x137E, 0x1382, 0x1386, 0x138A, 0x138E, 0x1392, 0x1396, 0x139A, 0x139E, 0x13A2, 0x13A6, 0x13AA, 0x13AE, 0x13B2, 0x13B6, 0x13BA, 0x13BE, 0x13C2, 0x13C6, 0x13CA, 0x13CE, 0x13D2, 0x13D6, 0x13DA, 0x13DE, 0x13E2, 0x13E6, 0x13E9, 0x13ED, 0x13F1, 0x13F5, 0x13F9, 0x13FD, 0x1401, 0x1405, 0x1409, 0x140D, 0x1411, 0x1415, 0x1419, 0x141D, 0x1421, 0x1425, 0x1429, 0x142D, 0x1431, 0x1435, 0x1439, 0x143D, 0x1440, 0x1444, 0x1448, 0x144C, 0x1450, 0x1454, 0x1458, 0x145C, 0x1460, 0x1464, 0x1468, 0x146C, 0x1470, 0x1473, 0x1477, 0x147B, 0x147F, 0x1483, 0x1487, 0x148B, 0x148F, 0x1493, 0x1497, 0x149B, 0x149E, 0x14A2, 0x14A6, 0x14AA, 0x14AE, 0x14B2, 0x14B6, 0x14BA, 0x14BE, 0x14C1, 0x14C5, 0x14C9, 0x14CD, 0x14D1, 0x14D5, 0x14D9, 0x14DD, 0x14E0, 0x14E4, 0x14E8, 0x14EC, 0x14F0, 0x14F4, 0x14F8, 0x14FB, 0x14FF, 0x1503, 0x1507, 0x150B, 0x150F, 0x1513, 0x1516, 0x151A, 0x151E, 0x1522, 0x1526, 0x152A, 0x152D, 0x1531, 0x1535, 0x1539, 0x153D, 0x1541, 0x1544, 0x1548, 0x154C, 0x1550, 0x1554, 0x1558, 0x155B, 0x155F, 0x1563, 0x1567, 0x156B, 0x156E, 0x1572, 0x1576, 0x157A, 0x157E, 0x1581, 0x1585, 0x1589, 0x158D, 0x1591, 0x1594, 0x1598, 0x159C, 0x15A0, 0x15A4, 0x15A7, 0x15AB, 0x15AF, 0x15B3, 0x15B7, 0x15BA, 0x15BE, 0x15C2, 0x15C6, 0x15C9, 0x15CD, 0x15D1, 0x15D5, 0x15D8, 0x15DC, 0x15E0, 0x15E4, 0x15E8, 0x15EB, 0x15EF, 0x15F3, 0x15F7, 0x15FA, 0x15FE, 0x1602, 0x1606, 0x1609, 0x160D, 0x1611, 0x1614, 0x1618, 0x161C, 0x1620, 0x1623, 0x1627, 0x162B, 0x162F, 0x1632, 0x1636, 0x163A, 0x163E, 0x1641, 0x1645, 0x1649, 0x164C, 0x1650, 0x1654, 0x1658, 0x165B, 0x165F, 0x1663, 0x1666, 0x166A, 0x166E, 0x1671, 0x1675, 0x1679, 0x167D, 0x1680, 0x1684, 0x1688, 0x168B, 0x168F, 0x1693, 0x1696, 0x169A, 0x169E, 0x16A1, 0x16A5, 0x16A9, 0x16AC, 0x16B0, 0x16B4, 0x16B7, 0x16BB, 0x16BF, 0x16C2, 0x16C6, 0x16CA, 0x16CD, 0x16D1, 0x16D5, 0x16D8, 0x16DC, 0x16E0, 0x16E3, 0x16E7, 0x16EB, 0x16EE, 0x16F2, 0x16F6, 0x16F9, 0x16FD, 0x1700, 0x1704, 0x1708, 0x170B, 0x170F, 0x1713, 0x1716, 0x171A, 0x171D, 0x1721, 0x1725, 0x1728, 0x172C, 0x1730, 0x1733, 0x1737, 0x173A, 0x173E, 0x1742, 0x1745, 0x1749, 0x174C, 0x1750, 0x1754, 0x1757, 0x175B, 0x175E, 0x1762, 0x1766, 0x1769, 0x176D, 0x1770, 0x1774, 0x1778, 0x177B, 0x177F, 0x1782, 0x1786, 0x1789, 0x178D, 0x1791, 0x1794, 0x1798, 0x179B, 0x179F, 0x17A2, 0x17A6, 0x17AA, 0x17AD, 0x17B1, 0x17B4, 0x17B8, 0x17BB, 0x17BF, 0x17C2, 0x17C6, 0x17C9, 0x17CD, 0x17D1, 0x17D4, 0x17D8, 0x17DB, 0x17DF, 0x17E2, 0x17E6, 0x17E9, 0x17ED, 0x17F0, 0x17F4, 0x17F7, 0x17FB, 0x17FE, 0x1802, 0x1806, 0x1809, 0x180D, 0x1810, 0x1814, 0x1817, 0x181B, 0x181E, 0x1822, 0x1825, 0x1829, 0x182C, 0x1830, 0x1833, 0x1837, 0x183A, 0x183E, 0x1841, 0x1845, 0x1848, 0x184C, 0x184F, 0x1853, 0x1856, 0x185A, 0x185D, 0x1860, 0x1864, 0x1867, 0x186B, 0x186E, 0x1872, 0x1875, 0x1879, 0x187C, 0x1880, 0x1883, 0x1887, 0x188A, 0x188E, 0x1891, 0x1894, 0x1898, 0x189B, 0x189F, 0x18A2, 0x18A6, 0x18A9, 0x18AD, 0x18B0, 0x18B3, 0x18B7, 0x18BA, 0x18BE, 0x18C1, 0x18C5, 0x18C8, 0x18CC, 0x18CF, 0x18D2, 0x18D6, 0x18D9, 0x18DD, 0x18E0, 0x18E3, 0x18E7, 0x18EA, 0x18EE, 0x18F1, 0x18F5, 0x18F8, 0x18FB, 0x18FF, 0x1902, 0x1906, 0x1909, 0x190C, 0x1910, 0x1913, 0x1917, 0x191A, 0x191D, 0x1921, 0x1924, 0x1928, 0x192B, 0x192E, 0x1932, 0x1935, 0x1938, 0x193C, 0x193F, 0x1943, 0x1946, 0x1949, 0x194D, 0x1950, 0x1953, 0x1957, 0x195A, 0x195D, 0x1961, 0x1964, 0x1968, 0x196B, 0x196E, 0x1972, 0x1975, 0x1978, 0x197C, 0x197F, 0x1982, 0x1986, 0x1989, 0x198C, 0x1990, 0x1993, 0x1996, 0x199A, 0x199D, 0x19A0, 0x19A4, 0x19A7, 0x19AA, 0x19AE, 0x19B1, 0x19B4, 0x19B8, 0x19BB, 0x19BE, 0x19C2, 0x19C5, 0x19C8, 0x19CC, 0x19CF, 0x19D2, 0x19D5, 0x19D9, 0x19DC, 0x19DF, 0x19E3, 0x19E6, 0x19E9, 0x19ED, 0x19F0, 0x19F3, 0x19F6, 0x19FA, 0x19FD, 0x1A00, 0x1A04, 0x1A07, 0x1A0A, 0x1A0D, 0x1A11, 0x1A14, 0x1A17, 0x1A1B, 0x1A1E, 0x1A21, 0x1A24, 0x1A28, 0x1A2B, 0x1A2E, 0x1A31, 0x1A35, 0x1A38, 0x1A3B, 0x1A3E, 0x1A42, 0x1A45, 0x1A48, 0x1A4B, 0x1A4F, 0x1A52, 0x1A55, 0x1A58, 0x1A5C, 0x1A5F, 0x1A62, 0x1A65, 0x1A69, 0x1A6C, 0x1A6F, 0x1A72, 0x1A76, 0x1A79, 0x1A7C, 0x1A7F, 0x1A83, 0x1A86, 0x1A89, 0x1A8C, 0x1A8F, 0x1A93, 0x1A96, 0x1A99, 0x1A9C, 0x1A9F, 0x1AA3, 0x1AA6, 0x1AA9, 0x1AAC, 0x1AB0, 0x1AB3, 0x1AB6, 0x1AB9, 0x1ABC, 0x1AC0, 0x1AC3, 0x1AC6, 0x1AC9, 0x1ACC, 0x1ACF, 0x1AD3, 0x1AD6, 0x1AD9, 0x1ADC, 0x1ADF, 0x1AE3, 0x1AE6, 0x1AE9, 0x1AEC, 0x1AEF, 0x1AF2, 0x1AF6, 0x1AF9, 0x1AFC, 0x1AFF, 0x1B02, 0x1B05, 0x1B09, 0x1B0C, 0x1B0F, 0x1B12, 0x1B15, 0x1B18, 0x1B1C, 0x1B1F, 0x1B22, 0x1B25, 0x1B28, 0x1B2B, 0x1B2E, 0x1B32, 0x1B35, 0x1B38, 0x1B3B, 0x1B3E, 0x1B41, 0x1B44, 0x1B48, 0x1B4B, 0x1B4E, 0x1B51, 0x1B54, 0x1B57, 0x1B5A, 0x1B5D, 0x1B61, 0x1B64, 0x1B67, 0x1B6A, 0x1B6D, 0x1B70, 0x1B73, 0x1B76, 0x1B79, 0x1B7D, 0x1B80, 0x1B83, 0x1B86, 0x1B89, 0x1B8C, 0x1B8F, 0x1B92, 0x1B95, 0x1B98, 0x1B9C, 0x1B9F, 0x1BA2, 0x1BA5, 0x1BA8, 0x1BAB, 0x1BAE, 0x1BB1, 0x1BB4, 0x1BB7, 0x1BBA, 0x1BBD, 0x1BC1, 0x1BC4, 0x1BC7, 0x1BCA, 0x1BCD, 0x1BD0, 0x1BD3, 0x1BD6, 0x1BD9, 0x1BDC, 0x1BDF, 0x1BE2, 0x1BE5, 0x1BE8, 0x1BEB, 0x1BEE, 0x1BF2, 0x1BF5, 0x1BF8, 0x1BFB, 0x1BFE, 0x1C01, 0x1C04, 0x1C07, 0x1C0A, 0x1C0D, 0x1C10, 0x1C13, 0x1C16, 0x1C19, 0x1C1C, 0x1C1F, 0x1C22, 0x1C25, 0x1C28, 0x1C2B, 0x1C2E, 0x1C31, 0x1C34, 0x1C37, 0x1C3A, 0x1C3D, 0x1C40, 0x1C43, 0x1C46, 0x1C49, 0x1C4C, 0x1C4F, 0x1C52, 0x1C55, 0x1C58, 0x1C5B, 0x1C5E, 0x1C61, 0x1C64, 0x1C67, 0x1C6A, 0x1C6D, 0x1C70, 0x1C73, 0x1C76, 0x1C79, 0x1C7C, 0x1C7F, 0x1C82, 0x1C85, 0x1C88, 0x1C8B, 0x1C8E, 0x1C91, 0x1C94, 0x1C97, 0x1C9A, 0x1C9D, 0x1CA0, 0x1CA3, 0x1CA6, 0x1CA9, 0x1CAC, 0x1CAF, 0x1CB2, 0x1CB5, 0x1CB8, 0x1CBB, 0x1CBE, 0x1CC1, 0x1CC3, 0x1CC6, 0x1CC9, 0x1CCC, 0x1CCF, 0x1CD2, 0x1CD5, 0x1CD8, 0x1CDB, 0x1CDE, 0x1CE1, 0x1CE4, 0x1CE7, 0x1CEA, 0x1CED, 0x1CF0, 0x1CF3, 0x1CF5, 0x1CF8, 0x1CFB, 0x1CFE, 0x1D01, 0x1D04, 0x1D07, 0x1D0A, 0x1D0D, 0x1D10, 0x1D13, 0x1D16, 0x1D18, 0x1D1B, 0x1D1E, 0x1D21, 0x1D24, 0x1D27, 0x1D2A, 0x1D2D, 0x1D30, 0x1D33, 0x1D35, 0x1D38, 0x1D3B, 0x1D3E, 0x1D41, 0x1D44, 0x1D47, 0x1D4A, 0x1D4D, 0x1D4F, 0x1D52, 0x1D55, 0x1D58, 0x1D5B, 0x1D5E, 0x1D61, 0x1D64, 0x1D66, 0x1D69, 0x1D6C, 0x1D6F, 0x1D72, 0x1D75, 0x1D78, 0x1D7B, 0x1D7D, 0x1D80, 0x1D83, 0x1D86, 0x1D89, 0x1D8C, 0x1D8E, 0x1D91, 0x1D94, 0x1D97, 0x1D9A, 0x1D9D, 0x1DA0, 0x1DA2, 0x1DA5, 0x1DA8, 0x1DAB, 0x1DAE, 0x1DB1, 0x1DB3, 0x1DB6, 0x1DB9, 0x1DBC, 0x1DBF, 0x1DC2, 0x1DC4, 0x1DC7, 0x1DCA, 0x1DCD, 0x1DD0, 0x1DD3, 0x1DD5, 0x1DD8, 0x1DDB, 0x1DDE, 0x1DE1, 0x1DE3, 0x1DE6, 0x1DE9, 0x1DEC, 0x1DEF, 0x1DF1, 0x1DF4, 0x1DF7, 0x1DFA, 0x1DFD, 0x1DFF, 0x1E02, 0x1E05, 0x1E08, 0x1E0B, 0x1E0D, 0x1E10, 0x1E13, 0x1E16, 0x1E19, 0x1E1B, 0x1E1E, 0x1E21, 0x1E24, 0x1E26, 0x1E29, 0x1E2C, 0x1E2F, 0x1E32, 0x1E34, 0x1E37, 0x1E3A, 0x1E3D, 0x1E3F, 0x1E42, 0x1E45, 0x1E48, 0x1E4A, 0x1E4D, 0x1E50, 0x1E53, 0x1E55, 0x1E58, 0x1E5B, 0x1E5E, 0x1E60, 0x1E63, 0x1E66, 0x1E69, 0x1E6B, 0x1E6E, 0x1E71, 0x1E74, 0x1E76, 0x1E79, 0x1E7C, 0x1E7F, 0x1E81, 0x1E84, 0x1E87, 0x1E8A, 0x1E8C, 0x1E8F, 0x1E92, 0x1E94, 0x1E97, 0x1E9A, 0x1E9D, 0x1E9F, 0x1EA2, 0x1EA5, 0x1EA8, 0x1EAA, 0x1EAD, 0x1EB0, 0x1EB2, 0x1EB5, 0x1EB8, 0x1EBA, 0x1EBD, 0x1EC0, 0x1EC3, 0x1EC5, 0x1EC8, 0x1ECB, 0x1ECD, 0x1ED0, 0x1ED3, 0x1ED5, 0x1ED8, 0x1EDB, 0x1EDE, 0x1EE0, 0x1EE3, 0x1EE6, 0x1EE8, 0x1EEB, 0x1EEE, 0x1EF0, 0x1EF3, 0x1EF6, 0x1EF8, 0x1EFB, 0x1EFE, 0x1F00, 0x1F03, 0x1F06, 0x1F08, 0x1F0B, 0x1F0E, 0x1F10, 0x1F13, 0x1F16, 0x1F18, 0x1F1B, 0x1F1E, 0x1F20, 0x1F23, 0x1F26, 0x1F28, 0x1F2B, 0x1F2E, 0x1F30, 0x1F33, 0x1F36, 0x1F38, 0x1F3B, 0x1F3D, 0x1F40, 0x1F43, 0x1F45, 0x1F48, 0x1F4B, 0x1F4D, 0x1F50, 0x1F53, 0x1F55, 0x1F58, 0x1F5A, 0x1F5D, 0x1F60, 0x1F62, 0x1F65, 0x1F68, 0x1F6A, 0x1F6D, 0x1F6F, 0x1F72, 0x1F75, 0x1F77, 0x1F7A, 0x1F7C, 0x1F7F, 0x1F82, 0x1F84, 0x1F87, 0x1F8A, 0x1F8C, 0x1F8F, 0x1F91, 0x1F94, 0x1F97, 0x1F99, 0x1F9C, 0x1F9E, 0x1FA1, 0x1FA4, 0x1FA6, 0x1FA9, 0x1FAB, 0x1FAE, 0x1FB0, 0x1FB3, 0x1FB6, 0x1FB8, 0x1FBB, 0x1FBD, 0x1FC0, 0x1FC3, 0x1FC5, 0x1FC8, 0x1FCA, 0x1FCD, 0x1FCF, 0x1FD2, 0x1FD5, 0x1FD7, 0x1FDA, 0x1FDC, 0x1FDF, 0x1FE1, 0x1FE4, 0x1FE6, 0x1FE9, 0x1FEC, 0x1FEE, 0x1FF1, 0x1FF3, 0x1FF6, 0x1FF8, 0x1FFB, 0x1FFD, 0x2000, 0x2000, }; const int32 atanOctant[] = { 0, -16384, -65535, 49152, -32768, 16384, 32768, -49152 }; int32 phd_atan(int32 x, int32 y) { if (x == 0 && y == 0) return 0; int32 o = 0; if (x < 0) { o += 4; x = -x; } if (y < 0) { o += 2; y = -y; } if (y > x) { o++; swap(x, y); } return abs(atanTable[(y << 11) / x] + atanOctant[o]); } uint32 phd_sqrt(uint32 x) { uint32 m = 0x40000000; uint32 y = 0; uint32 z = 0; do { y += m; if (y > x) { y = z; } else { x -= y; y = z + m; } z = y >> 1; } while (m >>= 2); return y; } void anglesFromVector(int32 x, int32 y, int32 z, int16 &angleX, int16 &angleY) { angleY = phd_atan(z, x); angleX = phd_atan(phd_sqrt(x * x + z * z), -y); } bool boxIntersect(const AABBi &a, const AABBi &b) { return !(a.maxX <= b.minX || a.minX >= b.maxX || a.maxY <= b.minY || a.minY >= b.maxY || a.maxZ <= b.minZ || a.minZ >= b.maxZ); } bool boxContains(const AABBi &a, const vec3i &p) { return !(a.minX > p.x || a.maxX < p.x || a.minY > p.y || a.maxY < p.y || a.minZ > p.z || a.maxZ < p.z); } vec3i boxPushOut(const AABBi &a, const AABBi &b) { int32 ax = b.maxX - a.minX; int32 bx = a.maxX - b.minX; int32 az = b.maxZ - a.minZ; int32 bz = a.maxZ - b.minZ; vec3i p; p.y = 0; p.x = (ax < bx) ? -ax : bx; p.z = (az < bz) ? -az : bz; return p; } /* #ifdef USE_DIV_TABLE void initDivTable() { uint16 divTable[DIV_TABLE_SIZE]; divTable[0] = 0xFFFF; divTable[1] = 0xFFFF; for (uint32 i = 2; i < DIV_TABLE_SIZE; i++) { divTable[i] = (1 << 16) / i; } ASSERT((DIV_TABLE_SIZE & 8) == 0) printf("const uint16 divTable[DIV_TABLE_SIZE] = {\n"); for (int i = 0; i < DIV_TABLE_SIZE; i += 8) { printf(" 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X,\n", divTable[i + 0], divTable[i + 1], divTable[i + 2], divTable[i + 3], divTable[i + 4], divTable[i + 5], divTable[i + 6], divTable[i + 7]); } printf("};\n"); } #endif */ X_INLINE int16 lerpAngle(int16 a, int16 b, int32 t) { int32 d = b - a; if (d > 0x8000) { d -= 0x10000; } else if (d < -0x8000) { d += 0x10000; } return a + ((d * t) >> FIXED_SHIFT); } X_INLINE int16 lerpAngleSlow(int16 a, int16 b, int32 mul, int32 div) { int32 d = b - a; if (d > 0x8000) { d -= 0x10000; } else if (d < -0x8000) { d += 0x10000; } return a + d * mul / div; } #ifndef USE_ASM void matrixPush_c() { ASSERT(gMatrixPtr - gMatrixStack < MAX_MATRICES); memcpy(gMatrixPtr + 1, gMatrixPtr, sizeof(Matrix)); gMatrixPtr++; } void matrixSetIdentity_c() { Matrix &m = matrixGet(); m.e00 = 0x4000; m.e01 = 0; m.e02 = 0; m.e03 = 0; m.e10 = 0; m.e11 = 0x4000; m.e12 = 0; m.e13 = 0; m.e20 = 0; m.e21 = 0; m.e22 = 0x4000; m.e23 = 0; } void matrixSetBasis_c(Matrix &dst, const Matrix &src) { dst.e00 = src.e00; dst.e01 = src.e01; dst.e02 = src.e02; dst.e10 = src.e10; dst.e11 = src.e11; dst.e12 = src.e12; dst.e10 = src.e10; dst.e11 = src.e11; dst.e12 = src.e12; } #define LERP_1_2(a, b) a = (b + a) >> 1 #define LERP_1_3(a, b) a = a + (b - a) / 3 #define LERP_2_3(a, b) a = b - (b - a) / 3 #define LERP_1_4(a, b) a = a + ((b - a) >> 2) #define LERP_3_4(a, b) a = b - ((b - a) >> 2) #define LERP_1_5(a, b) a = a + (b - a) / 5 #define LERP_2_5(a, b) a = a + ((b - a) << 1) / 5 #define LERP_3_5(a, b) a = b - ((b - a) << 1) / 5 #define LERP_4_5(a, b) a = b - (b - a) / 5 #define LERP_SLOW(a, b) a = a + ((b - a) * t >> 8) #define LERP_ROW(lerp_func, a, b, row) \ lerp_func(a.e##row##0, b.e##row##0); \ lerp_func(a.e##row##1, b.e##row##1); \ lerp_func(a.e##row##2, b.e##row##2); \ lerp_func(a.e##row##3, b.e##row##3); #define LERP_MATRIX(lerp_func) \ LERP_ROW(lerp_func, m, n, 0); \ LERP_ROW(lerp_func, m, n, 1); \ LERP_ROW(lerp_func, m, n, 2); void matrixLerp_c(const Matrix &n, int32 pmul, int32 pdiv) { Matrix &m = matrixGet(); if ((pdiv == 2) || ((pdiv == 4) && (pmul == 2))) { LERP_MATRIX(LERP_1_2); } else if (pdiv == 4) { if (pmul == 1) { LERP_MATRIX(LERP_1_4); } else { LERP_MATRIX(LERP_3_4); } } else { int32 t = pmul * FixedInvU(pdiv) >> 8; LERP_MATRIX(LERP_SLOW); } } #define MATRIX_TRANS(x,y,z)\ Matrix &m = matrixGet();\ int32 tx = DP33(m.e00, m.e01, m.e02, x, y, z);\ int32 ty = DP33(m.e10, m.e11, m.e12, x, y, z);\ int32 tz = DP33(m.e20, m.e21, m.e22, x, y, z); void matrixTranslateRel_c(int32 x, int32 y, int32 z) { MATRIX_TRANS(x, y, z); m.e03 += tx; m.e13 += ty; m.e23 += tz; } void matrixTranslateAbs_c(int32 x, int32 y, int32 z) { x -= gCameraViewPos.x; y -= gCameraViewPos.y; z -= gCameraViewPos.z; MATRIX_TRANS(x, y, z); m.e03 = tx; m.e13 = ty; m.e23 = tz; } void matrixTranslateSet_c(int32 x, int32 y, int32 z) { MATRIX_TRANS(x, y, z); m.e03 = tx; m.e13 = ty; m.e23 = tz; } void matrixRotateX_c(int32 angle) { int32 s, c; sincos(angle, s, c); Matrix &m = matrixGet(); X_ROTXY(m.e02, m.e01, s, c); X_ROTXY(m.e12, m.e11, s, c); X_ROTXY(m.e22, m.e21, s, c); } void matrixRotateY_c(int32 angle) { int32 s, c; sincos(angle, s, c); Matrix &m = matrixGet(); X_ROTXY(m.e00, m.e02, s, c); X_ROTXY(m.e10, m.e12, s, c); X_ROTXY(m.e20, m.e22, s, c); } void matrixRotateZ_c(int32 angle) { int32 s, c; sincos(angle, s, c); Matrix &m = matrixGet(); X_ROTXY(m.e01, m.e00, s, c); X_ROTXY(m.e11, m.e10, s, c); X_ROTXY(m.e21, m.e20, s, c); } void matrixRotateYQ_c(int32 quadrant) { if (quadrant == 2) return; Matrix &m = matrixGet(); if (quadrant == 0) { m.e00 = -m.e00; m.e10 = -m.e10; m.e20 = -m.e20; m.e02 = -m.e02; m.e12 = -m.e12; m.e22 = -m.e22; } else if (quadrant == 1) { int32 e0 = m.e02; int32 e1 = m.e12; int32 e2 = m.e22; m.e02 = -m.e00; m.e12 = -m.e10; m.e22 = -m.e20; m.e00 = e0; m.e10 = e1; m.e20 = e2; } else { int32 e0 = m.e02; int32 e1 = m.e12; int32 e2 = m.e22; m.e02 = m.e00; m.e12 = m.e10; m.e22 = m.e20; m.e00 = -e0; m.e10 = -e1; m.e20 = -e2; } } void matrixRotateYXZ_c(int32 angleX, int32 angleY, int32 angleZ) { if (angleY) matrixRotateY(angleY); if (angleX) matrixRotateX(angleX); if (angleZ) matrixRotateZ(angleZ); } void boxTranslate_c(AABBi &box, int32 x, int32 y, int32 z) { box.minX += x; box.maxX += x; box.minY += y; box.maxY += y; box.minZ += z; box.maxZ += z; } void boxRotateYQ_c(AABBi &box, int32 quadrant) { if (quadrant == 2) return; int32 minX = box.minX; int32 maxX = box.maxX; int32 minZ = box.minZ; int32 maxZ = box.maxZ; if (quadrant == 3) { box.minX = minZ; box.maxX = maxZ; box.minZ = -maxX; box.maxZ = -minX; } else if (quadrant == 1) { box.minX = -maxZ; box.maxX = -minZ; box.minZ = minX; box.maxZ = maxX; } else if (quadrant == 0) { box.minX = -maxX; box.maxX = -minX; box.minZ = -maxZ; box.maxZ = -minZ; } } #endif void matrixFrame(const void* pos, const void* angles) { int16 aX, aY, aZ; DECODE_ANGLES(*(uint32*)angles, aX, aY, aZ); uint32 xy = ((uint32*)pos)[0]; uint32 zu = ((uint32*)pos)[1]; #ifdef CPU_BIG_ENDIAN int32 posX = int16(xy >> 16); int32 posY = int16(xy & 0xFFFF); int32 posZ = int16(zu >> 16); #else int32 posX = int16(xy & 0xFFFF); int32 posY = int16(xy >> 16); int32 posZ = int16(zu & 0xFFFF); #endif matrixTranslateRel(posX, posY, posZ); matrixRotateYXZ(aX, aY, aZ); } void matrixFrameLerp(const void* pos, const void* anglesA, const void* anglesB, int32 delta, int32 rate) { int16 aX, aY, aZ; int16 bX, bY, bZ; DECODE_ANGLES(*(uint32*)anglesA, aX, aY, aZ); DECODE_ANGLES(*(uint32*)anglesB, bX, bY, bZ); uint32 xy = ((uint32*)pos)[0]; uint32 zu = ((uint32*)pos)[1]; #ifdef CPU_BIG_ENDIAN int32 posX = int16(xy >> 16); int32 posY = int16(xy & 0xFFFF); int32 posZ = int16(zu >> 16); #else int32 posX = int16(xy & 0xFFFF); int32 posY = int16(xy >> 16); int32 posZ = int16(zu & 0xFFFF); #endif matrixTranslateRel(posX, posY, posZ); matrixPush(); matrixRotateYXZ(bX, bY, bZ); matrixPop(); matrixRotateYXZ(aX, aY, aZ); matrixLerp(*(gMatrixPtr + 1), delta, rate); } void matrixSetView(const vec3i &pos, int32 angleX, int32 angleY) { int32 sx, cx; int32 sy, cy; sincos(angleX, sx, cx); sincos(angleY, sy, cy); Matrix &m = matrixGet(); m.e00 = cy; m.e01 = 0; m.e02 = -sy; m.e03 = 0; m.e10 = (sx * sy) >> FIXED_SHIFT; m.e11 = cx; m.e12 = (sx * cy) >> FIXED_SHIFT; m.e13 = 0; m.e20 = (cx * sy) >> FIXED_SHIFT; m.e21 = -sx; m.e22 = (cx * cy) >> FIXED_SHIFT; m.e23 = 0; gCameraViewPos = pos; } void CollisionInfo::setSide(CollisionInfo::SideType st, int32 floor, int32 ceiling) { SlantType slantType; if (FD_SLANT_X(gLastFloorSlant) == 0 && FD_SLANT_Z(gLastFloorSlant) == 0) { slantType = SLANT_NONE; } else if (abs(FD_SLANT_X(gLastFloorSlant)) < 3 && abs(FD_SLANT_Z(gLastFloorSlant)) < 3) { slantType = SLANT_LOW; } else { slantType = SLANT_HIGH; } if (st != ST_MIDDLE) { if (stopOnSlant && floor < 0 && slantType == SLANT_HIGH) { floor = -0x7FFF; } else if (stopOnSlant && floor > 0 && slantType == SLANT_HIGH) { floor = 512; }/* TODO lava else if (stopOnLava && floor > 0 && trigger && FloorData(*(uint16*)trigger).cmd.func == FloorData::LAVA) { floor = 512; }*/ } Side *s = &m + st; s->slantType = slantType; s->floor = floor; s->ceiling = ceiling; } void palGamma(const uint16* srcPal, uint16* dstPal, int32 value) { for (int32 i = 0; i < 256; i++) { uint16 src = *srcPal++; int32 r = 31 & (src); int32 g = 31 & (src >> 5); int32 b = 31 & (src >> 10); r = X_MIN(31, r + (((r * r >> 2) - r) * value >> 10)); g = X_MIN(31, g + (((g * g >> 2) - g) * value >> 10)); b = X_MIN(31, b + (((b * b >> 2) - b) * value >> 10)); *dstPal++ = r | (g << 5) | (b << 10); } } void palBright(const uint16* srcPal, uint16* dstPal, int32 value) { value >>= 2; for (int32 i = 0; i < 256; i++) { uint16 src = *srcPal++; int32 r = 31 & (src); int32 g = 31 & (src >> 5); int32 b = 31 & (src >> 10); r = X_CLAMP(r + value, 0, 31); g = X_CLAMP(g + value, 0, 31); b = X_CLAMP(b + value, 0, 31); *dstPal++ = r | (g << 5) | (b << 10); } } void palGrayRemap(uint8* data, int32 size) { static const uint8 grad[8] = { 1, 22, 21, 20, 19, 18, 17, 33 }; uint8 remap[256]; for (int32 i = 0; i < 256; i++) { uint16 p = level.palette[i]; uint8 r = (p & 31); uint8 g = ((p >> 5) & 31); uint8 b = ((p >> 10) & 31); int32 lum = (r * 77 + g * 150 + b * 29) >> (8 + 2); remap[i] = grad[lum]; } for (int32 i = 0; i < size; i++) { data[i] = remap[data[i]]; } } void palSet(const uint16* palette, int32 gamma, int32 bright) { const uint16* pal = palette; if (gamma || bright) { uint16 tmp[256]; if (gamma) { palGamma(pal, tmp, gamma); pal = tmp; } if (bright) { palBright(pal, tmp, bright); pal = tmp; } } osSetPalette(pal); } void dmaFill(void* dst, uint8 value, uint32 count) { ASSERT((count & 3) == 0); #ifdef __GBA__ vu32 v = value; dma3_fill(dst, v, count); #else memset(dst, value, count); #endif } #ifndef __NDS__ void dmaCopy(const void* src, void* dst, uint32 size) { ASSERT((size & 3) == 0); #ifdef __GBA__ dma3_cpy(dst, src, size); #else memcpy(dst, src, size); #endif } #endif
// RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %s -o %t.out // RUN: %HOST_RUN_PLACEHOLDER %t.out // RUN: %CPU_RUN_PLACEHOLDER %t.out // RUN: %GPU_RUN_PLACEHOLDER %t.out // RUN: %ACC_RUN_PLACEHOLDER %t.out // // Missing __spirv_SubgroupLocalInvocationId on AMD // XFAIL: hip_amd //==---------- barrier.cpp - SYCL sub_group barrier test -------*- C++ -*---==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "helper.hpp" #include <CL/sycl.hpp> #include <limits> #include <numeric> template <typename T, bool UseNewSyntax> class sycl_subgr; using namespace cl::sycl; template <typename T, bool UseNewSyntax = false> void check(queue &Queue, size_t G = 240, size_t L = 60) { try { nd_range<1> NdRange(G, L); std::vector<T> data(G); std::iota(data.begin(), data.end(), sizeof(T)); buffer<T> addbuf(data.data(), range<1>(G)); buffer<size_t> sgsizebuf(1); Queue.submit([&](handler &cgh) { auto addacc = addbuf.template get_access<access::mode::read_write>(cgh); auto sgsizeacc = sgsizebuf.get_access<access::mode::read_write>(cgh); cgh.parallel_for<sycl_subgr<T, UseNewSyntax>>( NdRange, [=](nd_item<1> NdItem) { ext::oneapi::sub_group SG = NdItem.get_sub_group(); size_t lid = SG.get_local_id().get(0); size_t gid = NdItem.get_global_id(0); size_t SGoff = gid - lid; T res = 0; for (size_t i = 0; i <= lid; i++) { res += addacc[SGoff + i]; } if constexpr (UseNewSyntax) { group_barrier(SG); } else { SG.barrier(access::fence_space::global_space); } addacc[gid] = res; if (NdItem.get_global_id(0) == 0) sgsizeacc[0] = SG.get_max_local_range()[0]; }); }); auto addacc = addbuf.template get_access<access::mode::read_write>(); auto sgsizeacc = sgsizebuf.get_access<access::mode::read_write>(); size_t sg_size = sgsizeacc[0]; int WGid = -1, SGid = 0; T add = 0; for (int j = 0; j < G; j++) { if (j % L % sg_size == 0) { SGid++; add = 0; } if (j % L == 0) { WGid++; SGid = 0; } add += j + sizeof(T); exit_if_not_equal<T>(addacc[j], add, "barrier"); } } catch (exception e) { std::cout << "SYCL exception caught: " << e.what(); exit(1); } } int main() { queue Queue; if (Queue.get_device().is_host()) { std::cout << "Skipping test\n"; return 0; } check<int>(Queue); check<unsigned int>(Queue); check<long>(Queue); check<unsigned long>(Queue); check<float>(Queue); check<int, true>(Queue); check<unsigned int, true>(Queue); check<long, true>(Queue); check<unsigned long, true>(Queue); check<float, true>(Queue); if (Queue.get_device().has(sycl::aspect::fp64)) { check<double>(Queue); check<double, true>(Queue); } std::cout << "Test passed." << std::endl; return 0; }
// UnderwaterBaseGen.cpp // Implements the cUnderwaterBaseGen class representing the underwater base generator #include "Globals.h" #include "UnderwaterBaseGen.h" #include "Prefabs/UnderwaterBasePrefabs.h" #include "PieceGenerator.h" static cPrefabPiecePool g_UnderwaterBase(g_UnderwaterBasePrefabs, g_UnderwaterBasePrefabsCount, g_UnderwaterBaseStartingPrefabs, g_UnderwaterBaseStartingPrefabsCount); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cUnderwaterBaseGen::cUnderwaterBase: class cUnderwaterBaseGen::cUnderwaterBase : public cGridStructGen::cStructure { typedef cGridStructGen::cStructure super; public: cUnderwaterBase( int a_Seed, int a_OriginX, int a_OriginZ, int a_MaxDepth, int a_MaxSize ) : super(a_OriginX, a_OriginZ), m_Seed(a_Seed), m_Noise(a_Seed), m_MaxSize(a_MaxSize), m_Borders(a_OriginX - a_MaxSize, 0, a_OriginZ - a_MaxSize, a_OriginX + a_MaxSize, 255, a_OriginZ + a_MaxSize) { // Generate the pieces for this base: cBFSPieceGenerator pg(g_UnderwaterBase, a_Seed); pg.PlacePieces(a_OriginX, 50, a_OriginZ, a_MaxDepth, m_Pieces); if (m_Pieces.empty()) { return; } } ~cUnderwaterBase() { cPieceGenerator::FreePieces(m_Pieces); } protected: /** Seed for the random functions */ int m_Seed; /** The noise used as a pseudo-random generator */ cNoise m_Noise; /** Maximum size, in X/Z blocks, of the village (radius from the origin) */ int m_MaxSize; /** Borders of the vilalge - no item may reach out of this cuboid. */ cCuboid m_Borders; /** The village pieces, placed by the generator. */ cPlacedPieces m_Pieces; // cGridStructGen::cStructure overrides: virtual void DrawIntoChunk(cChunkDesc & a_Chunk) override { for (cPlacedPieces::iterator itr = m_Pieces.begin(), end = m_Pieces.end(); itr != end; ++itr) { cPrefab & Prefab = (cPrefab &)((*itr)->GetPiece()); Prefab.Draw(a_Chunk, *itr); } // for itr - m_PlacedPieces[] } } ; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cUnderwaterBaseGen: cUnderwaterBaseGen::cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxDepth, int a_MaxSize, cBiomeGen & a_BiomeGen) : super(a_Seed, a_GridSize, a_GridSize, a_MaxSize, a_MaxSize, 100), m_Noise(a_Seed + 1000), m_MaxDepth(a_MaxDepth), m_MaxSize(a_MaxSize), m_BiomeGen(a_BiomeGen) { } cGridStructGen::cStructurePtr cUnderwaterBaseGen::CreateStructure(int a_OriginX, int a_OriginZ) { // Generate the biomes for the chunk surrounding the origin: int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_OriginX, a_OriginZ, ChunkX, ChunkZ); cChunkDef::BiomeMap Biomes; m_BiomeGen.GenBiomes(ChunkX, ChunkZ, Biomes); // Check if all the biomes are ocean: // If just one is not, no base is created, because it's likely that an unfriendly biome is too close for (size_t i = 0; i < ARRAYCOUNT(Biomes); i++) { switch (Biomes[i]) { case biOcean: case biDeepOcean: { // These biomes allow underwater bases break; } default: { // base-unfriendly biome, bail out with zero structure: return cStructurePtr(); } } // switch (Biomes[i]) } // for i - Biomes[] // Create a base based on the chosen prefabs: return cStructurePtr(new cUnderwaterBase(m_Seed, a_OriginX, a_OriginZ, m_MaxDepth, m_MaxSize)); }
/* Copyright 2020 The OneFlow 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 "oneflow/core/framework/framework.h" #include "oneflow/core/kernel/new_kernel_util.h" namespace oneflow { namespace user_op { template<DeviceType device_type, typename T> class ConstantKernel final : public OpKernel { public: ConstantKernel() = default; ~ConstantKernel() = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { Tensor* out_tensor = ctx->Tensor4ArgNameAndIndex("out", 0); bool is_floating_value = ctx->Attr<bool>("is_floating_value"); const int64_t elem_cnt = out_tensor->shape().elem_cnt(); CHECK_GT(elem_cnt, 0); NewKernelUtil<device_type>::Fill(ctx->device_ctx(), elem_cnt, is_floating_value ? static_cast<T>(ctx->Attr<double>("floating_value")) : static_cast<T>(ctx->Attr<int64_t>("integer_value")), out_tensor->mut_dptr<T>()); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_CONSTANT_XPU_KERNEL(device, dtype) \ REGISTER_USER_KERNEL("constant") \ .SetCreateFn<ConstantKernel<device, dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == device) \ & (user_op::HobAttr<DataType>("dtype") == GetDataType<dtype>::value)); #define REGISTER_CONSTANT_KERNEL(device, dtype_pair) \ REGISTER_CONSTANT_XPU_KERNEL(device, OF_PP_PAIR_FIRST(dtype_pair)) #define DATA_TYPE_SEQ \ FLOATING_DATA_TYPE_SEQ \ INT_DATA_TYPE_SEQ \ UNSIGNED_INT_DATA_TYPE_SEQ OF_PP_SEQ_PRODUCT_FOR_EACH_TUPLE(REGISTER_CONSTANT_KERNEL, DEVICE_TYPE_SEQ, DATA_TYPE_SEQ) } // namespace user_op } // namespace oneflow
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ /* AMCL basic functions for Large Finite Field support */ #include "ff_WWW.h" using namespace XXX; namespace WWW { static void FF_dsucopy(BIG x[],BIG y[],int); static void FF_dscopy(BIG x[],BIG y[],int); static void FF_sducopy(BIG x[],BIG y[],int); static void FF_shrw(BIG a[],int); static void FF_shlw(BIG a[],int); static void FF_radd(BIG z[],int,BIG x[],int,BIG y[],int,int); static void FF_rinc(BIG z[],int,BIG y[],int,int); static void FF_rdec(BIG z[],int,BIG y[],int,int); static void FF_rnorm(BIG z[],int,int); static void FF_cswap(BIG a[],BIG b[],int,int); static void FF_karmul(BIG z[],int,BIG x[],int,BIG y[],int,BIG t[],int,int); static void FF_karsqr(BIG z[],int,BIG x[],int,BIG t[],int,int); static void FF_karmul_lower(BIG z[],int,BIG x[],int,BIG y[],int,BIG t[],int,int); static void FF_karmul_upper(BIG z[],BIG x[],BIG y[],BIG t[],int); static void FF_lmul(BIG z[],BIG x[],BIG y[],int); static void FF_reduce(BIG r[],BIG T[],BIG N[],BIG ND[],int); static void FF_nres(BIG a[],BIG m[],int); static void FF_redc(BIG a[],BIG m[],BIG ND[],int); static void FF_invmod2m(BIG U[],BIG a[],int); static void FF_modmul(BIG z[],BIG x[],BIG y[],BIG p[],BIG ND[],int); static void FF_modsqr(BIG z[],BIG x[],BIG p[],BIG ND[],int); } /* Arazi and Qi inversion mod 256 */ static int invmod256(int a) { int U,t1,t2,b,c; t1=0; c=(a>>1)&1; t1+=c; t1&=1; t1=2-t1; t1<<=1; U=t1+1; // i=2 b=a&3; t1=U*b; t1>>=2; c=(a>>2)&3; t2=(U*c)&3; t1+=t2; t1*=U; t1&=3; t1=4-t1; t1<<=2; U+=t1; // i=4 b=a&15; t1=U*b; t1>>=4; c=(a>>4)&15; t2=(U*c)&15; t1+=t2; t1*=U; t1&=15; t1=16-t1; t1<<=4; U+=t1; return U; } /* a=1/a mod 2^BIGBITS_XXX. This is very fast! */ void XXX::BIG_invmod2m(BIG a) { int i; BIG U,t1,b,c; BIG_zero(U); BIG_inc(U,invmod256(BIG_lastbits(a,8))); for (i=8; i<BIGBITS_XXX; i<<=1) { BIG_norm(U); BIG_copy(b,a); BIG_mod2m(b,i); // bottom i bits of a BIG_smul(t1,U,b); BIG_shr(t1,i); // top i bits of U*b BIG_copy(c,a); BIG_shr(c,i); BIG_mod2m(c,i); // top i bits of a BIG_smul(b,U,c); BIG_mod2m(b,i); // bottom i bits of U*c BIG_add(t1,t1,b); BIG_norm(t1); BIG_smul(b,t1,U); BIG_copy(t1,b); // (t1+b)*U BIG_mod2m(t1,i); // bottom i bits of (t1+b)*U BIG_one(b); BIG_shl(b,i); BIG_sub(t1,b,t1); BIG_norm(t1); BIG_shl(t1,i); BIG_add(U,U,t1); } BIG_copy(a,U); BIG_norm(a); BIG_mod2m(a,BIGBITS_XXX); } /* void FF_rcopy(BIG x[],const BIG y[],int n) { int i; for (i=0;i<n;i++) BIG_rcopy(x[i],y[i]); } */ /* x=y */ void WWW::FF_copy(BIG x[],BIG y[],int n) { int i; for (i=0; i<n; i++) BIG_copy(x[i],y[i]); } /* x=y<<n */ static void WWW::FF_dsucopy(BIG x[],BIG y[],int n) { int i; for (i=0; i<n; i++) { BIG_copy(x[n+i],y[i]); BIG_zero(x[i]); } } /* x=y */ static void WWW::FF_dscopy(BIG x[],BIG y[],int n) { int i; for (i=0; i<n; i++) { BIG_copy(x[i],y[i]); BIG_zero(x[n+i]); } } /* x=y>>n */ static void WWW::FF_sducopy(BIG x[],BIG y[],int n) { int i; for (i=0; i<n; i++) BIG_copy(x[i],y[n+i]); } /* set to zero */ void WWW::FF_zero(BIG x[],int n) { int i; for (i=0; i<n; i++) BIG_zero(x[i]); } /* test equals 0 */ int WWW::FF_iszilch(BIG x[],int n) { int i; for (i=0; i<n; i++) if (!BIG_iszilch(x[i])) return 0; return 1; } /* shift right by BIGBITS_XXX-bit words */ static void WWW::FF_shrw(BIG a[],int n) { int i; for (i=0; i<n; i++) { BIG_copy(a[i],a[i+n]); BIG_zero(a[i+n]); } } /* shift left by BIGBITS_XXX-bit words */ static void WWW::FF_shlw(BIG a[],int n) { int i; for (i=0; i<n; i++) { BIG_copy(a[i+n],a[i]); BIG_zero(a[i]); } } /* extract last bit */ int WWW::FF_parity(BIG x[]) { return BIG_parity(x[0]); } /* extract last m bits */ int WWW::FF_lastbits(BIG x[],int m) { return BIG_lastbits(x[0],m); } /* x=1 */ void WWW::FF_one(BIG x[],int n) { int i; BIG_one(x[0]); for (i=1; i<n; i++) BIG_zero(x[i]); } /* x=m, where m is 32-bit int */ void WWW::FF_init(BIG x[],sign32 m,int n) { int i; BIG_zero(x[0]); #if CHUNK<64 x[0][0]=(chunk)(m&BMASK_XXX); x[0][1]=(chunk)(m>>BASEBITS_XXX); #else x[0][0]=(chunk)m; #endif for (i=1; i<n; i++) BIG_zero(x[i]); } /* compare x and y - must be normalised */ int WWW::FF_comp(BIG x[],BIG y[],int n) { int i,j; for (i=n-1; i>=0; i--) { j=BIG_comp(x[i],y[i]); if (j!=0) return j; } return 0; } /* recursive add */ static void WWW::FF_radd(BIG z[],int zp,BIG x[],int xp,BIG y[],int yp,int n) { int i; for (i=0; i<n; i++) BIG_add(z[zp+i],x[xp+i],y[yp+i]); } /* recursive inc */ static void WWW::FF_rinc(BIG z[],int zp,BIG y[],int yp,int n) { int i; for (i=0; i<n; i++) BIG_add(z[zp+i],z[zp+i],y[yp+i]); } /* recursive sub */ /* static void FF_rsub(BIG z[],int zp,BIG x[],int xp,BIG y[],int yp,int n) { int i; for (i=0;i<n;i++) BIG_sub(z[zp+i],x[xp+i],y[yp+i]); } */ /* recursive dec */ static void WWW::FF_rdec(BIG z[],int zp,BIG y[],int yp,int n) { int i; for (i=0; i<n; i++) BIG_sub(z[zp+i],z[zp+i],y[yp+i]); } /* simple add */ void WWW::FF_add(BIG z[],BIG x[],BIG y[],int n) { int i; for (i=0; i<n; i++) BIG_add(z[i],x[i],y[i]); } /* simple sub */ void WWW::FF_sub(BIG z[],BIG x[],BIG y[],int n) { int i; for (i=0; i<n; i++) BIG_sub(z[i],x[i],y[i]); } /* increment/decrement by a small integer */ void WWW::FF_inc(BIG x[],int m,int n) { BIG_inc(x[0],m); FF_norm(x,n); } void WWW::FF_dec(BIG x[],int m,int n) { BIG_dec(x[0],m); FF_norm(x,n); } /* normalise - but hold any overflow in top part unless n<0 */ static void WWW::FF_rnorm(BIG z[],int zp,int n) { int i,trunc=0; chunk carry; if (n<0) { /* -v n signals to do truncation */ n=-n; trunc=1; } for (i=0; i<n-1; i++) { carry=BIG_norm(z[zp+i]); z[zp+i][NLEN_XXX-1]^=carry<<P_TBITS_WWW; /* remove it */ z[zp+i+1][0]+=carry; } carry=BIG_norm(z[zp+n-1]); if (trunc) z[zp+n-1][NLEN_XXX-1]^=carry<<P_TBITS_WWW; } void WWW::FF_norm(BIG z[],int n) { FF_rnorm(z,0,n); } /* shift left by one bit */ void WWW::FF_shl(BIG x[],int n) { int i; int carry,delay_carry=0; for (i=0; i<n-1; i++) { carry=BIG_fshl(x[i],1); x[i][0]|=delay_carry; x[i][NLEN_XXX-1]^=(chunk)carry<<P_TBITS_WWW; delay_carry=carry; } BIG_fshl(x[n-1],1); x[n-1][0]|=delay_carry; } /* shift right by one bit */ void WWW::FF_shr(BIG x[],int n) { int i; int carry; for (i=n-1; i>0; i--) { carry=BIG_fshr(x[i],1); x[i-1][NLEN_XXX-1]|=(chunk)carry<<P_TBITS_WWW; } BIG_fshr(x[0],1); } void WWW::FF_output(BIG x[],int n) { int i; FF_norm(x,n); for (i=n-1; i>=0; i--) { BIG_output(x[i]); printf(" "); } } void WWW::FF_rawoutput(BIG x[],int n) { int i; for (i=n-1; i>=0; i--) { BIG_rawoutput(x[i]); printf(" "); } } /* Convert FFs to/from octet strings */ void WWW::FF_toOctet(octet *w,BIG x[],int n) { int i; w->len=n*MODBYTES_XXX; for (i=0; i<n; i++) { BIG_toBytes(&(w->val[(n-i-1)*MODBYTES_XXX]),x[i]); } } void WWW::FF_fromOctet(BIG x[],octet *w,int n) { int i; for (i=0; i<n; i++) { BIG_fromBytes(x[i],&(w->val[(n-i-1)*MODBYTES_XXX])); } } /* in-place swapping using xor - side channel resistant */ static void WWW::FF_cswap(BIG a[],BIG b[],int d,int n) { int i; for (i=0; i<n; i++) BIG_cswap(a[i],b[i],d); return; } /* z=x*y, t is workspace */ static void WWW::FF_karmul(BIG z[],int zp,BIG x[],int xp,BIG y[],int yp,BIG t[],int tp,int n) { int nd2; if (n==1) { BIG_norm(x[xp]); BIG_norm(y[yp]); BIG_mul(t[tp],x[xp],y[yp]); BIG_split(z[zp+1],z[zp],t[tp],BIGBITS_XXX); return; } nd2=n/2; FF_radd(z,zp,x,xp,x,xp+nd2,nd2); FF_rnorm(z,zp,nd2); /* needs this if recursion level too deep */ FF_radd(z,zp+nd2,y,yp,y,yp+nd2,nd2); FF_rnorm(z,zp+nd2,nd2); FF_karmul(t,tp,z,zp,z,zp+nd2,t,tp+n,nd2); FF_karmul(z,zp,x,xp,y,yp,t,tp+n,nd2); FF_karmul(z,zp+n,x,xp+nd2,y,yp+nd2,t,tp+n,nd2); FF_rdec(t,tp,z,zp,n); FF_rdec(t,tp,z,zp+n,n); FF_rinc(z,zp+nd2,t,tp,n); FF_rnorm(z,zp,2*n); } static void WWW::FF_karsqr(BIG z[],int zp,BIG x[],int xp,BIG t[],int tp,int n) { int nd2; if (n==1) { BIG_norm(x[xp]); BIG_sqr(t[tp],x[xp]); BIG_split(z[zp+1],z[zp],t[tp],BIGBITS_XXX); return; } nd2=n/2; FF_karsqr(z,zp,x,xp,t,tp+n,nd2); FF_karsqr(z,zp+n,x,xp+nd2,t,tp+n,nd2); FF_karmul(t,tp,x,xp,x,xp+nd2,t,tp+n,nd2); FF_rinc(z,zp+nd2,t,tp,n); FF_rinc(z,zp+nd2,t,tp,n); FF_rnorm(z,zp+nd2,n); /* was FF_rnorm(z,zp,2*n) */ } static void WWW::FF_karmul_lower(BIG z[],int zp,BIG x[],int xp,BIG y[],int yp,BIG t[],int tp,int n) { /* Calculates Least Significant bottom half of x*y */ int nd2; if (n==1) { /* only calculate bottom half of product */ BIG_norm(x[xp]); BIG_norm(y[yp]); BIG_smul(z[zp],x[xp],y[yp]); return; } nd2=n/2; FF_karmul(z,zp,x,xp,y,yp,t,tp+n,nd2); FF_karmul_lower(t,tp,x,xp+nd2,y,yp,t,tp+n,nd2); FF_rinc(z,zp+nd2,t,tp,nd2); FF_karmul_lower(t,tp,x,xp,y,yp+nd2,t,tp+n,nd2); FF_rinc(z,zp+nd2,t,tp,nd2); FF_rnorm(z,zp+nd2,-nd2); /* truncate it */ } static void WWW::FF_karmul_upper(BIG z[],BIG x[],BIG y[],BIG t[],int n) { /* Calculates Most Significant upper half of x*y, given lower part */ int nd2; nd2=n/2; FF_radd(z,n,x,0,x,nd2,nd2); FF_radd(z,n+nd2,y,0,y,nd2,nd2); FF_rnorm(z,n,nd2); FF_rnorm(z,n+nd2,nd2); FF_karmul(t,0,z,n+nd2,z,n,t,n,nd2); /* t = (a0+a1)(b0+b1) */ FF_karmul(z,n,x,nd2,y,nd2,t,n,nd2); /* z[n]= a1*b1 */ /* z[0-nd2]=l(a0b0) z[nd2-n]= h(a0b0)+l(t)-l(a0b0)-l(a1b1) */ FF_rdec(t,0,z,n,n); /* t=t-a1b1 */ FF_rinc(z,nd2,z,0,nd2); /* z[nd2-n]+=l(a0b0) = h(a0b0)+l(t)-l(a1b1) */ FF_rdec(z,nd2,t,0,nd2); /* z[nd2-n]=h(a0b0)+l(t)-l(a1b1)-l(t-a1b1)=h(a0b0) */ FF_rnorm(z,0,-n); /* a0b0 now in z - truncate it */ FF_rdec(t,0,z,0,n); /* (a0+a1)(b0+b1) - a0b0 */ FF_rinc(z,nd2,t,0,n); FF_rnorm(z,nd2,n); } /* z=x*y */ void WWW::FF_mul(BIG z[],BIG x[],BIG y[],int n) { #ifndef C99 BIG t[2*FFLEN_WWW]; #else BIG t[2*n]; #endif // FF_norm(x,n); /* change here */ // FF_norm(y,n); /* change here */ FF_karmul(z,0,x,0,y,0,t,0,n); } /* return low part of product */ static void WWW::FF_lmul(BIG z[],BIG x[],BIG y[],int n) { #ifndef C99 BIG t[2*FFLEN_WWW]; #else BIG t[2*n]; #endif // FF_norm(x,n); /* change here */ // FF_norm(y,n); /* change here */ FF_karmul_lower(z,0,x,0,y,0,t,0,n); } /* Set b=b mod c */ void WWW::FF_mod(BIG b[],BIG c[],int n) { int k=0; FF_norm(b,n); if (FF_comp(b,c,n)<0) return; do { FF_shl(c,n); k++; } while (FF_comp(b,c,n)>=0); while (k>0) { FF_shr(c,n); if (FF_comp(b,c,n)>=0) { FF_sub(b,b,c,n); FF_norm(b,n); } k--; } } /* z=x^2 */ void WWW::FF_sqr(BIG z[],BIG x[],int n) { #ifndef C99 BIG t[2*FFLEN_WWW]; #else BIG t[2*n]; #endif // FF_norm(x,n); /* change here */ FF_karsqr(z,0,x,0,t,0,n); } /* r=t mod modulus, N is modulus, ND is Montgomery Constant */ static void WWW::FF_reduce(BIG r[],BIG T[],BIG N[],BIG ND[],int n) { /* fast karatsuba Montgomery reduction */ #ifndef C99 BIG t[2*FFLEN_WWW]; BIG m[FFLEN_WWW]; #else BIG t[2*n]; BIG m[n]; #endif WWW::FF_sducopy(r,T,n); /* keep top half of T */ //FF_norm(T,n); /* change here */ FF_karmul_lower(m,0,T,0,ND,0,t,0,n); /* m=T.(1/N) mod R */ //FF_norm(N,n); /* change here */ FF_karmul_upper(T,N,m,t,n); /* T=mN */ FF_sducopy(m,T,n); FF_add(r,r,N,n); FF_sub(r,r,m,n); FF_norm(r,n); } /* Set r=a mod b */ /* a is of length - 2*n */ /* r,b is of length - n */ void WWW::FF_dmod(BIG r[],BIG a[],BIG b[],int n) { int k; #ifndef C99 BIG m[2*FFLEN_WWW]; BIG x[2*FFLEN_WWW]; #else BIG m[2*n]; BIG x[2*n]; #endif FF_copy(x,a,2*n); FF_norm(x,2*n); FF_dsucopy(m,b,n); k=BIGBITS_XXX*n; while (FF_comp(x,m,2*n)>=0) { FF_sub(x,x,m,2*n); FF_norm(x,2*n); } while (k>0) { FF_shr(m,2*n); if (FF_comp(x,m,2*n)>=0) { FF_sub(x,x,m,2*n); FF_norm(x,2*n); } k--; } FF_copy(r,x,n); FF_mod(r,b,n); } /* Set r=1/a mod p. Binary method - a<p on entry */ void WWW::FF_invmodp(BIG r[],BIG a[],BIG p[],int n) { #ifndef C99 BIG u[FFLEN_WWW],v[FFLEN_WWW],x1[FFLEN_WWW],x2[FFLEN_WWW],t[FFLEN_WWW],one[FFLEN_WWW]; #else BIG u[n],v[n],x1[n],x2[n],t[n],one[n]; #endif FF_copy(u,a,n); FF_copy(v,p,n); FF_one(one,n); FF_copy(x1,one,n); FF_zero(x2,n); // reduce n in here as well! while (FF_comp(u,one,n)!=0 && FF_comp(v,one,n)!=0) { while (FF_parity(u)==0) { FF_shr(u,n); if (FF_parity(x1)!=0) { FF_add(x1,p,x1,n); FF_norm(x1,n); } FF_shr(x1,n); } while (FF_parity(v)==0) { FF_shr(v,n); if (FF_parity(x2)!=0) { FF_add(x2,p,x2,n); FF_norm(x2,n); } FF_shr(x2,n); } if (FF_comp(u,v,n)>=0) { FF_sub(u,u,v,n); FF_norm(u,n); if (FF_comp(x1,x2,n)>=0) FF_sub(x1,x1,x2,n); else { FF_sub(t,p,x2,n); FF_add(x1,x1,t,n); } FF_norm(x1,n); } else { FF_sub(v,v,u,n); FF_norm(v,n); if (FF_comp(x2,x1,n)>=0) FF_sub(x2,x2,x1,n); else { FF_sub(t,p,x1,n); FF_add(x2,x2,t,n); } FF_norm(x2,n); } } if (FF_comp(u,one,n)==0) FF_copy(r,x1,n); else FF_copy(r,x2,n); } /* nesidue mod m */ static void WWW::FF_nres(BIG a[],BIG m[],int n) { #ifndef C99 BIG d[2*FFLEN_WWW]; #else BIG d[2*n]; #endif if (n==1) { BIG_dscopy(d[0],a[0]); BIG_dshl(d[0],NLEN_XXX*BASEBITS_XXX); BIG_dmod(a[0],d[0],m[0]); } else { FF_dsucopy(d,a,n); FF_dmod(a,d,m,n); } } static void WWW::FF_redc(BIG a[],BIG m[],BIG ND[],int n) { #ifndef C99 BIG d[2*FFLEN_WWW]; #else BIG d[2*n]; #endif if (n==1) { BIG_dzero(d[0]); BIG_dscopy(d[0],a[0]); BIG_monty(a[0],m[0],((chunk)1<<BASEBITS_XXX)-ND[0][0],d[0]); } else { FF_mod(a,m,n); FF_dscopy(d,a,n); FF_reduce(a,d,m,ND,n); FF_mod(a,m,n); } } /* U=1/a mod 2^m - Arazi & Qi */ static void WWW::FF_invmod2m(BIG U[],BIG a[],int n) { int i; #ifndef C99 BIG t1[FFLEN_WWW],b[FFLEN_WWW],c[FFLEN_WWW]; #else BIG t1[2*n],b[n],c[n]; #endif FF_zero(U,n); FF_zero(b,n); FF_zero(c,n); FF_zero(t1,2*n); BIG_copy(U[0],a[0]); BIG_invmod2m(U[0]); for (i=1; i<n; i<<=1) { FF_copy(b,a,i); FF_mul(t1,U,b,i); FF_shrw(t1,i); // top half to bottom half, top half=0 FF_copy(c,a,2*i); FF_shrw(c,i); // top half of c FF_lmul(b,U,c,i); // should set top half of b=0 FF_add(t1,t1,b,i); FF_norm(t1,2*i); FF_lmul(b,t1,U,i); FF_copy(t1,b,i); FF_one(b,i); FF_shlw(b,i); FF_sub(t1,b,t1,2*i); FF_norm(t1,2*i); FF_shlw(t1,i); FF_add(U,U,t1,2*i); } FF_norm(U,n); } void WWW::FF_random(BIG x[],csprng *rng,int n) { int i; for (i=0; i<n; i++) { BIG_random(x[i],rng); } /* make sure top bit is 1 */ while (BIG_nbits(x[n-1])<MODBYTES_XXX*8) BIG_random(x[n-1],rng); } /* generate random x mod p */ void WWW::FF_randomnum(BIG x[],BIG p[],csprng *rng,int n) { int i; #ifndef C99 BIG d[2*FFLEN_WWW]; #else BIG d[2*n]; #endif for (i=0; i<2*n; i++) { BIG_random(d[i],rng); } FF_dmod(x,d,p,n); } static void WWW::FF_modmul(BIG z[],BIG x[],BIG y[],BIG p[],BIG ND[],int n) { #ifndef C99 BIG d[2*FFLEN_WWW]; #else BIG d[2*n]; #endif chunk ex=P_EXCESS_WWW(x[n-1]); chunk ey=P_EXCESS_WWW(y[n-1]); #ifdef dchunk if ((dchunk)(ex+1)*(ey+1)>(dchunk)P_FEXCESS_WWW) #else if ((ex+1)>P_FEXCESS_WWW/(ey+1)) #endif { #ifdef DEBUG_REDUCE printf("Product too large - reducing it %d %d\n",ex,ey); #endif FF_mod(x,p,n); } if (n==1) { BIG_mul(d[0],x[0],y[0]); BIG_monty(z[0],p[0],((chunk)1<<BASEBITS_XXX)-ND[0][0],d[0]); } else { FF_mul(d,x,y,n); FF_reduce(z,d,p,ND,n); } } static void WWW::FF_modsqr(BIG z[],BIG x[],BIG p[],BIG ND[],int n) { #ifndef C99 BIG d[2*FFLEN_WWW]; #else BIG d[2*n]; #endif chunk ex=P_EXCESS_WWW(x[n-1]); #ifdef dchunk if ((dchunk)(ex+1)*(ex+1)>(dchunk)P_FEXCESS_WWW) #else if ((ex+1)>P_FEXCESS_WWW/(ex+1)) #endif { #ifdef DEBUG_REDUCE printf("Product too large - reducing it %d\n",ex); #endif FF_mod(x,p,n); } if (n==1) { BIG_sqr(d[0],x[0]); BIG_monty(z[0],p[0],((chunk)1<<BASEBITS_XXX)-ND[0][0],d[0]); } else { FF_sqr(d,x,n); FF_reduce(z,d,p,ND,n); } } /* r=x^e mod p using side-channel resistant Montgomery Ladder, for large e */ void WWW::FF_skpow(BIG r[],BIG x[],BIG e[],BIG p[],int n) { int i,b; #ifndef C99 BIG R0[FFLEN_WWW],R1[FFLEN_WWW],ND[FFLEN_WWW]; #else BIG R0[n],R1[n],ND[n]; #endif FF_invmod2m(ND,p,n); FF_one(R0,n); FF_copy(R1,x,n); FF_nres(R0,p,n); FF_nres(R1,p,n); for (i=8*MODBYTES_XXX*n-1; i>=0; i--) { b=BIG_bit(e[i/BIGBITS_XXX],i%BIGBITS_XXX); FF_modmul(r,R0,R1,p,ND,n); FF_cswap(R0,R1,b,n); FF_modsqr(R0,R0,p,ND,n); FF_copy(R1,r,n); FF_cswap(R0,R1,b,n); } FF_copy(r,R0,n); FF_redc(r,p,ND,n); } /* r=x^e mod p using side-channel resistant Montgomery Ladder, for short e */ void WWW::FF_skspow(BIG r[],BIG x[],BIG e,BIG p[],int n) { int i,b; #ifndef C99 BIG R0[FFLEN_WWW],R1[FFLEN_WWW],ND[FFLEN_WWW]; #else BIG R0[n],R1[n],ND[n]; #endif FF_invmod2m(ND,p,n); FF_one(R0,n); FF_copy(R1,x,n); FF_nres(R0,p,n); FF_nres(R1,p,n); for (i=8*MODBYTES_XXX-1; i>=0; i--) { b=BIG_bit(e,i); FF_modmul(r,R0,R1,p,ND,n); FF_cswap(R0,R1,b,n); FF_modsqr(R0,R0,p,ND,n); FF_copy(R1,r,n); FF_cswap(R0,R1,b,n); } FF_copy(r,R0,n); FF_redc(r,p,ND,n); } /* raise to an integer power - right-to-left method */ void WWW::FF_power(BIG r[],BIG x[],int e,BIG p[],int n) { int f=1; #ifndef C99 BIG w[FFLEN_WWW],ND[FFLEN_WWW]; #else BIG w[n],ND[n]; #endif FF_invmod2m(ND,p,n); FF_copy(w,x,n); FF_nres(w,p,n); if (e==2) { FF_modsqr(r,w,p,ND,n); } else for (;;) { if (e%2==1) { if (f) FF_copy(r,w,n); else FF_modmul(r,r,w,p,ND,n); f=0; } e>>=1; if (e==0) break; FF_modsqr(w,w,p,ND,n); } FF_redc(r,p,ND,n); } /* r=x^e mod p, faster but not side channel resistant */ void WWW::FF_pow(BIG r[],BIG x[],BIG e[],BIG p[],int n) { int i,b; #ifndef C99 BIG w[FFLEN_WWW],ND[FFLEN_WWW]; #else BIG w[n],ND[n]; #endif FF_invmod2m(ND,p,n); FF_copy(w,x,n); FF_one(r,n); FF_nres(r,p,n); FF_nres(w,p,n); for (i=8*MODBYTES_XXX*n-1; i>=0; i--) { FF_modsqr(r,r,p,ND,n); b=BIG_bit(e[i/BIGBITS_XXX],i%BIGBITS_XXX); if (b==1) FF_modmul(r,r,w,p,ND,n); } FF_redc(r,p,ND,n); } /* double exponentiation r=x^e.y^f mod p */ void WWW::FF_pow2(BIG r[],BIG x[],BIG e,BIG y[],BIG f,BIG p[],int n) { int i,eb,fb; #ifndef C99 BIG xn[FFLEN_WWW],yn[FFLEN_WWW],xy[FFLEN_WWW],ND[FFLEN_WWW]; #else BIG xn[n],yn[n],xy[n],ND[n]; #endif FF_invmod2m(ND,p,n); FF_copy(xn,x,n); FF_copy(yn,y,n); FF_nres(xn,p,n); FF_nres(yn,p,n); FF_modmul(xy,xn,yn,p,ND,n); FF_one(r,n); FF_nres(r,p,n); for (i=8*MODBYTES_XXX-1; i>=0; i--) { eb=BIG_bit(e,i); fb=BIG_bit(f,i); FF_modsqr(r,r,p,ND,n); if (eb==1) { if (fb==1) FF_modmul(r,r,xy,p,ND,n); else FF_modmul(r,r,xn,p,ND,n); } else { if (fb==1) FF_modmul(r,r,yn,p,ND,n); } } FF_redc(r,p,ND,n); } static sign32 igcd(sign32 x,sign32 y) { /* integer GCD, returns GCD of x and y */ sign32 r; if (y==0) return x; while ((r=x%y)!=0) x=y,y=r; return y; } /* quick and dirty check for common factor with s */ int WWW::FF_cfactor(BIG w[],sign32 s,int n) { int r; sign32 g; #ifndef C99 BIG x[FFLEN_WWW],y[FFLEN_WWW]; #else BIG x[n],y[n]; #endif FF_init(y,s,n); FF_copy(x,w,n); FF_norm(x,n); // if (FF_parity(x)==0) return 1; do { FF_sub(x,x,y,n); FF_norm(x,n); while (!FF_iszilch(x,n) && FF_parity(x)==0) FF_shr(x,n); } while (FF_comp(x,y,n)>0); #if CHUNK<32 g=x[0][0]+((sign32)(x[0][1])<<BASEBITS_XXX); #else g=(sign32)x[0][0]; #endif r=igcd(s,g); if (r>1) return 1; return 0; } /* Miller-Rabin test for primality. Slow. */ int WWW::FF_prime(BIG p[],csprng *rng,int n) { int i,j,loop,s=0; #ifndef C99 BIG d[FFLEN_WWW],x[FFLEN_WWW],unity[FFLEN_WWW],nm1[FFLEN_WWW]; #else BIG d[n],x[n],unity[n],nm1[n]; #endif sign32 sf=4849845;/* 3*5*.. *19 */ FF_norm(p,n); if (FF_cfactor(p,sf,n)) return 0; FF_one(unity,n); FF_sub(nm1,p,unity,n); FF_norm(nm1,n); FF_copy(d,nm1,n); while (FF_parity(d)==0) { FF_shr(d,n); s++; } if (s==0) return 0; for (i=0; i<10; i++) { FF_randomnum(x,p,rng,n); FF_pow(x,x,d,p,n); if (FF_comp(x,unity,n)==0 || FF_comp(x,nm1,n)==0) continue; loop=0; for (j=1; j<s; j++) { FF_power(x,x,2,p,n); if (FF_comp(x,unity,n)==0) return 0; if (FF_comp(x,nm1,n)==0 ) { loop=1; break; } } if (loop) continue; return 0; } return 1; } /* BIG P[4]= {{0x1670957,0x1568CD3C,0x2595E5,0xEED4F38,0x1FC9A971,0x14EF7E62,0xA503883,0x9E1E05E,0xBF59E3},{0x1844C908,0x1B44A798,0x3A0B1E7,0xD1B5B4E,0x1836046F,0x87E94F9,0x1D34C537,0xF7183B0,0x46D07},{0x17813331,0x19E28A90,0x1473A4D6,0x1CACD01F,0x1EEA8838,0xAF2AE29,0x1F85292A,0x1632585E,0xD945E5},{0x919F5EF,0x1567B39F,0x19F6AD11,0x16CE47CF,0x9B36EB1,0x35B7D3,0x483B28C,0xCBEFA27,0xB5FC21}}; int main() { int i; BIG p[4],e[4],x[4],r[4]; csprng rng; char raw[100]; for (i=0;i<100;i++) raw[i]=i; RAND_seed(&rng,100,raw); FF_init(x,3,4); FF_copy(p,P,4); FF_copy(e,p,4); FF_dec(e,1,4); FF_norm(e,4); printf("p= ");FF_output(p,4); printf("\n"); if (FF_prime(p,&rng,4)) printf("p is a prime\n"); printf("e= ");FF_output(e,4); printf("\n"); FF_skpow(r,x,e,p,4); printf("r= ");FF_output(r,4); printf("\n"); } */
/*============================================================================= Copyright (c) 2005-2011 Joel de Guzman Copyright (c) 2005-2006 Dan Marsden 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) ==============================================================================*/ #if !defined(BOOST_FUSION_DEQUE_DETAIL_KEYED_ELEMENT_26112006_1330) #define BOOST_FUSION_DEQUE_DETAIL_KEYED_ELEMENT_26112006_1330 #include <boost/fusion/support/detail/access.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/iterator/next.hpp> namespace boost { namespace fusion { struct fusion_sequence_tag; namespace detail { struct nil_keyed_element { typedef fusion_sequence_tag tag; void get(); template<typename It> static nil_keyed_element from_iterator(It const&) { return nil_keyed_element(); } }; template<typename Key, typename Value, typename Rest> struct keyed_element : Rest { typedef Rest base; typedef fusion_sequence_tag tag; using Rest::get; template<typename It> static keyed_element from_iterator(It const& it) { return keyed_element( *it, base::from_iterator(fusion::next(it))); } template<typename U, typename Rst> keyed_element(keyed_element<Key, U, Rst> const& rhs) : Rest(rhs.get_base()), value_(rhs.value_) {} Rest const get_base() const { return *this; } typename cref_result<Value>::type get(Key) const { return value_; } typename ref_result<Value>::type get(Key) { return value_; } keyed_element(typename call_param<Value>::type value, Rest const& rest) : Rest(rest), value_(value) {} keyed_element() : Rest(), value_() {} template<typename U, typename Rst> keyed_element& operator=(keyed_element<Key, U, Rst> const& rhs) { base::operator=(static_cast<Rst const&>(rhs)); // cast for msvc-7.1 value_ = rhs.value_; return *this; } keyed_element& operator=(keyed_element const& rhs) { base::operator=(rhs); value_ = rhs.value_; return *this; } Value value_; }; template<typename Elem, typename Key> struct keyed_element_value_at : keyed_element_value_at<typename Elem::base, Key> {}; template<typename Key, typename Value, typename Rest> struct keyed_element_value_at<keyed_element<Key, Value, Rest>, Key> { typedef Value type; }; }}} #endif
#ifndef RAPIDXML_HPP_INCLUDED #define RAPIDXML_HPP_INCLUDED // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml.hpp This file contains rapidxml parser and DOM implementation // If standard library is disabled, user must provide implementations of required functions and typedefs #if !defined(RAPIDXML_NO_STDLIB) #include <cstdlib> // For std::size_t #include <cassert> // For assert #include <new> // For placement new #endif // On MSVC, disable "conditional expression is constant" warning (level 4). // This warning is almost impossible to avoid with certain types of templated code #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4127) // Conditional expression is constant #endif /////////////////////////////////////////////////////////////////////////// // RAPIDXML_PARSE_ERROR #if defined(RAPIDXML_NO_EXCEPTIONS) #define RAPIDXML_PARSE_ERROR(what, where) { parse_error_handler(what, where); assert(0); } namespace rapidxml { //! When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, //! this function is called to notify user about the error. //! It must be defined by the user. //! <br><br> //! This function cannot return. If it does, the results are undefined. //! <br><br> //! A very simple definition might look like that: //! <pre> //! void %rapidxml::%parse_error_handler(const char *what, void *where) //! { //! std::cout << "Parse error: " << what << "\n"; //! std::abort(); //! } //! </pre> //! \param what Human readable description of the error. //! \param where Pointer to character data where error was detected. void parse_error_handler(const char *what, void *where); } #else #include <exception> // For std::exception #define RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where) namespace rapidxml { //! Parse error exception. //! This exception is thrown by the parser when an error occurs. //! Use what() function to get human-readable error message. //! Use where() function to get a pointer to position within source text where error was detected. //! <br><br> //! If throwing exceptions by the parser is undesirable, //! it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included. //! This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception. //! This function must be defined by the user. //! <br><br> //! This class derives from <code>std::exception</code> class. class parse_error: public std::exception { public: //! Constructs parse error parse_error(const char *what, void *where) : m_what(what) , m_where(where) { } //! Gets human readable description of error. //! \return Pointer to null terminated description of the error. virtual const char *what() const throw() { return m_what; } //! Gets pointer to character data where error happened. //! Ch should be the same as char type of xml_document that produced the error. //! \return Pointer to location within the parsed string where error occured. template<class Ch> Ch *where() const { return reinterpret_cast<Ch *>(m_where); } private: const char *m_what; void *m_where; }; } #endif /////////////////////////////////////////////////////////////////////////// // Pool sizes #ifndef RAPIDXML_STATIC_POOL_SIZE // Size of static memory block of memory_pool. // Define RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. // No dynamic memory allocations are performed by memory_pool until static memory is exhausted. #define RAPIDXML_STATIC_POOL_SIZE (64 * 1024) #endif #ifndef RAPIDXML_DYNAMIC_POOL_SIZE // Size of dynamic memory block of memory_pool. // Define RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. // After the static block is exhausted, dynamic blocks with approximately this size are allocated by memory_pool. #define RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024) #endif #ifndef RAPIDXML_ALIGNMENT // Memory allocation alignment. // Define RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to override the default value, which is the size of pointer. // All memory allocations for nodes, attributes and strings will be aligned to this value. // This must be a power of 2 and at least 1, otherwise memory_pool will not work. #define RAPIDXML_ALIGNMENT sizeof(void *) #endif namespace rapidxml { // Forward declarations template<class Ch> class xml_node; template<class Ch> class xml_attribute; template<class Ch> class xml_document; //! Enumeration listing all node types produced by the parser. //! Use xml_node::type() function to query node type. enum node_type { node_document, //!< A document node. Name and value are empty. node_element, //!< An element node. Name contains element name. Value contains text of first data node. node_data, //!< A data node. Name is empty. Value contains data text. node_cdata, //!< A CDATA node. Name is empty. Value contains data text. node_comment, //!< A comment node. Name is empty. Value contains comment text. node_declaration, //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes. node_doctype, //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text. node_pi //!< A PI node. Name contains target. Value contains instructions. }; /////////////////////////////////////////////////////////////////////// // Parsing flags //! Parse flag instructing the parser to not create data nodes. //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_data_nodes = 0x1; //! Parse flag instructing the parser to not use text of first data node as a value of parent element. //! Can be combined with other flags by use of | operator. //! Note that child data nodes of element node take precendence over its value when printing. //! That is, if element has one or more child data nodes <em>and</em> a value, the value will be ignored. //! Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements. //! <br><br> //! See xml_document::parse() function. const int parse_no_element_values = 0x2; //! Parse flag instructing the parser to not place zero terminators after strings in the source text. //! By default zero terminators are placed, modifying source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_string_terminators = 0x4; //! Parse flag instructing the parser to not translate entities in the source text. //! By default entities are translated, modifying source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_entity_translation = 0x8; //! Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. //! By default, UTF-8 handling is enabled. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_utf8 = 0x10; //! Parse flag instructing the parser to create XML declaration node. //! By default, declaration node is not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_declaration_node = 0x20; //! Parse flag instructing the parser to create comments nodes. //! By default, comment nodes are not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_comment_nodes = 0x40; //! Parse flag instructing the parser to create DOCTYPE node. //! By default, doctype node is not created. //! Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_doctype_node = 0x80; //! Parse flag instructing the parser to create PI nodes. //! By default, PI nodes are not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_pi_nodes = 0x100; //! Parse flag instructing the parser to validate closing tag names. //! If not set, name inside closing tag is irrelevant to the parser. //! By default, closing tags are not validated. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_validate_closing_tags = 0x200; //! Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. //! By default, whitespace is not trimmed. //! This flag does not cause the parser to modify source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_trim_whitespace = 0x400; //! Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. //! Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag. //! By default, whitespace is not normalized. //! If this flag is specified, source text will be modified. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_normalize_whitespace = 0x800; // Compound flags //! Parse flags which represent default behaviour of the parser. //! This is always equal to 0, so that all other flags can be simply ored together. //! Normally there is no need to inconveniently disable flags by anding with their negated (~) values. //! This also means that meaning of each flag is a <i>negation</i> of the default setting. //! For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is <i>enabled</i> by default, //! and using the flag will disable it. //! <br><br> //! See xml_document::parse() function. const int parse_default = 0; //! A combination of parse flags that forbids any modifications of the source text. //! This also results in faster parsing. However, note that the following will occur: //! <ul> //! <li>names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends</li> //! <li>entities will not be translated</li> //! <li>whitespace will not be normalized</li> //! </ul> //! See xml_document::parse() function. const int parse_non_destructive = parse_no_string_terminators | parse_no_entity_translation; //! A combination of parse flags resulting in fastest possible parsing, without sacrificing important data. //! <br><br> //! See xml_document::parse() function. const int parse_fastest = parse_non_destructive | parse_no_data_nodes; //! A combination of parse flags resulting in largest amount of data being extracted. //! This usually results in slowest parsing. //! <br><br> //! See xml_document::parse() function. const int parse_full = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags; /////////////////////////////////////////////////////////////////////// // Internals //! \cond internal namespace internal { // Struct that contains lookup tables for the parser // It must be a template to allow correct linking (because it has static data members, which are defined in a header file). template<int Dummy> struct lookup_tables { static const unsigned char lookup_whitespace[256]; // Whitespace table static const unsigned char lookup_node_name[256]; // Node name table static const unsigned char lookup_text[256]; // Text table static const unsigned char lookup_text_pure_no_ws[256]; // Text table static const unsigned char lookup_text_pure_with_ws[256]; // Text table static const unsigned char lookup_attribute_name[256]; // Attribute name table static const unsigned char lookup_attribute_data_1[256]; // Attribute data table with single quote static const unsigned char lookup_attribute_data_1_pure[256]; // Attribute data table with single quote static const unsigned char lookup_attribute_data_2[256]; // Attribute data table with double quotes static const unsigned char lookup_attribute_data_2_pure[256]; // Attribute data table with double quotes static const unsigned char lookup_digits[256]; // Digits static const unsigned char lookup_upcase[256]; // To uppercase conversion table for ASCII characters }; // Find length of the string template<class Ch> inline std::size_t measure(const Ch *p) { const Ch *tmp = p; while (*tmp) ++tmp; return tmp - p; } // Compare strings for equality template<class Ch> inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive) { if (size1 != size2) return false; if (case_sensitive) { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) if (*p1 != *p2) return false; } else { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) if (lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p1)] != lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p2)]) return false; } return true; } } //! \endcond /////////////////////////////////////////////////////////////////////// // Memory pool //! This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. //! In most cases, you will not need to use this class directly. //! However, if you need to create nodes manually or modify names/values of nodes, //! you are encouraged to use memory_pool of relevant xml_document to allocate the memory. //! Not only is this faster than allocating them by using <code>new</code> operator, //! but also their lifetime will be tied to the lifetime of document, //! possibly simplyfing memory management. //! <br><br> //! Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. //! You can also call allocate_string() function to allocate strings. //! Such strings can then be used as names or values of nodes without worrying about their lifetime. //! Note that there is no <code>free()</code> function -- all allocations are freed at once when clear() function is called, //! or when the pool is destroyed. //! <br><br> //! It is also possible to create a standalone memory_pool, and use it //! to allocate nodes, whose lifetime will not be tied to any document. //! <br><br> //! Pool maintains <code>RAPIDXML_STATIC_POOL_SIZE</code> bytes of statically allocated memory. //! Until static memory is exhausted, no dynamic memory allocations are done. //! When static memory is exhausted, pool allocates additional blocks of memory of size <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> each, //! by using global <code>new[]</code> and <code>delete[]</code> operators. //! This behaviour can be changed by setting custom allocation routines. //! Use set_allocator() function to set them. //! <br><br> //! Allocations for nodes, attributes and strings are aligned at <code>RAPIDXML_ALIGNMENT</code> bytes. //! This value defaults to the size of pointer on target architecture. //! <br><br> //! To obtain absolutely top performance from the parser, //! it is important that all nodes are allocated from a single, contiguous block of memory. //! Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. //! If required, you can tweak <code>RAPIDXML_STATIC_POOL_SIZE</code>, <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>RAPIDXML_ALIGNMENT</code> //! to obtain best wasted memory to performance compromise. //! To do it, define their values before rapidxml.hpp file is included. //! \param Ch Character type of created nodes. template<class Ch = char> class memory_pool { public: //! \cond internal typedef void *(alloc_func)(std::size_t); // Type of user-defined function used to allocate memory typedef void (free_func)(void *); // Type of user-defined function used to free memory //! \endcond //! Constructs empty pool with default allocator functions. memory_pool() : m_alloc_func(0) , m_free_func(0) { init(); } //! Destroys pool and frees all the memory. //! This causes memory occupied by nodes allocated by the pool to be freed. //! Nodes allocated from the pool are no longer valid. ~memory_pool() { clear(); } //! Allocates a new node from the pool, and optionally assigns name and value to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param type Type of node to create. //! \param name Name to assign to the node, or 0 to assign no name. //! \param value Value to assign to the node, or 0 to assign no value. //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. //! \return Pointer to allocated node. This pointer will never be NULL. xml_node<Ch> *allocate_node(node_type type, const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0) { void *memory = allocate_aligned(sizeof(xml_node<Ch>)); xml_node<Ch> *node = new(memory) xml_node<Ch>(type); if (name) { if (name_size > 0) node->name(name, name_size); else node->name(name); } if (value) { if (value_size > 0) node->value(value, value_size); else node->value(value); } return node; } //! Allocates a new attribute from the pool, and optionally assigns name and value to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param name Name to assign to the attribute, or 0 to assign no name. //! \param value Value to assign to the attribute, or 0 to assign no value. //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. //! \return Pointer to allocated attribute. This pointer will never be NULL. xml_attribute<Ch> *allocate_attribute(const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0) { void *memory = allocate_aligned(sizeof(xml_attribute<Ch>)); xml_attribute<Ch> *attribute = new(memory) xml_attribute<Ch>; if (name) { if (name_size > 0) attribute->name(name, name_size); else attribute->name(name); } if (value) { if (value_size > 0) attribute->value(value, value_size); else attribute->value(value); } return attribute; } //! Allocates a char array of given size from the pool, and optionally copies a given string to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param source String to initialize the allocated memory with, or 0 to not initialize it. //! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated. //! \return Pointer to allocated char array. This pointer will never be NULL. Ch *allocate_string(const Ch *source = 0, std::size_t size = 0) { assert(source || size); // Either source or size (or both) must be specified if (size == 0) size = internal::measure(source) + 1; Ch *result = static_cast<Ch *>(allocate_aligned(size * sizeof(Ch))); if (source) for (std::size_t i = 0; i < size; ++i) result[i] = source[i]; return result; } //! Clones an xml_node and its hierarchy of child nodes and attributes. //! Nodes and attributes are allocated from this memory pool. //! Names and values are not cloned, they are shared between the clone and the source. //! Result node can be optionally specified as a second parameter, //! in which case its contents will be replaced with cloned source node. //! This is useful when you want to clone entire document. //! \param source Node to clone. //! \param result Node to put results in, or 0 to automatically allocate result node //! \return Pointer to cloned node. This pointer will never be NULL. xml_node<Ch> *clone_node(const xml_node<Ch> *source, xml_node<Ch> *result = 0) { // Prepare result node if (result) { result->remove_all_attributes(); result->remove_all_nodes(); result->type(source->type()); } else result = allocate_node(source->type()); // Clone name and value result->name(source->name(), source->name_size()); result->value(source->value(), source->value_size()); // Clone child nodes and attributes for (xml_node<Ch> *child = source->first_node(); child; child = child->next_sibling()) result->append_node(clone_node(child)); for (xml_attribute<Ch> *attr = source->first_attribute(); attr; attr = attr->next_attribute()) result->append_attribute(allocate_attribute(attr->name(), attr->value(), attr->name_size(), attr->value_size())); return result; } //! Clears the pool. //! This causes memory occupied by nodes allocated by the pool to be freed. //! Any nodes or strings allocated from the pool will no longer be valid. void clear() { while (m_begin != m_static_memory) { char *previous_begin = reinterpret_cast<header *>(align(m_begin))->previous_begin; if (m_free_func) m_free_func(m_begin); else delete[] m_begin; m_begin = previous_begin; } init(); } //! Sets or resets the user-defined memory allocation functions for the pool. //! This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. //! Allocation function must not return invalid pointer on failure. It should either throw, //! stop the program, or use <code>longjmp()</code> function to pass control to other place of program. //! If it returns invalid pointer, results are undefined. //! <br><br> //! User defined allocation functions must have the following forms: //! <br><code> //! <br>void *allocate(std::size_t size); //! <br>void free(void *pointer); //! </code><br> //! \param af Allocation function, or 0 to restore default function //! \param ff Free function, or 0 to restore default function void set_allocator(alloc_func *af, free_func *ff) { assert(m_begin == m_static_memory && m_ptr == align(m_begin)); // Verify that no memory is allocated yet m_alloc_func = af; m_free_func = ff; } private: struct header { char *previous_begin; }; void init() { m_begin = m_static_memory; m_ptr = align(m_begin); m_end = m_static_memory + sizeof(m_static_memory); } char *align(char *ptr) { std::size_t alignment = ((RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (RAPIDXML_ALIGNMENT - 1))) & (RAPIDXML_ALIGNMENT - 1)); return ptr + alignment; } char *allocate_raw(std::size_t size) { // Allocate void *memory; if (m_alloc_func) // Allocate memory using either user-specified allocation function or global operator new[] { memory = m_alloc_func(size); assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp } else { memory = new char[size]; #ifdef RAPIDXML_NO_EXCEPTIONS if (!memory) // If exceptions are disabled, verify memory allocation, because new will not be able to throw bad_alloc RAPIDXML_PARSE_ERROR("out of memory", 0); #endif } return static_cast<char *>(memory); } void *allocate_aligned(std::size_t size) { // Calculate aligned pointer char *result = align(m_ptr); // If not enough memory left in current pool, allocate a new pool if (result + size > m_end) { // Calculate required pool size (may be bigger than RAPIDXML_DYNAMIC_POOL_SIZE) std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE; if (pool_size < size) pool_size = size; // Allocate std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + pool_size; // 2 alignments required in worst case: one for header, one for actual allocation char *raw_memory = allocate_raw(alloc_size); // Setup new pool in allocated memory char *pool = align(raw_memory); header *new_header = reinterpret_cast<header *>(pool); new_header->previous_begin = m_begin; m_begin = raw_memory; m_ptr = pool + sizeof(header); m_end = raw_memory + alloc_size; // Calculate aligned pointer again using new pool result = align(m_ptr); } // Update pool and return aligned pointer m_ptr = result + size; return result; } char *m_begin; // Start of raw memory making up current pool char *m_ptr; // First free byte in current pool char *m_end; // One past last available byte in current pool char m_static_memory[RAPIDXML_STATIC_POOL_SIZE]; // Static raw memory alloc_func *m_alloc_func; // Allocator function, or 0 if default is to be used free_func *m_free_func; // Free function, or 0 if default is to be used }; /////////////////////////////////////////////////////////////////////////// // XML base //! Base class for xml_node and xml_attribute implementing common functions: //! name(), name_size(), value(), value_size() and parent(). //! \param Ch Character type to use template<class Ch = char> class xml_base { public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction // Construct a base with empty name, value and parent xml_base() : m_name(0) , m_value(0) , m_parent(0) { } /////////////////////////////////////////////////////////////////////////// // Node data access //! Gets name of the node. //! Interpretation of name depends on type of node. //! Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. //! <br><br> //! Use name_size() function to determine length of the name. //! \return Name of node, or empty string if node has no name. Ch *name() const { return m_name ? m_name : nullstr(); } //! Gets size of node name, not including terminator character. //! This function works correctly irrespective of whether name is or is not zero terminated. //! \return Size of node name, in characters. std::size_t name_size() const { return m_name ? m_name_size : 0; } //! Gets value of node. //! Interpretation of value depends on type of node. //! Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. //! <br><br> //! Use value_size() function to determine length of the value. //! \return Value of node, or empty string if node has no value. Ch *value() const { return m_value ? m_value : nullstr(); } //! Gets size of node value, not including terminator character. //! This function works correctly irrespective of whether value is or is not zero terminated. //! \return Size of node value, in characters. std::size_t value_size() const { return m_value ? m_value_size : 0; } /////////////////////////////////////////////////////////////////////////// // Node modification //! Sets name of node to a non zero-terminated string. //! See \ref ownership_of_strings. //! <br><br> //! Note that node does not own its name or value, it only stores a pointer to it. //! It will not delete or otherwise free the pointer on destruction. //! It is reponsibility of the user to properly manage lifetime of the string. //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - //! on destruction of the document the string will be automatically freed. //! <br><br> //! Size of name must be specified separately, because name does not have to be zero terminated. //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated). //! \param name Name of node to set. Does not have to be zero terminated. //! \param size Size of name, in characters. This does not include zero terminator, if one is present. void name(const Ch *name, std::size_t size) { m_name = const_cast<Ch *>(name); m_name_size = size; } //! Sets name of node to a zero-terminated string. //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t). //! \param name Name of node to set. Must be zero terminated. void name(const Ch *name) { this->name(name, internal::measure(name)); } //! Sets value of node to a non zero-terminated string. //! See \ref ownership_of_strings. //! <br><br> //! Note that node does not own its name or value, it only stores a pointer to it. //! It will not delete or otherwise free the pointer on destruction. //! It is reponsibility of the user to properly manage lifetime of the string. //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - //! on destruction of the document the string will be automatically freed. //! <br><br> //! Size of value must be specified separately, because it does not have to be zero terminated. //! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated). //! <br><br> //! If an element has a child node of type node_data, it will take precedence over element value when printing. //! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser. //! \param value value of node to set. Does not have to be zero terminated. //! \param size Size of value, in characters. This does not include zero terminator, if one is present. void value(const Ch *value, std::size_t size) { m_value = const_cast<Ch *>(value); m_value_size = size; } //! Sets value of node to a zero-terminated string. //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t). //! \param value Vame of node to set. Must be zero terminated. void value(const Ch *value) { this->value(value, internal::measure(value)); } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets node parent. //! \return Pointer to parent node, or 0 if there is no parent. xml_node<Ch> *parent() const { return m_parent; } protected: // Return empty string static Ch *nullstr() { static Ch zero = Ch('\0'); return &zero; } Ch *m_name; // Name of node, or 0 if no name Ch *m_value; // Value of node, or 0 if no value std::size_t m_name_size; // Length of node name, or undefined of no name std::size_t m_value_size; // Length of node value, or undefined if no value xml_node<Ch> *m_parent; // Pointer to parent node, or 0 if none }; //! Class representing attribute node of XML document. //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing. //! Thus, this text must persist in memory for the lifetime of attribute. //! \param Ch Character type to use. template<class Ch = char> class xml_attribute: public xml_base<Ch> { friend class xml_node<Ch>; public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction //! Constructs an empty attribute with the specified type. //! Consider using memory_pool of appropriate xml_document if allocating attributes manually. xml_attribute() { } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets document of which attribute is a child. //! \return Pointer to document that contains this attribute, or 0 if there is no parent document. xml_document<Ch> *document() const { if (xml_node<Ch> *node = this->parent()) { while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0; } else return 0; } //! Gets previous attribute, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *previous_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return this->m_parent ? m_prev_attribute : 0; } //! Gets next attribute, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *next_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return this->m_parent ? m_next_attribute : 0; } private: xml_attribute<Ch> *m_prev_attribute; // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero xml_attribute<Ch> *m_next_attribute; // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero }; /////////////////////////////////////////////////////////////////////////// // XML node //! Class representing a node of XML document. //! Each node may have associated name and value strings, which are available through name() and value() functions. //! Interpretation of name and value depends on type of the node. //! Type of node can be determined by using type() function. //! <br><br> //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. //! Thus, this text must persist in the memory for the lifetime of node. //! \param Ch Character type to use. template<class Ch = char> class xml_node: public xml_base<Ch> { public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction //! Constructs an empty node with the specified type. //! Consider using memory_pool of appropriate document to allocate nodes manually. //! \param type Type of node to construct. xml_node(node_type type) : m_type(type) , m_first_node(0) , m_first_attribute(0) { } /////////////////////////////////////////////////////////////////////////// // Node data access //! Gets type of node. //! \return Type of node. node_type type() const { return m_type; } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets document of which node is a child. //! \return Pointer to document that contains this node, or 0 if there is no parent document. xml_document<Ch> *document() const { xml_node<Ch> *node = const_cast<xml_node<Ch> *>(this); while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0; } //! Gets first child node, optionally matching node name. //! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found child, or 0 if not found. xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling()) if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive)) return child; return 0; } else return m_first_node; } //! Gets last child node, optionally matching node name. //! Behaviour is undefined if node has no children. //! Use first_node() to test if node has children. //! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found child, or 0 if not found. xml_node<Ch> *last_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(m_first_node); // Cannot query for last child if node has no children if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *child = m_last_node; child; child = child->previous_sibling()) if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive)) return child; return 0; } else return m_last_node; } //! Gets previous sibling node, optionally matching node name. //! Behaviour is undefined if node has no parent. //! Use parent() to test if node has a parent. //! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found sibling, or 0 if not found. xml_node<Ch> *previous_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive)) return sibling; return 0; } else return m_prev_sibling; } //! Gets next sibling node, optionally matching node name. //! Behaviour is undefined if node has no parent. //! Use parent() to test if node has a parent. //! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found sibling, or 0 if not found. xml_node<Ch> *next_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive)) return sibling; return 0; } else return m_next_sibling; } //! Gets first attribute of node, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *first_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return m_first_attribute; } //! Gets last attribute of node, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *last_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return m_first_attribute ? m_last_attribute : 0; } /////////////////////////////////////////////////////////////////////////// // Node modification //! Sets type of node. //! \param type Type of node to set. void type(node_type type) { m_type = type; } /////////////////////////////////////////////////////////////////////////// // Node manipulation //! Prepends a new child node. //! The prepended child becomes the first child, and all existing children are moved one position back. //! \param child Node to prepend. void prepend_node(xml_node<Ch> *child) { assert(child && !child->parent() && child->type() != node_document); if (first_node()) { child->m_next_sibling = m_first_node; m_first_node->m_prev_sibling = child; } else { child->m_next_sibling = 0; m_last_node = child; } m_first_node = child; child->m_parent = this; child->m_prev_sibling = 0; } //! Appends a new child node. //! The appended child becomes the last child. //! \param child Node to append. void append_node(xml_node<Ch> *child) { assert(child && !child->parent() && child->type() != node_document); if (first_node()) { child->m_prev_sibling = m_last_node; m_last_node->m_next_sibling = child; } else { child->m_prev_sibling = 0; m_first_node = child; } m_last_node = child; child->m_parent = this; child->m_next_sibling = 0; } //! Inserts a new child node at specified place inside the node. //! All children after and including the specified node are moved one position back. //! \param where Place where to insert the child, or 0 to insert at the back. //! \param child Node to insert. void insert_node(xml_node<Ch> *where, xml_node<Ch> *child) { assert(!where || where->parent() == this); assert(child && !child->parent() && child->type() != node_document); if (where == m_first_node) prepend_node(child); else if (where == 0) append_node(child); else { child->m_prev_sibling = where->m_prev_sibling; child->m_next_sibling = where; where->m_prev_sibling->m_next_sibling = child; where->m_prev_sibling = child; child->m_parent = this; } } //! Removes first child node. //! If node has no children, behaviour is undefined. //! Use first_node() to test if node has children. void remove_first_node() { assert(first_node()); xml_node<Ch> *child = m_first_node; m_first_node = child->m_next_sibling; if (child->m_next_sibling) child->m_next_sibling->m_prev_sibling = 0; else m_last_node = 0; child->m_parent = 0; } //! Removes last child of the node. //! If node has no children, behaviour is undefined. //! Use first_node() to test if node has children. void remove_last_node() { assert(first_node()); xml_node<Ch> *child = m_last_node; if (child->m_prev_sibling) { m_last_node = child->m_prev_sibling; child->m_prev_sibling->m_next_sibling = 0; } else m_first_node = 0; child->m_parent = 0; } //! Removes specified child from the node // \param where Pointer to child to be removed. void remove_node(xml_node<Ch> *where) { assert(where && where->parent() == this); assert(first_node()); if (where == m_first_node) remove_first_node(); else if (where == m_last_node) remove_last_node(); else { where->m_prev_sibling->m_next_sibling = where->m_next_sibling; where->m_next_sibling->m_prev_sibling = where->m_prev_sibling; where->m_parent = 0; } } //! Removes all child nodes (but not attributes). void remove_all_nodes() { for (xml_node<Ch> *node = first_node(); node; node = node->m_next_sibling) node->m_parent = 0; m_first_node = 0; } //! Prepends a new attribute to the node. //! \param attribute Attribute to prepend. void prepend_attribute(xml_attribute<Ch> *attribute) { assert(attribute && !attribute->parent()); if (first_attribute()) { attribute->m_next_attribute = m_first_attribute; m_first_attribute->m_prev_attribute = attribute; } else { attribute->m_next_attribute = 0; m_last_attribute = attribute; } m_first_attribute = attribute; attribute->m_parent = this; attribute->m_prev_attribute = 0; } //! Appends a new attribute to the node. //! \param attribute Attribute to append. void append_attribute(xml_attribute<Ch> *attribute) { assert(attribute && !attribute->parent()); if (first_attribute()) { attribute->m_prev_attribute = m_last_attribute; m_last_attribute->m_next_attribute = attribute; } else { attribute->m_prev_attribute = 0; m_first_attribute = attribute; } m_last_attribute = attribute; attribute->m_parent = this; attribute->m_next_attribute = 0; } //! Inserts a new attribute at specified place inside the node. //! All attributes after and including the specified attribute are moved one position back. //! \param where Place where to insert the attribute, or 0 to insert at the back. //! \param attribute Attribute to insert. void insert_attribute(xml_attribute<Ch> *where, xml_attribute<Ch> *attribute) { assert(!where || where->parent() == this); assert(attribute && !attribute->parent()); if (where == m_first_attribute) prepend_attribute(attribute); else if (where == 0) append_attribute(attribute); else { attribute->m_prev_attribute = where->m_prev_attribute; attribute->m_next_attribute = where; where->m_prev_attribute->m_next_attribute = attribute; where->m_prev_attribute = attribute; attribute->m_parent = this; } } //! Removes first attribute of the node. //! If node has no attributes, behaviour is undefined. //! Use first_attribute() to test if node has attributes. void remove_first_attribute() { assert(first_attribute()); xml_attribute<Ch> *attribute = m_first_attribute; if (attribute->m_next_attribute) { attribute->m_next_attribute->m_prev_attribute = 0; } else m_last_attribute = 0; attribute->m_parent = 0; m_first_attribute = attribute->m_next_attribute; } //! Removes last attribute of the node. //! If node has no attributes, behaviour is undefined. //! Use first_attribute() to test if node has attributes. void remove_last_attribute() { assert(first_attribute()); xml_attribute<Ch> *attribute = m_last_attribute; if (attribute->m_prev_attribute) { attribute->m_prev_attribute->m_next_attribute = 0; m_last_attribute = attribute->m_prev_attribute; } else m_first_attribute = 0; attribute->m_parent = 0; } //! Removes specified attribute from node. //! \param where Pointer to attribute to be removed. void remove_attribute(xml_attribute<Ch> *where) { assert(first_attribute() && where->parent() == this); if (where == m_first_attribute) remove_first_attribute(); else if (where == m_last_attribute) remove_last_attribute(); else { where->m_prev_attribute->m_next_attribute = where->m_next_attribute; where->m_next_attribute->m_prev_attribute = where->m_prev_attribute; where->m_parent = 0; } } //! Removes all attributes of node. void remove_all_attributes() { for (xml_attribute<Ch> *attribute = first_attribute(); attribute; attribute = attribute->m_next_attribute) attribute->m_parent = 0; m_first_attribute = 0; } private: /////////////////////////////////////////////////////////////////////////// // Restrictions // No copying xml_node(const xml_node &); void operator =(const xml_node &); /////////////////////////////////////////////////////////////////////////// // Data members // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0. // This is required for maximum performance, as it allows the parser to omit initialization of // unneded/redundant values. // // The rules are as follows: // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage node_type m_type; // Type of node; always valid xml_node<Ch> *m_first_node; // Pointer to first child node, or 0 if none; always valid xml_node<Ch> *m_last_node; // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero xml_attribute<Ch> *m_first_attribute; // Pointer to first attribute of node, or 0 if none; always valid xml_attribute<Ch> *m_last_attribute; // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero xml_node<Ch> *m_prev_sibling; // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero xml_node<Ch> *m_next_sibling; // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero }; /////////////////////////////////////////////////////////////////////////// // XML document //! This class represents root of the DOM hierarchy. //! It is also an xml_node and a memory_pool through public inheritance. //! Use parse() function to build a DOM tree from a zero-terminated XML text string. //! parse() function allocates memory for nodes and attributes by using functions of xml_document, //! which are inherited from memory_pool. //! To access root node of the document, use the document itself, as if it was an xml_node. //! \param Ch Character type to use. template<class Ch = char> class xml_document: public xml_node<Ch>, public memory_pool<Ch> { public: //! Constructs empty XML document xml_document() : xml_node<Ch>(node_document) { } //! Parses zero-terminated XML string according to given flags. //! Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used. //! The string must persist for the lifetime of the document. //! In case of error, rapidxml::parse_error exception will be thrown. //! <br><br> //! If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. //! Make sure that data is zero-terminated. //! <br><br> //! Document can be parsed into multiple times. //! Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool. //! \param text XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser. template<int Flags> void parse(Ch *text) { assert(text); // Remove current contents this->remove_all_nodes(); this->remove_all_attributes(); // Parse BOM, if any parse_bom<Flags>(text); // Parse children while (1) { // Skip whitespace before node skip<whitespace_pred, Flags>(text); if (*text == 0) break; // Parse and append new child if (*text == Ch('<')) { ++text; // Skip '<' if (xml_node<Ch> *node = parse_node<Flags>(text)) this->append_node(node); } else RAPIDXML_PARSE_ERROR("expected <", text); } } //! Clears the document by deleting all nodes and clearing the memory pool. //! All nodes owned by document pool are destroyed. void clear() { this->remove_all_nodes(); this->remove_all_attributes(); memory_pool<Ch>::clear(); } private: /////////////////////////////////////////////////////////////////////// // Internal character utility functions // Detect whitespace character struct whitespace_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_whitespace[static_cast<unsigned char>(ch)]; } }; // Detect node name character struct node_name_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_node_name[static_cast<unsigned char>(ch)]; } }; // Detect attribute name character struct attribute_name_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_attribute_name[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) struct text_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) that does not require processing struct text_pure_no_ws_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text_pure_no_ws[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) that does not require processing struct text_pure_with_ws_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text_pure_with_ws[static_cast<unsigned char>(ch)]; } }; // Detect attribute value character template<Ch Quote> struct attribute_value_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables<0>::lookup_attribute_data_1[static_cast<unsigned char>(ch)]; if (Quote == Ch('\"')) return internal::lookup_tables<0>::lookup_attribute_data_2[static_cast<unsigned char>(ch)]; return 0; // Should never be executed, to avoid warnings on Comeau } }; // Detect attribute value character template<Ch Quote> struct attribute_value_pure_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast<unsigned char>(ch)]; if (Quote == Ch('\"')) return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast<unsigned char>(ch)]; return 0; // Should never be executed, to avoid warnings on Comeau } }; // Insert coded character, using UTF8 or 8-bit ASCII template<int Flags> static void insert_coded_character(Ch *&text, unsigned long code) { if (Flags & parse_no_utf8) { // Insert 8-bit ASCII character // Todo: possibly verify that code is less than 256 and use replacement char otherwise? text[0] = static_cast<unsigned char>(code); text += 1; } else { // Insert UTF8 sequence if (code < 0x80) // 1 byte sequence { text[0] = static_cast<unsigned char>(code); text += 1; } else if (code < 0x800) // 2 byte sequence { text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xC0); text += 2; } else if (code < 0x10000) // 3 byte sequence { text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xE0); text += 3; } else if (code < 0x110000) // 4 byte sequence { text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xF0); text += 4; } else // Invalid, only codes up to 0x10FFFF are allowed in Unicode { RAPIDXML_PARSE_ERROR("invalid numeric character entity", text); } } } // Skip characters until predicate evaluates to true template<class StopPred, int Flags> static void skip(Ch *&text) { Ch *tmp = text; while (StopPred::test(*tmp)) ++tmp; text = tmp; } // Skip characters until predicate evaluates to true while doing the following: // - replacing XML character entity references with proper characters (&apos; &amp; &quot; &lt; &gt; &#...;) // - condensing whitespace sequences to single space character template<class StopPred, class StopPredPure, int Flags> static Ch *skip_and_expand_character_refs(Ch *&text) { // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip if (Flags & parse_no_entity_translation && !(Flags & parse_normalize_whitespace) && !(Flags & parse_trim_whitespace)) { skip<StopPred, Flags>(text); return text; } // Use simple skip until first modification is detected skip<StopPredPure, Flags>(text); // Use translation skip Ch *src = text; Ch *dest = src; while (StopPred::test(*src)) { // If entity translation is enabled if (!(Flags & parse_no_entity_translation)) { // Test if replacement is needed if (src[0] == Ch('&')) { switch (src[1]) { // &amp; &apos; case Ch('a'): if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';')) { *dest = Ch('&'); ++dest; src += 5; continue; } if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';')) { *dest = Ch('\''); ++dest; src += 6; continue; } break; // &quot; case Ch('q'): if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';')) { *dest = Ch('"'); ++dest; src += 6; continue; } break; // &gt; case Ch('g'): if (src[2] == Ch('t') && src[3] == Ch(';')) { *dest = Ch('>'); ++dest; src += 4; continue; } break; // &lt; case Ch('l'): if (src[2] == Ch('t') && src[3] == Ch(';')) { *dest = Ch('<'); ++dest; src += 4; continue; } break; // &#...; - assumes ASCII case Ch('#'): if (src[2] == Ch('x')) { unsigned long code = 0; src += 3; // Skip &#x while (1) { unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)]; if (digit == 0xFF) break; code = code * 16 + digit; ++src; } insert_coded_character<Flags>(dest, code); // Put character in output } else { unsigned long code = 0; src += 2; // Skip &# while (1) { unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)]; if (digit == 0xFF) break; code = code * 10 + digit; ++src; } insert_coded_character<Flags>(dest, code); // Put character in output } if (*src == Ch(';')) ++src; else RAPIDXML_PARSE_ERROR("expected ;", src); continue; // Something else default: // Ignore, just copy '&' verbatim break; } } } // If whitespace condensing is enabled if (Flags & parse_normalize_whitespace) { // Test if condensing is needed if (whitespace_pred::test(*src)) { *dest = Ch(' '); ++dest; // Put single space in dest ++src; // Skip first whitespace char // Skip remaining whitespace chars while (whitespace_pred::test(*src)) ++src; continue; } } // No replacement, only copy character *dest++ = *src++; } // Return new end text = src; return dest; } /////////////////////////////////////////////////////////////////////// // Internal parsing functions // Parse BOM, if any template<int Flags> void parse_bom(Ch *&text) { // UTF-8? if (static_cast<unsigned char>(text[0]) == 0xEF && static_cast<unsigned char>(text[1]) == 0xBB && static_cast<unsigned char>(text[2]) == 0xBF) { text += 3; // Skup utf-8 bom } } // Parse XML declaration (<?xml...) template<int Flags> xml_node<Ch> *parse_xml_declaration(Ch *&text) { // If parsing of declaration is disabled if (!(Flags & parse_declaration_node)) { // Skip until end of declaration while (text[0] != Ch('?') || text[1] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 2; // Skip '?>' return 0; } // Create declaration xml_node<Ch> *declaration = this->allocate_node(node_declaration); // Skip whitespace before attributes or ?> skip<whitespace_pred, Flags>(text); // Parse declaration attributes parse_node_attributes<Flags>(text, declaration); // Skip ?> if (text[0] != Ch('?') || text[1] != Ch('>')) RAPIDXML_PARSE_ERROR("expected ?>", text); text += 2; return declaration; } // Parse XML comment (<!--...) template<int Flags> xml_node<Ch> *parse_comment(Ch *&text) { // If parsing of comments is disabled if (!(Flags & parse_comment_nodes)) { // Skip until end of comment while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 3; // Skip '-->' return 0; // Do not produce comment node } // Remember value start Ch *value = text; // Skip until end of comment while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Create comment node xml_node<Ch> *comment = this->allocate_node(node_comment); comment->value(value, text - value); // Place zero terminator after comment value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 3; // Skip '-->' return comment; } // Parse DOCTYPE template<int Flags> xml_node<Ch> *parse_doctype(Ch *&text) { // Remember value start Ch *value = text; // Skip to > while (*text != Ch('>')) { // Determine character type switch (*text) { // If '[' encountered, scan for matching ending ']' using naive algorithm with depth // This works for all W3C test files except for 2 most wicked case Ch('['): { ++text; // Skip '[' int depth = 1; while (depth > 0) { switch (*text) { case Ch('['): ++depth; break; case Ch(']'): --depth; break; case 0: RAPIDXML_PARSE_ERROR("unexpected end of data", text); } ++text; } break; } // Error on end of text case Ch('\0'): RAPIDXML_PARSE_ERROR("unexpected end of data", text); // Other character, skip it default: ++text; } } // If DOCTYPE nodes enabled if (Flags & parse_doctype_node) { // Create a new doctype node xml_node<Ch> *doctype = this->allocate_node(node_doctype); doctype->value(value, text - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 1; // skip '>' return doctype; } else { text += 1; // skip '>' return 0; } } // Parse PI template<int Flags> xml_node<Ch> *parse_pi(Ch *&text) { // If creation of PI nodes is enabled if (Flags & parse_pi_nodes) { // Create pi node xml_node<Ch> *pi = this->allocate_node(node_pi); // Extract PI target name Ch *name = text; skip<node_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected PI target", text); pi->name(name, text - name); // Skip whitespace between pi target and pi skip<whitespace_pred, Flags>(text); // Remember start of pi Ch *value = text; // Skip to '?>' while (text[0] != Ch('?') || text[1] != Ch('>')) { if (*text == Ch('\0')) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Set pi value (verbatim, no entity expansion or whitespace normalization) pi->value(value, text - value); // Place zero terminator after name and value if (!(Flags & parse_no_string_terminators)) { pi->name()[pi->name_size()] = Ch('\0'); pi->value()[pi->value_size()] = Ch('\0'); } text += 2; // Skip '?>' return pi; } else { // Skip to '?>' while (text[0] != Ch('?') || text[1] != Ch('>')) { if (*text == Ch('\0')) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 2; // Skip '?>' return 0; } } // Parse and append data // Return character that ends data. // This is necessary because this character might have been overwritten by a terminating 0 template<int Flags> Ch parse_and_append_data(xml_node<Ch> *node, Ch *&text, Ch *contents_start) { // Backup to contents start if whitespace trimming is disabled if (!(Flags & parse_trim_whitespace)) text = contents_start; // Skip until end of data Ch *value = text, *end; if (Flags & parse_normalize_whitespace) end = skip_and_expand_character_refs<text_pred, text_pure_with_ws_pred, Flags>(text); else end = skip_and_expand_character_refs<text_pred, text_pure_no_ws_pred, Flags>(text); // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after > if (Flags & parse_trim_whitespace) { if (Flags & parse_normalize_whitespace) { // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end if (*(end - 1) == Ch(' ')) --end; } else { // Backup until non-whitespace character is found while (whitespace_pred::test(*(end - 1))) --end; } } // If characters are still left between end and value (this test is only necessary if normalization is enabled) // Create new data node if (!(Flags & parse_no_data_nodes)) { xml_node<Ch> *data = this->allocate_node(node_data); data->value(value, end - value); node->append_node(data); } // Add data to parent node if no data exists yet if (!(Flags & parse_no_element_values)) if (*node->value() == Ch('\0')) node->value(value, end - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) { Ch ch = *text; *end = Ch('\0'); return ch; // Return character that ends data; this is required because zero terminator overwritten it } // Return character that ends data return *text; } // Parse CDATA template<int Flags> xml_node<Ch> *parse_cdata(Ch *&text) { // If CDATA is disabled if (Flags & parse_no_data_nodes) { // Skip until end of cdata while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 3; // Skip ]]> return 0; // Do not produce CDATA node } // Skip until end of cdata Ch *value = text; while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Create new cdata node xml_node<Ch> *cdata = this->allocate_node(node_cdata); cdata->value(value, text - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 3; // Skip ]]> return cdata; } // Parse element node template<int Flags> xml_node<Ch> *parse_element(Ch *&text) { // Create element node xml_node<Ch> *element = this->allocate_node(node_element); // Extract element name Ch *name = text; skip<node_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected element name", text); element->name(name, text - name); // Skip whitespace between element name and attributes or > skip<whitespace_pred, Flags>(text); // Parse attributes, if any parse_node_attributes<Flags>(text, element); // Determine ending type if (*text == Ch('>')) { ++text; parse_node_contents<Flags>(text, element); } else if (*text == Ch('/')) { ++text; if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); ++text; } else RAPIDXML_PARSE_ERROR("expected >", text); // Place zero terminator after name if (!(Flags & parse_no_string_terminators)) element->name()[element->name_size()] = Ch('\0'); // Return parsed element return element; } // Determine node type, and parse it template<int Flags> xml_node<Ch> *parse_node(Ch *&text) { // Parse proper node type switch (text[0]) { // <... default: // Parse and append element node return parse_element<Flags>(text); // <?... case Ch('?'): ++text; // Skip ? if ((text[0] == Ch('x') || text[0] == Ch('X')) && (text[1] == Ch('m') || text[1] == Ch('M')) && (text[2] == Ch('l') || text[2] == Ch('L')) && whitespace_pred::test(text[3])) { // '<?xml ' - xml declaration text += 4; // Skip 'xml ' return parse_xml_declaration<Flags>(text); } else { // Parse PI return parse_pi<Flags>(text); } // <!... case Ch('!'): // Parse proper subset of <! node switch (text[1]) { // <!- case Ch('-'): if (text[2] == Ch('-')) { // '<!--' - xml comment text += 3; // Skip '!--' return parse_comment<Flags>(text); } break; // <![ case Ch('['): if (text[2] == Ch('C') && text[3] == Ch('D') && text[4] == Ch('A') && text[5] == Ch('T') && text[6] == Ch('A') && text[7] == Ch('[')) { // '<![CDATA[' - cdata text += 8; // Skip '![CDATA[' return parse_cdata<Flags>(text); } break; // <!D case Ch('D'): if (text[2] == Ch('O') && text[3] == Ch('C') && text[4] == Ch('T') && text[5] == Ch('Y') && text[6] == Ch('P') && text[7] == Ch('E') && whitespace_pred::test(text[8])) { // '<!DOCTYPE ' - doctype text += 9; // skip '!DOCTYPE ' return parse_doctype<Flags>(text); } } // switch // Attempt to skip other, unrecognized node types starting with <! ++text; // Skip ! while (*text != Ch('>')) { if (*text == 0) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } ++text; // Skip '>' return 0; // No node recognized } } // Parse contents of the node - children, data etc. template<int Flags> void parse_node_contents(Ch *&text, xml_node<Ch> *node) { // For all children and text while (1) { // Skip whitespace between > and node contents Ch *contents_start = text; // Store start of node contents before whitespace is skipped skip<whitespace_pred, Flags>(text); Ch next_char = *text; // After data nodes, instead of continuing the loop, control jumps here. // This is because zero termination inside parse_and_append_data() function // would wreak havoc with the above code. // Also, skipping whitespace after data nodes is unnecessary. after_data_node: // Determine what comes next: node closing, child node, data node, or 0? switch (next_char) { // Node closing or child node case Ch('<'): if (text[1] == Ch('/')) { // Node closing text += 2; // Skip '</' if (Flags & parse_validate_closing_tags) { // Skip and validate closing tag name Ch *closing_name = text; skip<node_name_pred, Flags>(text); if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true)) RAPIDXML_PARSE_ERROR("invalid closing tag name", text); } else { // No validation, just skip name skip<node_name_pred, Flags>(text); } // Skip remaining whitespace after node name skip<whitespace_pred, Flags>(text); if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); ++text; // Skip '>' return; // Node closed, finished parsing contents } else { // Child node ++text; // Skip '<' if (xml_node<Ch> *child = parse_node<Flags>(text)) node->append_node(child); } break; // End of data - error case Ch('\0'): RAPIDXML_PARSE_ERROR("unexpected end of data", text); // Data node default: next_char = parse_and_append_data<Flags>(node, text, contents_start); goto after_data_node; // Bypass regular processing after data nodes } } } // Parse XML attributes of the node template<int Flags> void parse_node_attributes(Ch *&text, xml_node<Ch> *node) { // For all attributes while (attribute_name_pred::test(*text)) { // Extract attribute name Ch *name = text; ++text; // Skip first character of attribute name skip<attribute_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected attribute name", name); // Create new attribute xml_attribute<Ch> *attribute = this->allocate_attribute(); attribute->name(name, text - name); node->append_attribute(attribute); // Skip whitespace after attribute name skip<whitespace_pred, Flags>(text); // Skip = if (*text != Ch('=')) RAPIDXML_PARSE_ERROR("expected =", text); ++text; // Add terminating zero after name if (!(Flags & parse_no_string_terminators)) attribute->name()[attribute->name_size()] = 0; // Skip whitespace after = skip<whitespace_pred, Flags>(text); // Skip quote and remember if it was ' or " Ch quote = *text; if (quote != Ch('\'') && quote != Ch('"')) RAPIDXML_PARSE_ERROR("expected ' or \"", text); ++text; // Extract attribute value and expand char refs in it Ch *value = text, *end; const int AttFlags = Flags & ~parse_normalize_whitespace; // No whitespace normalization in attributes if (quote == Ch('\'')) end = skip_and_expand_character_refs<attribute_value_pred<Ch('\'')>, attribute_value_pure_pred<Ch('\'')>, AttFlags>(text); else end = skip_and_expand_character_refs<attribute_value_pred<Ch('"')>, attribute_value_pure_pred<Ch('"')>, AttFlags>(text); // Set attribute value attribute->value(value, end - value); // Make sure that end quote is present if (*text != quote) RAPIDXML_PARSE_ERROR("expected ' or \"", text); ++text; // Skip quote // Add terminating zero after value if (!(Flags & parse_no_string_terminators)) attribute->value()[attribute->value_size()] = 0; // Skip whitespace after attribute value skip<whitespace_pred, Flags>(text); } } }; //! \cond internal namespace internal { // Whitespace (space \n \r \t) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_whitespace[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F }; // Node name (anything but space \n \r \t / > ? \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_node_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) (anything but < \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled // (anything but < \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text_pure_no_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled // (anything but < \0 & space \n \r \t) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text_pure_with_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute name (anything but space \n \r \t / < > = ? ! \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote (anything but ' \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote that does not require processing (anything but ' \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote (anything but " \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote that does not require processing (anything but " \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Digits (dec and hex, 255 denotes end of numeric character reference) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_digits[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255 // F }; // Upper case conversion template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_upcase[256] = { // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A B C D E F 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 0 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, // 1 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, // 2 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // 3 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 4 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, // 5 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 6 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127, // 7 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, // 8 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, // 9 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, // A 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, // B 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, // C 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, // D 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, // E 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255 // F }; } //! \endcond } // Undefine internal macros #undef RAPIDXML_PARSE_ERROR // On MSVC, restore warnings state #ifdef _MSC_VER #pragma warning(pop) #endif #endif
// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/internal/popo/building_blocks/condition_listener.hpp" #include "iceoryx_posh/internal/popo/building_blocks/condition_notifier.hpp" #include "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp" #include "iceoryx_utils/testing/timing_test.hpp" #include "iceoryx_utils/testing/watch_dog.hpp" #include "test.hpp" #include <atomic> #include <memory> #include <thread> #include <type_traits> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::units::duration_literals; class ConditionVariable_test : public Test { public: using NotificationVector_t = ConditionListener::NotificationVector_t; using Type_t = iox::cxx::BestFittingType_t<iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER>; const iox::RuntimeName_t m_runtimeName{"Ferdinand"}; const iox::units::Duration m_timeToWait = 2_s; const iox::units::Duration m_timingTestTime = 100_ms; ConditionVariableData m_condVarData{m_runtimeName}; ConditionListener m_waiter{m_condVarData}; ConditionNotifier m_signaler{m_condVarData, 0U}; vector<ConditionNotifier, iox::MAX_NUMBER_OF_NOTIFIERS_PER_CONDITION_VARIABLE> m_notifiers; void SetUp() override { for (uint64_t i = 0U; i < iox::MAX_NUMBER_OF_NOTIFIERS_PER_CONDITION_VARIABLE; ++i) { m_notifiers.emplace_back(m_condVarData, i); } m_watchdog.watchAndActOnFailure([&] { std::terminate(); }); } Watchdog m_watchdog{m_timeToWait}; iox::posix::Semaphore m_syncSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U).value(); }; TEST_F(ConditionVariable_test, ConditionListenerIsNeitherCopyNorMovable) { EXPECT_FALSE(std::is_copy_constructible<ConditionListener>::value); EXPECT_FALSE(std::is_move_constructible<ConditionListener>::value); EXPECT_FALSE(std::is_copy_assignable<ConditionListener>::value); EXPECT_FALSE(std::is_move_assignable<ConditionListener>::value); } TEST_F(ConditionVariable_test, ConditionNotifierIsNeitherCopyNorMovable) { EXPECT_FALSE(std::is_copy_constructible<ConditionNotifier>::value); EXPECT_FALSE(std::is_move_constructible<ConditionNotifier>::value); EXPECT_FALSE(std::is_copy_assignable<ConditionNotifier>::value); EXPECT_FALSE(std::is_move_assignable<ConditionNotifier>::value); } TEST_F(ConditionVariable_test, NotifyOnceResultsInBeingTriggered) { m_signaler.notify(); EXPECT_TRUE(m_waiter.wasNotified()); } TEST_F(ConditionVariable_test, NoNotifyResultsInNotBeingTriggered) { EXPECT_FALSE(m_waiter.wasNotified()); } TEST_F(ConditionVariable_test, WaitResetsAllNotificationsInWait) { m_signaler.notify(); m_signaler.notify(); m_signaler.notify(); m_waiter.wait(); std::atomic_bool isThreadFinished{false}; std::thread t([&] { m_waiter.wait(); isThreadFinished = true; }); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_FALSE(isThreadFinished.load()); m_signaler.notify(); t.join(); EXPECT_TRUE(isThreadFinished.load()); } TEST_F(ConditionVariable_test, WaitAndNotifyResultsInImmediateTriggerMultiThreaded) { std::atomic<int> counter{0}; std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); IOX_DISCARD_RESULT(m_syncSemaphore.post()); m_waiter.wait(); EXPECT_THAT(counter, Eq(1)); }); IOX_DISCARD_RESULT(m_syncSemaphore.wait()); counter++; m_signaler.notify(); waiter.join(); } TEST_F(ConditionVariable_test, AllNotificationsAreFalseAfterConstruction) { ConditionVariableData sut; for (auto& notification : sut.m_activeNotifications) { EXPECT_THAT(notification, Eq(false)); } } TEST_F(ConditionVariable_test, CorrectRuntimeNameAfterConstructionWithRuntimeName) { EXPECT_THAT(m_condVarData.m_runtimeName.c_str(), StrEq(m_runtimeName)); } TEST_F(ConditionVariable_test, AllNotificationsAreFalseAfterConstructionWithRuntimeName) { for (auto& notification : m_condVarData.m_activeNotifications) { EXPECT_THAT(notification, Eq(false)); } } TEST_F(ConditionVariable_test, NotifyActivatesCorrectIndex) { constexpr Type_t EVENT_INDEX = iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER - 1U; ConditionNotifier sut(m_condVarData, EVENT_INDEX); sut.notify(); for (Type_t i = 0U; i < iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER; i++) { if (i == EVENT_INDEX) { EXPECT_THAT(m_condVarData.m_activeNotifications[i], Eq(true)); } else { EXPECT_THAT(m_condVarData.m_activeNotifications[i], Eq(false)); } } } TEST_F(ConditionVariable_test, TimedWaitWithZeroTimeoutWorks) { ConditionListener sut(m_condVarData); EXPECT_TRUE(sut.timedWait(iox::units::Duration::fromSeconds(0)).empty()); } TEST_F(ConditionVariable_test, TimedWaitWithoutNotificationReturnsEmptyVector) { ConditionListener sut(m_condVarData); EXPECT_TRUE(sut.timedWait(iox::units::Duration::fromMilliseconds(100)).empty()); } TEST_F(ConditionVariable_test, TimedWaitReturnsOneNotifiedIndex) { ConditionListener sut(m_condVarData); ConditionNotifier(m_condVarData, 6U).notify(); auto indices = sut.timedWait(iox::units::Duration::fromMilliseconds(100)); ASSERT_THAT(indices.size(), Eq(1U)); EXPECT_THAT(indices[0U], Eq(6U)); } TEST_F(ConditionVariable_test, TimedWaitReturnsMultipleNotifiedIndices) { ConditionListener sut(m_condVarData); ConditionNotifier(m_condVarData, 5U).notify(); ConditionNotifier(m_condVarData, 15U).notify(); auto indices = sut.timedWait(iox::units::Duration::fromMilliseconds(100)); ASSERT_THAT(indices.size(), Eq(2U)); EXPECT_THAT(indices[0U], Eq(5U)); EXPECT_THAT(indices[1U], Eq(15U)); } TEST_F(ConditionVariable_test, TimedWaitReturnsAllNotifiedIndices) { ConditionListener sut(m_condVarData); for (uint64_t i = 0U; i < iox::MAX_NUMBER_OF_NOTIFIERS_PER_CONDITION_VARIABLE; ++i) { ConditionNotifier(m_condVarData, i).notify(); } auto indices = sut.timedWait(iox::units::Duration::fromMilliseconds(100)); ASSERT_THAT(indices.size(), Eq(iox::MAX_NUMBER_OF_NOTIFIERS_PER_CONDITION_VARIABLE)); for (uint64_t i = 0U; i < iox::MAX_NUMBER_OF_NOTIFIERS_PER_CONDITION_VARIABLE; ++i) { EXPECT_THAT(indices[i], Eq(i)); } } TIMING_TEST_F(ConditionVariable_test, TimedWaitBlocksUntilTimeout, Repeat(5), [&] { ConditionListener listener(m_condVarData); NotificationVector_t activeNotifications; iox::posix::Semaphore threadSetupSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U).value(); std::atomic_bool hasWaited{false}; std::thread waiter([&] { activeNotifications = listener.timedWait(m_timingTestTime); hasWaited.store(true, std::memory_order_relaxed); ASSERT_THAT(activeNotifications.size(), Eq(0U)); }); std::this_thread::sleep_for(std::chrono::milliseconds(2 * m_timingTestTime.toMilliseconds() / 3)); EXPECT_THAT(hasWaited, Eq(false)); std::this_thread::sleep_for(std::chrono::milliseconds(2 * m_timingTestTime.toMilliseconds() / 3)); EXPECT_THAT(hasWaited, Eq(true)); waiter.join(); }) TIMING_TEST_F(ConditionVariable_test, TimedWaitBlocksUntilNotification, Repeat(5), [&] { ConditionListener listener(m_condVarData); NotificationVector_t activeNotifications; iox::posix::Semaphore threadSetupSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U).value(); std::atomic_bool hasWaited{false}; std::thread waiter([&] { activeNotifications = listener.timedWait(m_timingTestTime); hasWaited.store(true, std::memory_order_relaxed); ASSERT_THAT(activeNotifications.size(), Eq(1U)); EXPECT_THAT(activeNotifications[0], 13U); }); std::this_thread::sleep_for(std::chrono::milliseconds(m_timingTestTime.toMilliseconds() / 4)); EXPECT_THAT(hasWaited, Eq(false)); ConditionNotifier(m_condVarData, 13U).notify(); std::this_thread::sleep_for(std::chrono::milliseconds(m_timingTestTime.toMilliseconds() / 4)); EXPECT_THAT(hasWaited, Eq(true)); waiter.join(); }) TEST_F(ConditionVariable_test, WaitIsNonBlockingAfterDestroyAndReturnsEmptyVector) { ConditionListener sut(m_condVarData); sut.destroy(); const auto& activeNotifications = sut.wait(); EXPECT_THAT(activeNotifications.size(), Eq(0U)); } TEST_F(ConditionVariable_test, WaitIsNonBlockingAfterDestroyAndNotifyAndReturnsEmptyVector) { ConditionListener sut(m_condVarData); sut.destroy(); ConditionNotifier notifier(m_condVarData, 0U); notifier.notify(); const auto& activeNotifications = sut.wait(); EXPECT_THAT(activeNotifications.size(), Eq(0U)); } TEST_F(ConditionVariable_test, DestroyWakesUpWaitWhichReturnsEmptyVector) { ConditionListener sut(m_condVarData); NotificationVector_t activeNotifications; std::thread waiter([&] { activeNotifications = sut.wait(); EXPECT_THAT(activeNotifications.size(), Eq(0U)); }); sut.destroy(); waiter.join(); } TEST_F(ConditionVariable_test, GetCorrectNotificationVectorAfterNotifyAndWait) { constexpr Type_t EVENT_INDEX = iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER - 1U; ConditionNotifier notifier(m_condVarData, EVENT_INDEX); ConditionListener listener(m_condVarData); notifier.notify(); const auto& activeNotifications = listener.wait(); ASSERT_THAT(activeNotifications.size(), Eq(1U)); EXPECT_THAT(activeNotifications[0], Eq(EVENT_INDEX)); } TEST_F(ConditionVariable_test, GetCorrectNotificationVectorAfterMultipleNotifyAndWait) { constexpr Type_t FIRST_EVENT_INDEX = iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER - 1U; constexpr Type_t SECOND_EVENT_INDEX = 0U; ConditionNotifier notifier1(m_condVarData, FIRST_EVENT_INDEX); ConditionNotifier notifier2(m_condVarData, SECOND_EVENT_INDEX); ConditionListener listener(m_condVarData); notifier1.notify(); notifier2.notify(); const auto& activeNotifications = listener.wait(); ASSERT_THAT(activeNotifications.size(), Eq(2U)); EXPECT_THAT(activeNotifications[0], Eq(SECOND_EVENT_INDEX)); EXPECT_THAT(activeNotifications[1], Eq(FIRST_EVENT_INDEX)); } TEST_F(ConditionVariable_test, WaitAndNotifyResultsInCorrectNotificationVector) { constexpr Type_t EVENT_INDEX = iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER - 5U; ConditionNotifier notifier(m_condVarData, EVENT_INDEX); ConditionListener listener(m_condVarData); NotificationVector_t activeNotifications; std::thread waiter([&] { activeNotifications = listener.wait(); ASSERT_THAT(activeNotifications.size(), Eq(1U)); EXPECT_THAT(activeNotifications[0], Eq(EVENT_INDEX)); }); notifier.notify(); waiter.join(); } TIMING_TEST_F(ConditionVariable_test, WaitBlocks, Repeat(5), [&] { constexpr Type_t EVENT_INDEX = iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER - 5U; ConditionNotifier notifier(m_condVarData, EVENT_INDEX); ConditionListener listener(m_condVarData); NotificationVector_t activeNotifications; iox::posix::Semaphore threadSetupSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U).value(); std::atomic_bool hasWaited{false}; std::thread waiter([&] { IOX_DISCARD_RESULT(threadSetupSemaphore.post()); activeNotifications = listener.wait(); hasWaited.store(true, std::memory_order_relaxed); ASSERT_THAT(activeNotifications.size(), Eq(1U)); EXPECT_THAT(activeNotifications[0], Eq(EVENT_INDEX)); }); IOX_DISCARD_RESULT(threadSetupSemaphore.wait()); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_THAT(hasWaited, Eq(false)); notifier.notify(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_THAT(hasWaited, Eq(true)); waiter.join(); }) TIMING_TEST_F(ConditionVariable_test, SecondWaitBlocksUntilNewNotification, Repeat(5), [&] { constexpr Type_t FIRST_EVENT_INDEX = iox::MAX_NUMBER_OF_EVENTS_PER_LISTENER - 2U; constexpr Type_t SECOND_EVENT_INDEX = 0U; ConditionNotifier notifier1(m_condVarData, FIRST_EVENT_INDEX); ConditionNotifier notifier2(m_condVarData, SECOND_EVENT_INDEX); ConditionListener listener(m_condVarData); iox::posix::Semaphore threadSetupSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U).value(); std::atomic_bool hasWaited{false}; Watchdog watchdogFirstWait(m_timeToWait); watchdogFirstWait.watchAndActOnFailure([&] { listener.destroy(); }); notifier1.notify(); notifier2.notify(); NotificationVector_t activeNotifications = listener.wait(); ASSERT_THAT(activeNotifications.size(), Eq(2U)); EXPECT_THAT(activeNotifications[0], Eq(SECOND_EVENT_INDEX)); EXPECT_THAT(activeNotifications[1], Eq(FIRST_EVENT_INDEX)); Watchdog watchdogSecondWait(m_timeToWait); watchdogSecondWait.watchAndActOnFailure([&] { listener.destroy(); }); std::thread waiter([&] { IOX_DISCARD_RESULT(threadSetupSemaphore.post()); activeNotifications = listener.wait(); hasWaited.store(true, std::memory_order_relaxed); ASSERT_THAT(activeNotifications.size(), Eq(1U)); EXPECT_THAT(activeNotifications[0], Eq(FIRST_EVENT_INDEX)); for (const auto& notification : m_condVarData.m_activeNotifications) { EXPECT_THAT(notification, Eq(false)); } }); IOX_DISCARD_RESULT(threadSetupSemaphore.wait()); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_THAT(hasWaited, Eq(false)); notifier1.notify(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_THAT(hasWaited, Eq(true)); waiter.join(); }) void waitReturnsSortedListWhenTriggeredInOrder(ConditionVariable_test& test, const function_ref<ConditionListener::NotificationVector_t()>& wait) { for (uint64_t i = 0U; i < test.m_notifiers.size(); ++i) { test.m_notifiers[i].notify(); } auto notifications = wait(); ASSERT_THAT(notifications.size(), Eq(test.m_notifiers.size())); for (uint64_t i = 0U; i < test.m_notifiers.size(); ++i) { EXPECT_THAT(notifications[i], Eq(i)); } } TEST_F(ConditionVariable_test, WaitReturnsSortedListWhenTriggeredInOrder) { waitReturnsSortedListWhenTriggeredInOrder(*this, [this] { return m_waiter.wait(); }); } TEST_F(ConditionVariable_test, TimedWaitReturnsSortedListWhenTriggeredInOrder) { waitReturnsSortedListWhenTriggeredInOrder( *this, [this] { return m_waiter.timedWait(iox::units::Duration::fromSeconds(1)); }); } void waitReturnsSortedListWhenTriggeredInReverseOrder( ConditionVariable_test& test, const function_ref<ConditionListener::NotificationVector_t()>& wait) { for (uint64_t i = 0U; i < test.m_notifiers.size(); ++i) { test.m_notifiers[test.m_notifiers.size() - i - 1U].notify(); } auto notifications = wait(); ASSERT_THAT(notifications.size(), Eq(test.m_notifiers.size())); for (uint64_t i = 0U; i < test.m_notifiers.size(); ++i) { EXPECT_THAT(notifications[i], Eq(i)); } } TEST_F(ConditionVariable_test, WaitReturnsSortedListWhenTriggeredInReverseOrder) { waitReturnsSortedListWhenTriggeredInReverseOrder(*this, [this] { return m_waiter.wait(); }); } TEST_F(ConditionVariable_test, TimedWaitReturnsSortedListWhenTriggeredInReverseOrder) { waitReturnsSortedListWhenTriggeredInReverseOrder( *this, [this] { return m_waiter.timedWait(iox::units::Duration::fromSeconds(1)); }); }
#include <koinos/chain/chronicler.hpp> namespace koinos::chain { void chronicler::set_session( std::shared_ptr< abstract_chronicler_session > s ) { _session = s; } void chronicler::push_event( protocol::event_data&& ev ) { ev.set_sequence( _seq_no ); bool within_session = false; if ( auto session = _session.lock() ) { within_session = true; session->push_event( ev ); } _events.emplace_back( std::make_pair( within_session, std::move( ev ) ) ); _seq_no++; } void chronicler::push_log( const std::string& message ) { if ( auto session = _session.lock() ) session->push_log( message ); else _logs.push_back( message ); } const std::vector< event_bundle >& chronicler::events() { return _events; } const std::vector< std::string >& chronicler::logs() { return _logs; } } // koinos::chain
/* * gucefWEB: GUCEF module providing Web application functionality * for standardized protocols * * Copyright (C) 1998 - 2020. Dinand Vanvelzen * * 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. */ /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #ifndef GUCEF_CORE_CLOGMANAGER_H #include "CLogManager.h" #define GUCEF_CORE_CLOGMANAGER_H #endif /* GUCEF_CORE_CLOGMANAGER_H ? */ #ifndef GUCEF_CORE_DVCPPSTRINGUTILS_H #include "dvcppstringutils.h" #define GUCEF_CORE_DVCPPSTRINGUTILS_H #endif /* GUCEF_CORE_DVCPPSTRINGUTILS_H ? */ #ifndef GUCEF_CORE_CMFILEACCESS_H #include "CMFileAccess.h" #define GUCEF_CORE_CMFILEACCESS_H #endif /* GUCEF_CORE_CMFILEACCESS_H ? */ #ifndef GUCEF_CORE_CURLHANDLERREGISTRY_H #include "CURLHandlerRegistry.h" #define GUCEF_CORE_CURLHANDLERREGISTRY_H #endif /* GUCEF_CORE_CURLHANDLERREGISTRY_H ? */ #include "gucefWEB_CHTTPURLHandler.h" /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace WEB { /*-------------------------------------------------------------------------// // // // UTILITIES // // // //-------------------------------------------------------------------------*/ CHTTPURLHandler::CHTTPURLHandler( void ) : CURLHandler() , m_httpClient( NULL ) , m_transferFinished( false ) {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ CHTTPURLHandler::CHTTPURLHandler( const CHTTPURLHandler& src ) : CURLHandler( src ) , m_httpClient( NULL ) , m_transferFinished( false ) {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ CHTTPURLHandler::~CHTTPURLHandler() {GUCEF_TRACE; if ( NULL != m_httpClient ) { UnsubscribeFrom( m_httpClient ); delete m_httpClient; m_httpClient = NULL; } } /*-------------------------------------------------------------------------*/ CHTTPURLHandler& CHTTPURLHandler::operator=( const CHTTPURLHandler& src ) {GUCEF_TRACE; return *this; } /*-------------------------------------------------------------------------*/ bool CHTTPURLHandler::Activate( CORE::CURL& url ) {GUCEF_TRACE; GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): Activating using URL: " + url.GetURL() ); m_transferFinished = false; delete m_httpClient; m_httpClient = new CHTTPClient( url.GetPulseGenerator() ); SubscribeTo( m_httpClient ); return m_httpClient->Get( url.GetURL() ); } /*-------------------------------------------------------------------------*/ void CHTTPURLHandler::Deactivate( CORE::CURL& url ) {GUCEF_TRACE; GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): Deactivating" ); if ( NULL != m_httpClient ) { m_httpClient->Close(); } } /*-------------------------------------------------------------------------*/ bool CHTTPURLHandler::IsActive( const CORE::CURL& url ) const {GUCEF_TRACE; if ( NULL != m_httpClient ) { return m_httpClient->IsConnected(); } return false; } /*-------------------------------------------------------------------------*/ CORE::CICloneable* CHTTPURLHandler::Clone( void ) const {GUCEF_TRACE; return new CHTTPURLHandler( *this ); } /*-------------------------------------------------------------------------*/ void CHTTPURLHandler::OnNotify( CORE::CNotifier* notifier , const CORE::CEvent& eventid , CORE::CICloneable* eventdata /* = NULL */ ) {GUCEF_TRACE; // We only accept events from our own HTTP client if ( notifier == m_httpClient ) { if ( ( eventid == CHTTPClient::HTTPErrorEvent ) || ( eventid == CHTTPClient::ConnectionErrorEvent ) ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): Data retrieval error" ); NotifyObservers( CIURLEvents::URLDataRetrievalErrorEvent ); return; } if ( eventid == CHTTPClient::HTTPDataRecievedEvent ) { // pass on the eventdata since it's a cloneable buffer it will sort itself out GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): Data received" ); NotifyObservers( CIURLEvents::URLDataRecievedEvent, eventdata ); return; } if ( eventid == CHTTPClient::HTTPTransferFinishedEvent ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): Transfer finished" ); m_transferFinished = true; NotifyObservers( CIURLEvents::URLAllDataRecievedEvent ); return; } if ( eventid == CHTTPClient::ConnectingEvent ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): Connecting" ); NotifyObservers( CIURLEvents::URLActivateEvent ); return; } if ( eventid == CHTTPClient::DisconnectedEvent ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): Disconnected" ); // Check if the transfer has already been completed. If so then the URLAllDataRecievedEvent event was the // final event and we don't have to send anything. If we where still expecting data then we will send the // URLDeactivateEvent event to notify that we deactivated prematurely. if ( !m_transferFinished ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CHTTPURLHandler(" + CORE::PointerToString( this ) + "): The transfer was not finished when we where disconnected!" ); NotifyObservers( CIURLEvents::URLDeactivateEvent ); } return; } } } /*-------------------------------------------------------------------------*/ void CHTTPURLHandler::Register( void ) {GUCEF_TRACE; CORE::CURLHandlerRegistry* registry = &CORE::CCoreGlobal::Instance()->GetUrlHandlerRegistry(); if ( !registry->IsRegistered( "http" ) ) { registry->Register( "http", new CHTTPURLHandler() ); } } /*-------------------------------------------------------------------------*/ const CString& CHTTPURLHandler::GetClassTypeName( void ) const {GUCEF_TRACE; static CString typeName = "GUCEF::COM::CHTTPURLHandler"; return typeName; } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ } /* namespace COM */ } /* namespace GUCEF */ /*-------------------------------------------------------------------------*/
//MIT License //Copyright (c) 2020 bexoft GmbH (mail@bexoft.de) //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 "finalmq/metadataserialize/MetaDataExchange.h" #include "finalmq/metadata/MetaData.h" #include "finalmq/serializejson/ParserJson.h" #include "finalmq/serializejson/SerializerJson.h" #include "finalmq/serializeproto/ParserProto.h" #include "finalmq/serializeproto/SerializerProto.h" #include "finalmq/serializestruct/SerializerStruct.h" #include "finalmq/serializestruct/ParserStruct.h" #include "finalmq/helpers/ZeroCopyBuffer.h" #include <algorithm> namespace finalmq { static MetaTypeId convert(SerializeMetaTypeId value) { return static_cast<MetaTypeId>(static_cast<SerializeMetaTypeId::Enum>(value)); } static SerializeMetaTypeId convert(MetaTypeId value) { return static_cast<SerializeMetaTypeId::Enum>(static_cast<MetaTypeId>(value)); } void MetaDataExchange::importMetaData(const SerializeMetaData& metadata) { // enums for (size_t i = 0; i < metadata.enums.size(); ++i) { const SerializeMetaEnum& enumSource = metadata.enums[i]; std::vector<MetaEnumEntry> entries; for (size_t n = 0; n < enumSource.entries.size(); ++n) { const SerializeMetaEnumEntry& entrySource = enumSource.entries[i]; entries.push_back({entrySource.name, entrySource.id, entrySource.desc}); } MetaDataGlobal::instance().addEnum({enumSource.type, enumSource.desc, std::move(entries)}); } // structs for (size_t i = 0; i < metadata.structs.size(); ++i) { const SerializeMetaStruct& structSource = metadata.structs[i]; std::vector<MetaField> fields; for (size_t n = 0; n < structSource.fields.size(); ++n) { const SerializeMetaField& fieldSource = structSource.fields[i]; int flags = 0; std::for_each(fieldSource.flags.begin(), fieldSource.flags.end(), [&flags] (const SerializeMetaFieldFlags& flag) { flags |= flag; }); fields.push_back({convert(fieldSource.tid), fieldSource.type, fieldSource.name, fieldSource.desc, flags}); } MetaDataGlobal::instance().addStruct({structSource.type, structSource.desc, std::move(fields)}); } } void MetaDataExchange::exportMetaData(SerializeMetaData& metadata) { metadata.enums.clear(); metadata.structs.clear(); // enums const std::unordered_map<std::string, MetaEnum>& enumsSource = MetaDataGlobal::instance().getAllEnums(); for (auto it = enumsSource.begin(); it != enumsSource.end(); ++it) { const MetaEnum& enumSource = it->second; SerializeMetaEnum enumDestination; enumDestination.type = enumSource.getTypeName(); enumDestination.desc = enumSource.getDescription(); for (int n = 0; n < enumSource.getEntrySize(); ++n) { const MetaEnumEntry* entrySource = enumSource.getEntryByIndex(n); assert(entrySource); enumDestination.entries.push_back({entrySource->name, entrySource->id, entrySource->description}); } metadata.enums.push_back(std::move(enumDestination)); } // structs const std::unordered_map<std::string, MetaStruct>& structsSource = MetaDataGlobal::instance().getAllStructs(); for (auto it = structsSource.begin(); it != structsSource.end(); ++it) { const MetaStruct& structSource = it->second; SerializeMetaStruct structDestination; structDestination.type = structSource.getTypeName(); structDestination.desc = structSource.getDescription(); for (int n = 0; n < structSource.getFieldsSize(); ++n) { const MetaField* fieldSource = structSource.getFieldByIndex(n); assert(fieldSource); std::vector<SerializeMetaFieldFlags> flags; for (int k = 0; k < 32; ++k) { std::int32_t flag = 1 << k; if (fieldSource->flags & flag) { flags.push_back(static_cast<SerializeMetaFieldFlags::Enum>(flag)); } } structDestination.fields.push_back({convert(fieldSource->typeId), fieldSource->typeName, fieldSource->name, fieldSource->description, flags}); } metadata.structs.push_back(std::move(structDestination)); } } void MetaDataExchange::importMetaDataJson(const char* json) { SerializeMetaData root; SerializerStruct serializer(root); ParserJson parser(serializer, json); parser.parseStruct("finalmq.SerializeMetaData"); importMetaData(root); } void MetaDataExchange::exportMetaDataJson(std::string& json) { SerializeMetaData root; exportMetaData(root); ZeroCopyBuffer buffer; SerializerJson serializer(buffer, 8192, true, false); ParserStruct parser(serializer, root); parser.parseStruct(); json = buffer.getData(); } void MetaDataExchange::importMetaDataProto(const char* proto, ssize_t size) { SerializeMetaData root; SerializerStruct serializer(root); ParserProto parser(serializer, proto, size); parser.parseStruct("finalmq.SerializeMetaData"); importMetaData(root); } void MetaDataExchange::exportMetaDataProto(std::string& proto) { SerializeMetaData root; exportMetaData(root); ZeroCopyBuffer buffer; SerializerProto serializer(buffer, 8192); ParserStruct parser(serializer, root); parser.parseStruct(); proto = buffer.getData(); } } // namespace finalmq
#include "pch.h" #include <iostream> #include "GraphData.h" #include <regex> GraphData::GraphData() { } void GraphData::Parse(const string& little_langague_data) { ParseLabel(little_langague_data); ParseTicksAndRanges(little_langague_data); ParseCoordinates(little_langague_data); } void GraphData::ParseLabel(const string& little_langague_data) { _label = GetRegexMatches(regex("label ([\\w ,-]+)"), little_langague_data)[0]; cout << "Label: " << _label << endl; } void GraphData::ParseCoordinates(const string& little_langague_data) { regex coordinate{ "([0-9]+) ([0-9]+)" }; const vector<int> matchingGroupIndex = { 1,2 }; auto coordinates = GetRegexMatches(regex("\n([0-9]+) ([0-9]+)"), little_langague_data, 0); for (string x : coordinates) { auto matches = GetRegexMatches(coordinate, x, matchingGroupIndex); Coordinate c { stoi(matches[0]), stoi(matches[1]) }; _coordinates.push_back(c); cout << "Coordinate parsed, x:" << c.x << " y: " << c.y << endl; } } void GraphData::ParseTicksAndRanges(const string& little_langague_data) { regex text{ "([a-z ]+)[a-z]" }; regex numeric{ "[0-9]+" }; auto dataPoints = GetRegexMatches(regex("[a-z ]+ [\\d ]+"), little_langague_data, 0); for (string x : dataPoints) { auto dataPoint = GetRegexMatches(text, x, 0)[0]; cout << "Range and Tick parsed: " << dataPoint << endl; vector<int> values; auto string_numbers = GetRegexMatches(numeric, x, 0); for (string y : string_numbers) { int i = stoi(y); values.push_back(i); cout << i << endl; } _rangesAndTicks.insert(pair<string, vector<int>>(dataPoint, values)); } } vector<string> GraphData::GetRegexMatches(const regex lookup, string data, int groupMatchIndex) { return GetRegexMatches(lookup, data, vector<int> {groupMatchIndex}); } vector<string> GraphData::GetRegexMatches(const regex lookup, const string data, vector<int> groupMatchIndexes) { auto text_iter = data.cbegin(); smatch regexResuts; vector<string> results; while (regex_search(text_iter, data.cend(), regexResuts, lookup)) { for (int x : groupMatchIndexes) { results.push_back(regexResuts[x]); } text_iter = regexResuts[0].second; } return results; }
#include <buffer.hpp> #include "t/string/string_testcase.pb.h" TEMPLATE_TEST_CASE("write string field and check with libprotobuf", "", buffer_test_string, buffer_test_vector, buffer_test_array, buffer_test_external) { TestType buffer; typename TestType::writer_type pw{buffer.buffer()}; TestString::Test msg; SECTION("empty") { pw.add_string(1, ""); msg.ParseFromArray(buffer.data(), buffer.size()); REQUIRE(msg.s().empty()); } SECTION("one") { pw.add_string(1, "x"); msg.ParseFromArray(buffer.data(), buffer.size()); REQUIRE(msg.s() == "x"); } SECTION("string") { pw.add_string(1, "foobar"); msg.ParseFromArray(buffer.data(), buffer.size()); REQUIRE(msg.s() == "foobar"); } }
/* Test: geometry/antipodal_points.cpp Link: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B Note: Find the diameter of a convex polygon */ #include <bits/stdc++.h> using namespace std; typedef complex<double> point; typedef vector<point> polygon; #define NEXT(i) (((i) + 1) % n) double cross(point a, point b) { return imag(conj(a) * b); } double area2(point a, point b, point c) { return cross(b - a, c - a); } vector<pair<int, int>> antipodal(const polygon &P) { vector<pair<int, int>> ans; int n = P.size(); if (P.size() == 2) ans.push_back({ 0, 1 }); if (P.size() < 3) return ans; int q0 = 0; while (abs(area2(P[n - 1], P[0], P[NEXT(q0)])) > abs(area2(P[n - 1], P[0], P[q0]))) ++q0; for (int q = q0, p = 0; q != 0 && p <= q0; ++p) { ans.push_back({ p, q }); while (abs(area2(P[p], P[NEXT(p)], P[NEXT(q)])) > abs(area2(P[p], P[NEXT(p)], P[q]))) { q = NEXT(q); if (p != q0 || q != 0) ans.push_back({ p, q }); else return ans; } if (abs(area2(P[p], P[NEXT(p)], P[NEXT(q)])) == abs(area2(P[p], P[NEXT(p)], P[q]))) { if (p != q0 || q != n - 1) ans.push_back({ p, NEXT(q) }); else ans.push_back({ NEXT(p), q }); } } return ans; } int main(){ int n; cin >> n; polygon P(n); for (int i = 0; i < n; ++i){ double x, y; cin >> x >> y; P[i] = point(x, y); } auto apod = antipodal(P); double diameter = 0.; for (auto a : apod) diameter = max(diameter, abs(P[a.first] - P[a.second])); cout.precision(17); cout << fixed << diameter << endl; }