text
stringlengths
5
1.04M
/****************************************************************************** * * Project: GDAL Utilities * Purpose: Command line application to list info about a multidimensional raster * Author: Even Rouault,<even.rouault at spatialys.com> * * **************************************************************************** * Copyright (c) 2019, Even Rouault <even.rouault at spatialys.com> * * 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 "gdal_version.h" #include "gdal.h" #include "cpl_string.h" #include "cpl_multiproc.h" #include "commonutils.h" #include "gdal_utils_priv.h" CPL_CVSID("$Id: gdalmdiminfo_bin.cpp $") /************************************************************************/ /* Usage() */ /************************************************************************/ static void Usage(const char* pszErrorMsg = nullptr) { printf( "Usage: gdalmdiminfo [--help-general] [-oo NAME=VALUE]* [-arrayoption NAME=VALUE]*\n" " [-detailed] [-nopretty] [-array {array_name}] [-limit {number}]\n" " [-stats] datasetname\n" ); if( pszErrorMsg != nullptr ) fprintf(stderr, "\nFAILURE: %s\n", pszErrorMsg); exit( 1 ); } /************************************************************************/ /* GDALMultiDimInfoOptionsForBinary() */ /************************************************************************/ static GDALMultiDimInfoOptionsForBinary *GDALMultiDimInfoOptionsForBinaryNew(void) { return static_cast<GDALMultiDimInfoOptionsForBinary *>( CPLCalloc(1, sizeof(GDALMultiDimInfoOptionsForBinary))); } /************************************************************************/ /* GDALMultiDimInfoOptionsForBinaryFree() */ /************************************************************************/ static void GDALMultiDimInfoOptionsForBinaryFree( GDALMultiDimInfoOptionsForBinary* psOptionsForBinary ) { if( psOptionsForBinary ) { CPLFree(psOptionsForBinary->pszFilename); CSLDestroy(psOptionsForBinary->papszOpenOptions); CPLFree(psOptionsForBinary); } } /************************************************************************/ /* main() */ /************************************************************************/ MAIN_START(argc, argv) { EarlySetConfigOptions(argc, argv); GDALAllRegister(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); for( int i = 0; argv != nullptr && argv[i] != nullptr; i++ ) { if( EQUAL(argv[i], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); CSLDestroy( argv ); return 0; } else if( EQUAL(argv[i],"--help") ) { Usage(); } } argv = CSLAddString(argv, "-stdout"); GDALMultiDimInfoOptionsForBinary* psOptionsForBinary = GDALMultiDimInfoOptionsForBinaryNew(); GDALMultiDimInfoOptions *psOptions = GDALMultiDimInfoOptionsNew(argv + 1, psOptionsForBinary); if( psOptions == nullptr ) Usage(); if( psOptionsForBinary->pszFilename == nullptr ) Usage("No datasource specified."); GDALDatasetH hDataset = GDALOpenEx( psOptionsForBinary->pszFilename, GDAL_OF_MULTIDIM_RASTER | GDAL_OF_VERBOSE_ERROR, nullptr, psOptionsForBinary->papszOpenOptions, nullptr ); if( !hDataset ) { fprintf( stderr, "gdalmdiminfo failed - unable to open '%s'.\n", psOptionsForBinary->pszFilename ); GDALMultiDimInfoOptionsForBinaryFree(psOptionsForBinary); GDALMultiDimInfoOptionsFree( psOptions ); CSLDestroy( argv ); GDALDumpOpenDatasets( stderr ); GDALDestroyDriverManager(); CPLDumpSharedList( nullptr ); CPLCleanupTLS(); exit(1); } char* pszGDALInfoOutput = GDALMultiDimInfo( hDataset, psOptions ); if( pszGDALInfoOutput ) printf( "%s", pszGDALInfoOutput ); CPLFree( pszGDALInfoOutput ); GDALClose(hDataset); GDALMultiDimInfoOptionsForBinaryFree(psOptionsForBinary); GDALMultiDimInfoOptionsFree( psOptions ); CSLDestroy( argv ); GDALDumpOpenDatasets( stderr ); GDALDestroyDriverManager(); CPLDumpSharedList( nullptr ); CPLCleanupTLS(); exit( 0 ); } MAIN_END
// // TCPSocket.cc // // Copyright 2019-Present Couchbase, Inc. // // Use of this software is governed by the Business Source License included // in the file licenses/BSL-Couchbase.txt. As of the Change Date specified // in that file, in accordance with the Business Source License, use of this // software will be governed by the Apache License, Version 2.0, included in // the file licenses/APL2.txt. // #include "TCPSocket.hh" #include "TLSContext.hh" #include "Poller.hh" #include "Headers.hh" #include "HTTPLogic.hh" #include "Certificate.hh" #include "NetworkInterfaces.hh" #include "WebSocketInterface.hh" #include "SecureRandomize.hh" #include "Error.hh" #include "StringUtil.hh" #include "sockpp/exception.h" #include "sockpp/inet6_address.h" #include "sockpp/tcp_acceptor.h" #include "sockpp/connector.h" #include "sockpp/mbedtls_context.h" #include "sockpp/tls_socket.h" #include "PlatformIO.hh" #include "c4ExceptionUtils.hh" // for ExpectingExceptions #include "slice_stream.hh" #include <chrono> #include <regex> #include <string> #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #include "mbedtls/error.h" #include "mbedtls/ssl.h" #pragma clang diagnostic pop namespace litecore { namespace net { using namespace std; using namespace fleece; using namespace sockpp; using namespace litecore::net; using namespace litecore::websocket; static constexpr size_t kInitialDelimitedReadBufferSize = 1024; static chrono::microseconds secsToMicrosecs(double secs) { return chrono::microseconds(long(secs * 1e6)); } void TCPSocket::initialize() { static once_flag f; call_once(f, [=] { socket::initialize(); }); } #define WSLog (*(LogDomain*)kC4WebSocketLog) TCPSocket::TCPSocket(bool isClient, TLSContext *tls) :_tlsContext(tls) ,_isClient(isClient) { initialize(); } TCPSocket::~TCPSocket() { _socket.reset(); // Make sure socket closes before _tlsContext does if (_onClose) _onClose(); } bool TCPSocket::setSocket(unique_ptr<stream_socket> socket) { Assert(!_socket); _socket = move(socket); if (!checkSocketFailure()) return false; _setTimeout(_timeout); return true; } TLSContext* TCPSocket::tlsContext() { return _tlsContext; } bool TCPSocket::wrapTLS(slice hostname) { if (!_tlsContext) _tlsContext = new TLSContext(_isClient ? TLSContext::Client : TLSContext::Server); string hostnameStr(hostname); auto oldSocket = move(_socket); return setSocket(_tlsContext->_context->wrap_socket(move(oldSocket), (_isClient ? tls_context::CLIENT : tls_context::SERVER), hostnameStr.c_str())); } bool TCPSocket::connected() const { return _socket && !_socket->is_shutdown(); } void TCPSocket::close() { if (connected()) { int fd = fileDescriptor(); _socket->shutdown(); // The shutdown() system call should cause poll() to notify the Poller that the fd is // closed, but sometimes it does not, so send it an interrupt too: if (_nonBlocking) Poller::instance().interrupt(fd); } } sockpp::stream_socket* TCPSocket::actualSocket() const { if (auto socket = _socket.get(); !socket || !socket->is_open()) return nullptr; else if (auto tlsSock = dynamic_cast<tls_socket*>(socket); tlsSock) return &tlsSock->stream(); else return socket; } string TCPSocket::peerAddress() { if (auto socket = actualSocket(); socket) { switch (auto addr = socket->peer_address(); addr.family()) { case AF_INET: return inet_address(addr).to_string(); case AF_INET6: return inet6_address(addr).to_string(); } } return ""; } string TCPSocket::peerTLSCertificateData() { auto tlsSock = dynamic_cast<tls_socket*>(_socket.get()); return tlsSock ? tlsSock->peer_certificate() : ""; } Retained<crypto::Cert> TCPSocket::peerTLSCertificate() { string certData = peerTLSCertificateData(); return certData.empty() ? nullptr : new crypto::Cert(slice(certData)); } #pragma mark - CLIENT SOCKET: ClientSocket::ClientSocket(TLSContext *tls) :TCPSocket(true, tls) { } bool ClientSocket::connect(const Address &addr) { string hostname(slice(addr.hostname)); optional<IPAddress> ipAddr = IPAddress::parse(hostname); unique_ptr<connector> socket; try { // sockpp constructors can throw exceptions. ExpectingExceptions x; unique_ptr<sock_address> sockAddr; if (ipAddr) { // hostname is numeric, either IPv4 or IPv6: sockAddr = ipAddr->sockppAddress(addr.port); } else { // Otherwise it's a DNS name; let sockpp resolve it: sockAddr = make_unique<inet_address>(hostname, addr.port); } socket = make_unique<connector>(); socket->connect(*sockAddr, secsToMicrosecs(timeout())); } catch (const sockpp::sys_error &sx) { auto e = error::convertException(sx); setError(C4ErrorDomain(e.domain), e.code, slice(e.what())); return false; } catch (const sockpp::getaddrinfo_error &gx) { auto e = error::convertException(gx); setError(C4ErrorDomain(e.domain), e.code, slice(e.what())); return false; } return setSocket(move(socket)) && (!addr.isSecure() || wrapTLS(addr.hostname)); } #pragma mark - RESPONDER SOCKET: ResponderSocket::ResponderSocket(TLSContext *tls) :TCPSocket(false, tls) { } bool ResponderSocket::acceptSocket(stream_socket &&s) { return setSocket( make_unique<tcp_socket>(move(s))); } bool ResponderSocket::acceptSocket(unique_ptr<stream_socket> socket) { return setSocket(move(socket)); } #pragma mark - READ/WRITE: static int socketToPosixErrCode(int err); ssize_t TCPSocket::write(slice data) { if (data.size == 0) return 0; ssize_t written = _socket->write(data.buf, data.size); if (written < 0) { if (_nonBlocking && socketToPosixErrCode(_socket->last_error()) == EWOULDBLOCK) return 0; checkStreamError(); } else if (written == 0) { _eofOnWrite = true; } return written; } ssize_t TCPSocket::write_n(slice data) { if (data.size == 0) return 0; ssize_t written = _socket->write_n(data.buf, data.size); if (written < 0) { if (_nonBlocking && socketToPosixErrCode(_socket->last_error()) == EWOULDBLOCK) return 0; checkStreamError(); } return written; } ssize_t TCPSocket::write(vector<slice> &ioByteRanges) { // We are going to cast slice[] to iovec[] since they are identical structs, // but make sure they are actualy identical: static_assert(sizeof(iovec) == sizeof(slice) && sizeof(iovec::iov_base) == sizeof(slice::buf) && sizeof(iovec::iov_len) == sizeof(slice::size), "iovec and slice are incompatible"); ssize_t written = _socket->write(reinterpret_cast<vector<iovec>&>(ioByteRanges)); if (written < 0) { checkStreamError(); return written; } ssize_t remaining = written; for (auto i = ioByteRanges.begin(); i != ioByteRanges.end(); ++i) { remaining -= i->size; if (remaining < 0) { // This slice was only partly written (or unwritten). Adjust its start: i->moveStart(i->size + remaining); // Remove all prior slices: ioByteRanges.erase(ioByteRanges.begin(), i); return written; } } // Looks like everything was written: ioByteRanges.clear(); return written; } // Primitive unbuffered read call. Returns 0 on EOF, -1 on error (and sets _error). // Assumes EWOULDBLOCK is not an error, since it happens normally in non-blocking reads. ssize_t TCPSocket::_read(void *dst, size_t byteCount) { Assert(byteCount > 0); ssize_t n = _socket->read(dst, byteCount); if (n < 0) { if (_nonBlocking && socketToPosixErrCode(_socket->last_error()) == EWOULDBLOCK) return 0; checkStreamError(); } else if (n == 0) { _eofOnRead = true; } return n; } // "Un-read" data by prepending it to the _unread buffer void TCPSocket::pushUnread(slice data) { if (_usuallyFalse(data.size == 0)) return; if (_usuallyTrue(_unreadLen + data.size > _unread.size)) _unread.resize(_unreadLen + data.size); memmove((void*)_unread.offset(data.size), _unread.offset(0), _unreadLen); memcpy((void*)_unread.offset(0), data.buf, data.size); _unreadLen += data.size; } // Read from the socket, or from the unread buffer if it exists ssize_t TCPSocket::read(void *dst, size_t byteCount) { if (_usuallyFalse(_unreadLen > 0)) { // Use up anything left in the buffer: size_t n = min(byteCount, _unreadLen); memcpy(dst, _unread.offset(0), n); memmove((void*)_unread.offset(0), _unread.offset(n), _unreadLen - n); _unreadLen -= n; if (_unreadLen == 0) _unread = nullslice; return n; } else { return _read(dst, byteCount); } } // Read exactly `byteCount` bytes from the socket (or the unread buffer) ssize_t TCPSocket::readExactly(void *dst, size_t byteCount) { ssize_t remaining = byteCount; while (remaining > 0) { auto n = read(dst, remaining); if (n < 0) return n; if (n == 0) { setError(WebSocketDomain, 400, "Premature end of HTTP body"_sl); return n; } remaining -= n; dst = offsetby(dst, n); } return byteCount; } // Read up to the given delimiter. alloc_slice TCPSocket::readToDelimiter(slice delim, bool includeDelim, size_t maxSize) { alloc_slice alloced(kInitialDelimitedReadBufferSize); slice result(alloced.buf, size_t(0)); while (true) { // Read more bytes: ssize_t n = read((void*)result.end(), alloced.size - result.size); if (n < 0) return nullslice; if (n == 0) { setError(WebSocketDomain, 400, "Unexpected EOF"_sl); return nullslice; } result.setSize(result.size + n); // Look for delimiter: slice found = result.find(delim); if (found) { pushUnread(slice(found.end(), result.end())); result.setEnd(found.end()); alloced.resize(result.size - (includeDelim ? 0 : delim.size)); return alloced; } // If allocated buffer is full, grow it: if (result.size == alloced.size) { size_t newSize = min(alloced.size * 2, maxSize); if (newSize == alloced.size) { setError(WebSocketDomain, 431, "Headers too large"_sl); return nullslice; } alloced.resize(newSize); result = slice(alloced.buf, result.size); } } } alloc_slice TCPSocket::readToEOF() { alloc_slice body; body.resize(1024); size_t length = 0; while (true) { ssize_t n = read((void*)&body[length], body.size - length); if (n < 0) { body.reset(); return nullslice; } else if (n == 0) break; length += n; if (length == body.size) body.resize(2 * body.size); } body.resize(length); return body; } alloc_slice TCPSocket::readChunkedHTTPBody() { // <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding#directives> alloc_slice body; size_t chunkLength; do { alloc_slice line = readToDelimiter("\r\n", false); slice_istream reader(line); chunkLength = (size_t)reader.readHex(); if (!reader.eof()) { setError(WebSocketDomain, kCodeProtocolError, "Invalid chunked response data"); return nullslice; } if (chunkLength > 0) { auto start = body.size; body.resize(start + chunkLength); if (readExactly((void*)&body[start], chunkLength) < chunkLength) return nullslice; } char crlf[2]; if (readExactly(crlf, 2) < 2) return nullslice; if (crlf[0] != '\r' || crlf[1] != '\n') { setError(WebSocketDomain, kCodeProtocolError, "Invalid chunked response data"); return nullslice; } } while (chunkLength > 0); return body; } bool TCPSocket::readHTTPBody(const Headers &headers, alloc_slice &body) { int64_t contentLength = headers.getInt("Content-Length"_sl, -1); if (contentLength >= 0) { // Read exactly Content-Length bytes: body.resize(size_t(contentLength)); if (contentLength > 0) { if (readExactly((void*)body.buf, (size_t)contentLength) < contentLength) body.reset(); } } else if (slice xfer = headers["Transfer-Encoding"]; xfer) { if (xfer.caseEquivalent("chunked")) { // Chunked transfer encoding: body = readChunkedHTTPBody(); //TODO: There may be more response headers after the chunks } else { body.reset(); setError(NetworkDomain, kNetErrUnknown, "Unsupported HTTP Transfer-Encoding"); // Other transfer encodings are "gzip", "deflate" } } else if (auto conn = headers["Connection"]; conn.caseEquivalent("close")) { // Connection:Close mode -- read till EOF: body = readToEOF(); } else { body.reset(); setError(WebSocketDomain, kCodeProtocolError, "Unsupported 'Connection' response header"); } return !!body; } #pragma mark - NONBLOCKING / SELECT: bool TCPSocket::setTimeout(double secs) { if (secs == _timeout) return true; if (_socket && !_setTimeout(secs)) return false; _timeout = secs; return true; } bool TCPSocket::_setTimeout(double secs) { std::chrono::microseconds us = secsToMicrosecs(secs); return _socket->read_timeout(us) && _socket->write_timeout(us); } bool TCPSocket::setNonBlocking(bool nb) { bool ok = _socket->set_non_blocking(nb); if (ok) _nonBlocking = nb; else checkStreamError(); return ok; } int TCPSocket::fileDescriptor() { if (auto socket = actualSocket(); socket) return socket->handle(); else return -1; } void TCPSocket::onReadable(function<void()> listener) { addListener(Poller::kReadable, move(listener)); } void TCPSocket::onWriteable(function<void()> listener) { addListener(Poller::kWriteable, move(listener)); } void TCPSocket::onDisconnect(function<void()> listener) { addListener(Poller::kDisconnected, move(listener)); } void TCPSocket::addListener(int event, function<void()> &&listener) { if (int fd = fileDescriptor(); fd >= 0) Poller::instance().addListener(fd, Poller::Event(event), move(listener)); } void TCPSocket::cancelCallbacks() { if (int fd = fileDescriptor(); fd >= 0) Poller::instance().removeListeners(fd); } #pragma mark - ERRORS: void TCPSocket::setError(C4ErrorDomain domain, int code, slice message) { Assert(code != 0); _error = c4error_make(domain, code, message); } bool TCPSocket::checkSocketFailure() { if (*_socket) return true; // TLS handshake failed: int err = _socket->last_error(); if (err == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { // Some more specific errors for certificate validation failures, based on flags: auto tlsSocket = (tls_socket*)_socket.get(); uint32_t flags = tlsSocket->peer_certificate_status(); LogError(WSLog, "TCPSocket TLS handshake failed; cert verify status 0x%02x", flags); if (flags != 0 && flags != UINT32_MAX) { string message = tlsSocket->peer_certificate_status_message(); int code; if (flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) { if(_tlsContext && _tlsContext->onlySelfSignedAllowed()) { code = kNetErrTLSCertUntrusted; message = "Self-signed only mode is active, and a non self-signed certificate was received"; } else { code = kNetErrTLSCertUnknownRoot; } } else if (flags & MBEDTLS_X509_BADCERT_REVOKED) code = kNetErrTLSCertRevoked; else if (flags & MBEDTLS_X509_BADCERT_EXPIRED) code = kNetErrTLSCertExpired; else if (flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) code = kNetErrTLSCertNameMismatch; else if (flags & MBEDTLS_X509_BADCERT_OTHER) code = kNetErrTLSCertUntrusted; else code = kNetErrTLSHandshakeFailed; setError(NetworkDomain, code, slice(message)); } } else if (err <= mbedtls_context::FATAL_ERROR_ALERT_BASE && err >= mbedtls_context::FATAL_ERROR_ALERT_BASE - 0xFF) { // Handle TLS 'fatal alert' when peer rejects our cert: auto alert = mbedtls_context::FATAL_ERROR_ALERT_BASE - err; LogError(WSLog, "TCPSocket TLS handshake failed with fatal alert %d", alert); int code; if (alert == MBEDTLS_SSL_ALERT_MSG_NO_CERT) { code = kNetErrTLSCertRequiredByPeer; } else if (alert >= MBEDTLS_SSL_ALERT_MSG_BAD_CERT && alert <= MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED) { code = kNetErrTLSCertRejectedByPeer; } else { code = kNetErrTLSHandshakeFailed; } setError(NetworkDomain, code, nullslice); } else { checkStreamError(); } return false; } static int socketToPosixErrCode(int err) { #ifdef WIN32 static constexpr struct {long fromErr; int toErr;} kWSAToPosixErr[] = { {WSA_INVALID_HANDLE, EBADF}, {WSA_NOT_ENOUGH_MEMORY, ENOMEM}, {WSA_INVALID_PARAMETER, EINVAL}, {WSAECONNREFUSED, ECONNREFUSED}, {WSAEADDRINUSE, EADDRINUSE}, {WSAEADDRNOTAVAIL, EADDRNOTAVAIL}, {WSAEAFNOSUPPORT, EAFNOSUPPORT}, {WSAECONNABORTED, ECONNABORTED}, {WSAECONNRESET, ECONNRESET}, {WSAEHOSTUNREACH, EHOSTUNREACH}, {WSAENETDOWN, ENETDOWN}, {WSAENETRESET, ENETRESET}, {WSAENETUNREACH, ENETUNREACH}, {WSAENOBUFS, ENOBUFS}, {WSAEISCONN, EISCONN}, {WSAENOTCONN, ENOTCONN}, {WSAETIMEDOUT, ETIMEDOUT}, {WSAELOOP, ELOOP}, {WSAENAMETOOLONG, ENAMETOOLONG}, {WSAEACCES, EACCES}, {WSAEMFILE, EMFILE}, {WSAEWOULDBLOCK, EWOULDBLOCK}, {WSAEALREADY, EALREADY}, {WSAENOTSOCK, ENOTSOCK}, {WSAEDESTADDRREQ, EDESTADDRREQ}, {WSAEPROTOTYPE, EPROTOTYPE}, {WSAENOPROTOOPT, ENOPROTOOPT}, {WSAEPROTONOSUPPORT, EPROTONOSUPPORT}, {0, 0} }; for(int i = 0; kWSAToPosixErr[i].fromErr != 0; ++i) { if(kWSAToPosixErr[i].fromErr == err) { //Log("Mapping WSA error %d to POSIX %d", err, kWSAToPosixErr[i].toErr); return kWSAToPosixErr[i].toErr; } } #endif return err; } static int mbedToNetworkErrCode(int err) { static constexpr struct {int mbed0; int mbed1; int net;} kMbedToNetErr[] = { {MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, kNetErrTLSCertUntrusted}, {-0x3000, -0x2000, kNetErrTLSCertUntrusted}, {-0x7FFF, -0x6000, kNetErrTLSHandshakeFailed}, {0, 0, 0} }; for (int i = 0; kMbedToNetErr[i].mbed0 != 0; ++i) { if (kMbedToNetErr[i].mbed0 <= err && err <= kMbedToNetErr[i].mbed1) return kMbedToNetErr[i].net; } Warn("No mapping for mbedTLS error -0x%04X", -err); return kNetErrUnknown; } void TCPSocket::checkStreamError() { int err = _socket->last_error(); Assert(err != 0); if (err > 0) { err = socketToPosixErrCode(err); string errStr = error::_what(error::POSIX, err); LogWarn(WSLog, "%s got POSIX error %d \"%s\"", (_isClient ? "ClientSocket" : "ResponderSocket"), err, errStr.c_str()); if (err == EWOULDBLOCK) // Occurs in blocking mode when I/O times out setError(NetworkDomain, kC4NetErrTimeout); else setError(POSIXDomain, err); } else { // Negative errors are assumed to be from mbedTLS. char msgbuf[100]; mbedtls_strerror(err, msgbuf, sizeof(msgbuf)); LogWarn(WSLog, "%s got mbedTLS error -0x%04X \"%s\"", (_isClient ? "ClientSocket" : "ResponderSocket"), -err, msgbuf); setError(NetworkDomain, mbedToNetworkErrCode(err), slice(msgbuf)); } } } }
/* * Copyright (c) 2018, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #define TestType(T, BITS, PACKING) \ struct { \ T a : BITS; \ T b : BITS; \ T c : BITS; \ T d : BITS; \ T e : BITS; \ T f : BITS; \ T g : BITS; \ T h : BITS; \ } PACKING #define TestDefine(T, BITS, PACKING, NAME) \ TestType(T, BITS, PACKING) NAME; #define TestAssign(NAME, A, B, C, D, E, F, G, H) \ NAME.a = A; \ NAME.b = B; \ NAME.c = C; \ NAME.d = D; \ NAME.e = E; \ NAME.f = F; \ NAME.g = G; \ NAME.h = H; __attribute__((constructor)) int test() { TestDefine(unsigned int, 1, , uiBool) TestDefine(signed int, 1, , siBool) TestDefine(unsigned int, 1, __attribute__ ((packed)), uiPackedBool) TestDefine(signed int, 1, __attribute__ ((packed)), siPackedBool) TestAssign(uiBool, 1, 0, 1, 0, 1, 0, 1, 0) TestAssign(siBool, 1, 0, 1, 0, 1, 0, 1, 0) TestAssign(uiPackedBool, 1, 0, 1, 0, 1, 0, 1, 0) TestAssign(siPackedBool, 1, 0, 1, 0, 1, 0, 1, 0) TestDefine(unsigned int, 3, , uiTriple) TestDefine(signed int, 3, , siTriple) TestDefine(unsigned int, 3, __attribute__ ((packed)), uiPackedTriple) TestDefine(signed int, 3, __attribute__ ((packed)), siPackedTriple) TestAssign(uiTriple, 0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111) TestAssign(siTriple, 0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111) TestAssign(uiPackedTriple, 0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111) TestAssign(siPackedTriple, 0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111) TestDefine(unsigned long int, 48, , ui48Long) TestDefine(signed long int, 48, , si48Long) TestDefine(unsigned long int, 48, __attribute__ ((packed)), uiPacked48Long) TestDefine(signed long int, 48, __attribute__ ((packed)), siPacked48Long) TestAssign(ui48Long, 140737488355328, 1, 0, 211106232532992, 150119987579016, 18764998447377, 900719925474102, 1351079888211145) TestAssign(si48Long, 140737488355328, 1, 0, 211106232532992, 150119987579016, 18764998447377, 900719925474102, 1351079888211145) TestAssign(uiPacked48Long, 140737488355328, 1, 0, 211106232532992, 150119987579016, 18764998447377, 900719925474102, 1351079888211145) TestAssign(siPacked48Long, 140737488355328, 1, 0, 211106232532992, 150119987579016, 18764998447377, 900719925474102, 1351079888211145) return 0; }
#ifndef __PRAGMAS__ #define __PRAGMAS__ #define DO_QUOTE(arg) #arg #ifndef UNROLL_LEVEL #define UNROLL_LEVEL 4 #endif #if defined(__ve__) #define __ivdep__ DO_QUOTE(_NEC ivdep) #define __novector__ DO_QUOTE(_NEC novector) #define __outerloop_unroll__ DO_QUOTE(_NEC outerloop_unroll(UNROLL_LEVEL)) #elif defined(_SX) #define __ivdep__ DO_QUOTE(cdir nodep) #define __novector__ DO_QUOTE(cdir novector) #define __outerloop_unroll__ DO_QUOTE(cdir outerunroll=UNROLL_LEVEL) #elif defined(__INTEL_COMPILER) #define __ivdep__ DO_QUOTE(ivdep) #define __novector__ DO_QUOTE(novector) #define __outerloop_unroll__ DO_QUOTE(unroll(UNROLL_LEVEL)) #else #define __ivdep__ DO_QUOTE(message("")) #define __novector__ DO_QUOTE(message("")) #define __outerloop_unroll__ DO_QUOTE(message("")) #endif #endif
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): none yet. * * ***** END GPL LICENSE BLOCK ***** * Game object wrapper */ /** \file gameengine/Ketsji/KX_GameObject.cpp * \ingroup ketsji */ #ifdef _MSC_VER /* This warning tells us about truncation of __long__ stl-generated names. * It can occasionally cause DevStudio to have internal compiler warnings. */ # pragma warning(disable : 4786) #endif #include "KX_GameObject.h" #include "BKE_lib_id.h" #include "BKE_mball.h" #include "BKE_modifier.h" #include "BKE_object.h" #include "DNA_modifier_types.h" #include "DRW_render.h" #include "bpy_rna.h" #include "depsgraph/DEG_depsgraph_query.h" #include "eevee_private.h" #include "windowmanager/WM_api.h" #include "windowmanager/WM_types.h" #include "BL_Action.h" #include "BL_ActionManager.h" #include "CM_Message.h" #include "KX_Camera.h" // only for their ::Type #include "KX_ClientObjectInfo.h" #include "KX_CollisionContactPoints.h" #include "KX_FontObject.h" // only for their ::Type #include "KX_Globals.h" #include "KX_Light.h" // only for their ::Type #include "KX_LodLevel.h" #include "KX_LodManager.h" #include "KX_MeshProxy.h" #include "KX_NavMeshObject.h" #include "KX_NetworkMessageScene.h" //Needed for sendMessage() #include "KX_PolyProxy.h" #include "KX_PyMath.h" #include "KX_PythonComponent.h" #include "KX_RayCast.h" #include "KX_SG_NodeRelationships.h" #include "SCA_ISensor.h" #include "SG_Controller.h" #ifdef WITH_PYTHON # include "EXP_PythonCallBack.h" # include "python_utildefines.h" #endif static MT_Vector3 dummy_point = MT_Vector3(0.0f, 0.0f, 0.0f); static MT_Vector3 dummy_scaling = MT_Vector3(1.0f, 1.0f, 1.0f); static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3( 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); KX_GameObject::KX_GameObject(void *sgReplicationInfo, SG_Callbacks callbacks) : SCA_IObject(), m_isReplica(false), // eevee m_visibleAtGameStart(false), // eevee m_forceIgnoreParentTx(false), // eevee m_layer(0), m_lodManager(nullptr), m_currentLodLevel(0), m_pBlenderObject(nullptr), m_pBlenderGroupObject(nullptr), m_bIsNegativeScaling(false), m_objectColor(1.0f, 1.0f, 1.0f, 1.0f), m_bVisible(true), m_bOccluder(false), m_pPhysicsController(nullptr), m_components(NULL), m_pInstanceObjects(nullptr), m_pDupliGroupObject(nullptr), m_actionManager(nullptr) #ifdef WITH_PYTHON , m_attr_dict(nullptr), m_collisionCallbacks(nullptr), m_removeCallbacks(nullptr) #endif { m_ignore_activity_culling = false; m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR); m_pSGNode = new SG_Node(this, sgReplicationInfo, callbacks); // define the relationship between this node and it's parent. KX_NormalParentRelation *parent_relation = KX_NormalParentRelation::New(); m_pSGNode->SetParentRelation(parent_relation); unit_m4(m_origObmat); // eevee unit_m4(m_prevObmat); // eevee }; KX_GameObject::~KX_GameObject() { #ifdef WITH_PYTHON /* onRemove callbacks */ RunOnRemoveCallbacks(); Py_CLEAR(m_removeCallbacks); if (m_attr_dict) { PyDict_Clear(m_attr_dict); /* in case of circular refs or other weird cases */ /* Py_CLEAR: Py_DECREF's and nullptr's */ Py_CLEAR(m_attr_dict); } // Unregister collision callbacks // Do this before we start freeing physics information like m_pClient_info if (m_collisionCallbacks) { UnregisterCollisionCallbacks(); Py_CLEAR(m_collisionCallbacks); } if (m_components) { m_components->Release(); } #endif // WITH_PYTHON /* EEVEE INTEGRATION */ Object *ob = GetBlenderObject(); if (ob) { RestoreObmat(ob); if (ob->gameflag & OB_OVERLAY_COLLECTION) { ob->gameflag &= ~OB_OVERLAY_COLLECTION; } } KX_Scene *scene = GetScene(); if (scene->m_isRuntime) { HideOriginalObject(); RemoveReplicaObject(); } else { // at scene exit if (ob && strcmp(ob->id.name, "OBgame_default_cam") != 0) { SetVisible(m_visibleAtGameStart, false); } RemoveReplicaObject(); if (ob && ob->type == OB_MBALL) { DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); } } /* END OF EEVEE INTEGRATION */ RemoveMeshes(); // is this delete somewhere ? // if (m_sumoObj) // delete m_sumoObj; delete m_pClient_info; // if (m_pSGNode) // delete m_pSGNode; if (m_pSGNode) { // must go through controllers and make sure they will not use us anymore // This is important for KX_BulletPhysicsControllers that unregister themselves // from the object when they are deleted. SGControllerList::iterator contit; SGControllerList &controllers = m_pSGNode->GetSGControllerList(); for (contit = controllers.begin(); contit != controllers.end(); ++contit) { (*contit)->ClearNode(); } m_pSGNode->SetSGClientObject(nullptr); /* m_pSGNode is freed in KX_Scene::RemoveNodeDestructObject */ } if (m_pPhysicsController) { delete m_pPhysicsController; } if (m_actionManager) { delete m_actionManager; } if (m_pDupliGroupObject) { m_pDupliGroupObject->Release(); } if (m_pInstanceObjects) { m_pInstanceObjects->Release(); } if (m_lodManager) { m_lodManager->Release(); GetScene()->RemoveObjFromLodObjList(this); } } /************************EEVEE_INTEGRATION**********************/ void KX_GameObject::SetBlenderObject(Object *obj) { m_pBlenderObject = obj; if (obj) { Scene *scene = GetScene()->GetBlenderScene(); ViewLayer *view_layer = BKE_view_layer_default_view(scene); Base *base = BKE_view_layer_base_find(view_layer, obj); if (base) { // base can be nullptr for objects in instanced collections m_visibleAtGameStart = (base->flag & BASE_HIDDEN) == 0; } } } /* Look at object_transform for original function */ void KX_GameObject::IgnoreParentTxBGE(Main *bmain, Depsgraph *depsgraph, KX_Scene *kxscene, Object *ob) { Object workob; Object *ob_child; Scene *scene_eval = DEG_get_evaluated_scene(depsgraph); CListValue<KX_GameObject> *children = GetChildren(); /* a change was made, adjust the children to compensate */ for (KX_GameObject *gameobj : children) { if (gameobj->GetBlenderObject()->parent == ob) { ob_child = gameobj->GetBlenderObject(); Object *ob_child_eval = DEG_get_evaluated_object(depsgraph, ob_child); BKE_object_apply_mat4(ob_child_eval, ob_child_eval->obmat, true, false); BKE_object_workob_calc_parent(depsgraph, kxscene->GetBlenderScene(), ob_child_eval, &workob); invert_m4_m4(ob_child->parentinv, workob.obmat); /* Copy result of BKE_object_apply_mat4(). */ BKE_object_transform_copy(ob_child, ob_child_eval); /* Make sure evaluated object is in a consistent state with the original one. * It might be needed for applying transform on its children. */ copy_m4_m4(ob_child_eval->parentinv, ob_child->parentinv); BKE_object_eval_transform_all(depsgraph, scene_eval, ob_child_eval); /* Tag for update. * This is because parent matrix did change, so in theory the child object might now be * evaluated to a different location in another editing context. */ if (!OrigObCanBeTransformedInRealtime(ob_child)) { break; } DEG_id_tag_update(&ob_child->id, ID_RECALC_TRANSFORM); } } } bool KX_GameObject::OrigObCanBeTransformedInRealtime(Object *ob) { FluidModifierData *fluidModifierData = (FluidModifierData *)BKE_modifiers_findby_type(ob, eModifierType_Fluid); if (fluidModifierData) { return false; } return true; } void KX_GameObject::SyncTransformWithDepsgraph() { Object *ob = GetBlenderObject(); if (ob) { float loc[3], rot[3][3], size[3]; mat4_to_loc_rot_size(loc, rot, size, ob->obmat); MT_Matrix3x3 orientation; NodeSetWorldPosition(MT_Vector3(loc)); // MT_Matrix3x3's constructor expects a 4x4 matrix orientation = MT_Matrix3x3(); orientation.setValue3x3(*rot); NodeSetGlobalOrientation(orientation); NodeSetWorldScale(MT_Vector3(size)); } } void KX_GameObject::ForceIgnoreParentTx() { m_forceIgnoreParentTx = true; } void KX_GameObject::TagForUpdate(bool is_overlay_pass) { float obmat[4][4]; NodeGetWorldTransform().getValue(&obmat[0][0]); bool staticObject = compare_m4m4(m_prevObmat, obmat, FLT_MIN); bContext *C = KX_GetActiveEngine()->GetContext(); Main *bmain = CTX_data_main(C); Depsgraph *depsgraph = CTX_data_depsgraph_on_load(C); if (!staticObject) { GetScene()->ResetTaaSamples(); } Object *ob_orig = GetBlenderObject(); bool skip_transform = ob_orig->transflag & OB_TRANSFLAG_OVERRIDE_GAME_PRIORITY; if (skip_transform) { SyncTransformWithDepsgraph(); } if (ob_orig && !skip_transform) { Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob_orig); bool applyTransformToOrig = OrigObCanBeTransformedInRealtime(ob_orig); if (applyTransformToOrig) { copy_m4_m4(ob_orig->obmat, obmat); BKE_object_apply_mat4(ob_orig, ob_orig->obmat, false, true); } copy_m4_m4(ob_eval->obmat, obmat); BKE_object_apply_mat4(ob_eval, ob_eval->obmat, false, true); if (!staticObject || m_forceIgnoreParentTx) { NodeList &children = m_pSGNode->GetSGChildren(); if (children.size()) { IgnoreParentTxBGE(bmain, depsgraph, GetScene(), ob_orig); } } if (applyTransformToOrig) { /* NORMAL CASE */ if (!staticObject && ob_orig->type != OB_MBALL) { DEG_id_tag_update(&ob_orig->id, ID_RECALC_TRANSFORM); } /* SPECIAL CASE: EXPERIMENTAL -> TEST METABALLS (incomplete) (TODO restore elems position at * ge exit) */ else if (!staticObject && ob_orig->type == OB_MBALL) { if (!BKE_mball_is_basis(ob_orig)) { DEG_id_tag_update(&ob_orig->id, ID_RECALC_GEOMETRY); } else { DEG_id_tag_update(&ob_orig->id, ID_RECALC_TRANSFORM); } } } } /* Wait the end of all render passes (main + overlay) * to evaluate if the objects were static compared to * the previous frame. If the objects are not static, * then evee engine current TAA sample will be set to 1. */ if (GetScene()->GetOverlayCamera() && !is_overlay_pass) { // wait } else if (GetScene()->GetOverlayCamera() && is_overlay_pass) { copy_m4_m4(m_prevObmat, obmat); } else { copy_m4_m4(m_prevObmat, obmat); } m_forceIgnoreParentTx = false; } void KX_GameObject::ReplicateBlenderObject() { Object *ob = GetBlenderObject(); if (ob) { bContext *C = KX_GetActiveEngine()->GetContext(); Main *bmain = CTX_data_main(C); Object *newob; BKE_id_copy_ex(bmain, &ob->id, (ID **)&newob, 0); id_us_min(&newob->id); Scene *scene = GetScene()->GetBlenderScene(); ViewLayer *view_layer = BKE_view_layer_default_view(scene); BKE_collection_object_add_from(bmain, scene, BKE_view_layer_camera_find(view_layer), newob); // add replica where is the active camera newob->base_flag |= (BASE_VISIBLE_VIEWLAYER | BASE_VISIBLE_DEPSGRAPH); newob->restrictflag &= ~OB_RESTRICT_VIEWPORT; GetScene()->TagForCollectionRemap(); if (ob->parent) { if (GetScene()->GetLastReplicatedParentObject()) { newob->parent = GetScene()->GetLastReplicatedParentObject(); if (ob->parent && ob->parent->type == OB_ARMATURE) { ModifierData *mod; for (mod = (ModifierData *)newob->modifiers.first; mod; mod = mod->next) { if (mod->type == eModifierType_Armature) { ((ArmatureModifierData *)mod)->object = newob->parent; } } } GetScene()->ResetLastReplicatedParentObject(); } } // To check again NodeList &children = GetSGNode()->GetSGChildren(); if (children.size() > 0) { GetScene()->SetLastReplicatedParentObject(newob); } DEG_relations_tag_update(bmain); GetScene()->ResetTaaSamples(); m_pBlenderObject = newob; m_isReplica = true; } } void KX_GameObject::RemoveReplicaObject() { Object *ob = GetBlenderObject(); if (ob && m_isReplica) { bContext *C = KX_GetActiveEngine()->GetContext(); Main *bmain = CTX_data_main(C); BKE_id_delete(bmain, ob); SetBlenderObject(nullptr); GetScene()->ResetTaaSamples(); DEG_relations_tag_update(bmain); } } void KX_GameObject::HideOriginalObject() { Object *ob = GetBlenderObject(); if (ob && !m_isReplica && (ob->base_flag & (BASE_VISIBLE_VIEWLAYER | BASE_VISIBLE_DEPSGRAPH)) != 0) { Scene *scene = GetScene()->GetBlenderScene(); ViewLayer *view_layer = BKE_view_layer_default_view(scene); Base *base = BKE_view_layer_base_find(view_layer, ob); if (base) { // As for SetVisible, there are cases (when we use bpy...) where Objects have no base. base->flag |= BASE_HIDDEN; BKE_layer_collection_sync(scene, view_layer); DEG_id_tag_update(&scene->id, ID_RECALC_BASE_FLAGS); GetScene()->m_hiddenObjectsDuringRuntime.push_back(ob); GetScene()->ResetTaaSamples(); } } } void KX_GameObject::RecalcGeometry() { Object *ob = GetBlenderObject(); if (ob) { DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); } } static void suspend_physics_recursive(SG_Node *node, bool freeConstraints) { NodeList &children = node->GetSGChildren(); for (NodeList::iterator childit = children.begin(); !(childit == children.end()); ++childit) { SG_Node *childnode = (*childit); KX_GameObject *clientgameobj = static_cast<KX_GameObject *>((*childit)->GetSGClientObject()); if (clientgameobj != nullptr) { // This is a GameObject clientgameobj->SuspendPhysics(freeConstraints, false); } // if the childobj is nullptr then this may be an inverse parent link // so a non recursive search should still look down this node. suspend_physics_recursive(childnode, freeConstraints); } } /* We Remove Physics controller */ void KX_GameObject::SuspendPhysics(bool freeConstraints, bool childrenRecursive) { if (m_pPhysicsController) { GetPhysicsController()->SuspendPhysics(freeConstraints); } if (childrenRecursive) { suspend_physics_recursive(GetSGNode(), freeConstraints); } } static void restore_physics_recursive(SG_Node *node) { NodeList &children = node->GetSGChildren(); for (NodeList::iterator childit = children.begin(); !(childit == children.end()); ++childit) { SG_Node *childnode = (*childit); KX_GameObject *clientgameobj = static_cast<KX_GameObject *>((*childit)->GetSGClientObject()); if (clientgameobj != nullptr) { // This is a GameObject clientgameobj->RestorePhysics(false); } // if the childobj is nullptr then this may be an inverse parent link // so a non recursive search should still look down this node. restore_physics_recursive(childnode); } } void KX_GameObject::RestorePhysics(bool childrenRecursive) { if (m_pPhysicsController) { GetPhysicsController()->RestorePhysics(); } if (childrenRecursive) { restore_physics_recursive(GetSGNode()); } } static void suspend_logic_recursive(SG_Node *node) { NodeList &children = node->GetSGChildren(); for (NodeList::iterator childit = children.begin(); !(childit == children.end()); ++childit) { SG_Node *childnode = (*childit); KX_GameObject *clientgameobj = static_cast<KX_GameObject *>((*childit)->GetSGClientObject()); if (clientgameobj != nullptr) { // This is a GameObject clientgameobj->SuspendSensors(); } // if the childobj is nullptr then this may be an inverse parent link // so a non recursive search should still look down this node. suspend_logic_recursive(childnode); } } /* We Disable Sensors */ void KX_GameObject::SuspendLogic(bool childrenRecursive) { SuspendSensors(); if (childrenRecursive) { suspend_logic_recursive(GetSGNode()); } } static void restore_logic_recursive(SG_Node *node) { NodeList &children = node->GetSGChildren(); for (NodeList::iterator childit = children.begin(); !(childit == children.end()); ++childit) { SG_Node *childnode = (*childit); KX_GameObject *clientgameobj = static_cast<KX_GameObject *>((*childit)->GetSGClientObject()); if (clientgameobj != nullptr) { // This is a GameObject clientgameobj->ResumeSensors(); } // if the childobj is nullptr then this may be an inverse parent link // so a non recursive search should still look down this node. restore_logic_recursive(childnode); } } void KX_GameObject::RestoreLogic(bool childrenRecursive) { ResumeSensors(); if (childrenRecursive) { restore_logic_recursive(GetSGNode()); } } void KX_GameObject::AddDummyLodManager(RAS_MeshObject *meshObj, Object *ob) { m_lodManager = new KX_LodManager(meshObj, ob); m_lodManager->AddRef(); GetScene()->AddObjToLodObjList(this); } bool KX_GameObject::IsReplica() { return m_isReplica; } void KX_GameObject::SetIsReplicaObject() { m_isReplica = true; } void KX_GameObject::BackupObmat(Object *ob) { if (ob) { copy_m4_m4(m_origObmat, ob->obmat); } } void KX_GameObject::RestoreObmat(Object *ob) { if (ob) { Scene *sce = GetScene()->GetBlenderScene(); if (sce->gm.flag & GAME_USE_UNDO && ob->type != OB_CAMERA && OrigObCanBeTransformedInRealtime(ob)) { copy_m4_m4(ob->obmat, m_origObmat); BKE_object_apply_mat4(ob, ob->obmat, false, true); DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); } } } /********************End of EEVEE INTEGRATION*********************/ KX_GameObject *KX_GameObject::GetClientObject(KX_ClientObjectInfo *info) { if (!info) return nullptr; return info->m_gameobject; } std::string KX_GameObject::GetName() { return m_name; } /* Set the name of the value */ void KX_GameObject::SetName(const std::string &name) { m_name = name; } PHY_IPhysicsController *KX_GameObject::GetPhysicsController() { return m_pPhysicsController; } KX_GameObject *KX_GameObject::GetDupliGroupObject() { return m_pDupliGroupObject; } CListValue<KX_GameObject> *KX_GameObject::GetInstanceObjects() { return m_pInstanceObjects; } void KX_GameObject::AddInstanceObjects(KX_GameObject *obj) { if (!m_pInstanceObjects) m_pInstanceObjects = new CListValue<KX_GameObject>(); obj->AddRef(); m_pInstanceObjects->Add(obj); } void KX_GameObject::RemoveInstanceObject(KX_GameObject *obj) { BLI_assert(m_pInstanceObjects); m_pInstanceObjects->RemoveValue(obj); obj->Release(); } void KX_GameObject::RemoveDupliGroupObject() { if (m_pDupliGroupObject) { m_pDupliGroupObject->Release(); m_pDupliGroupObject = nullptr; } } void KX_GameObject::SetDupliGroupObject(KX_GameObject *obj) { obj->AddRef(); m_pDupliGroupObject = obj; } void KX_GameObject::AddConstraint(bRigidBodyJointConstraint *cons) { m_constraints.push_back(cons); } std::vector<bRigidBodyJointConstraint *> KX_GameObject::GetConstraints() { return m_constraints; } void KX_GameObject::ClearConstraints() { m_constraints.clear(); } KX_GameObject *KX_GameObject::GetParent() { KX_GameObject *result = nullptr; SG_Node *node = m_pSGNode; while (node && !result) { node = node->GetSGParent(); if (node) result = (KX_GameObject *)node->GetSGClientObject(); } return result; } void KX_GameObject::SetParent(KX_GameObject *obj, bool addToCompound, bool ghost) { // check on valid node in case a python controller holds a reference to a deleted object if (obj && GetSGNode()->GetSGParent() != obj->GetSGNode() && // not already parented to same object !GetSGNode()->IsAncessor(obj->GetSGNode()) && // no parenting loop this != obj) // not the object itself { if (!(GetScene()->GetInactiveList()->SearchValue(obj) != GetScene()->GetObjectList()->SearchValue(this))) { CM_FunctionWarning( "child and parent are not in the same game objects list (active or inactive). This " "operation is forbidden."); return; } // Make sure the objects have some scale MT_Vector3 scale1 = NodeGetWorldScaling(); MT_Vector3 scale2 = obj->NodeGetWorldScaling(); if (fabs(scale2[0]) < (MT_Scalar)FLT_EPSILON || fabs(scale2[1]) < (MT_Scalar)FLT_EPSILON || fabs(scale2[2]) < (MT_Scalar)FLT_EPSILON || fabs(scale1[0]) < (MT_Scalar)FLT_EPSILON || fabs(scale1[1]) < (MT_Scalar)FLT_EPSILON || fabs(scale1[2]) < (MT_Scalar)FLT_EPSILON) { return; } KX_Scene *scene = GetScene(); // Remove us from our old parent and set our new parent RemoveParent(); obj->GetSGNode()->AddChild(GetSGNode()); if (m_pPhysicsController) { m_pPhysicsController->SuspendDynamics(ghost); } // Set us to our new scale, position, and orientation scale2[0] = 1.0f / scale2[0]; scale2[1] = 1.0f / scale2[1]; scale2[2] = 1.0f / scale2[2]; scale1 = scale1 * scale2; MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse(); MT_Vector3 newpos = invori * (NodeGetWorldPosition() - obj->NodeGetWorldPosition()) * scale2; NodeSetLocalScale(scale1); NodeSetLocalPosition(MT_Vector3(newpos[0], newpos[1], newpos[2])); NodeSetLocalOrientation(invori * NodeGetWorldOrientation()); NodeUpdateGS(0.f); // object will now be a child, it must be removed from the parent list CListValue<KX_GameObject> *rootlist = scene->GetRootParentList(); if (rootlist->RemoveValue(this)) // the object was in parent list, decrement ref count as it's now removed Release(); // if the new parent is a compound object, add this object shape to the compound shape. // step 0: verify this object has physical controller if (m_pPhysicsController && addToCompound) { // step 1: find the top parent (not necessarily obj) KX_GameObject *rootobj = (KX_GameObject *)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject(); // step 2: verify it has a physical controller and compound shape if (rootobj != nullptr && rootobj->m_pPhysicsController != nullptr && rootobj->m_pPhysicsController->IsCompound()) { rootobj->m_pPhysicsController->AddCompoundChild(m_pPhysicsController); } } } } void KX_GameObject::RemoveParent() { // check on valid node in case a python controller holds a reference to a deleted object if (GetSGNode()->GetSGParent()) { // get the root object to remove us from compound object if needed KX_GameObject *rootobj = (KX_GameObject *)GetSGNode()->GetRootSGParent()->GetSGClientObject(); // Set us to the right spot GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling()); GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation()); GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition()); // Remove us from our parent GetSGNode()->DisconnectFromParent(); NodeUpdateGS(0.f); KX_Scene *scene = GetScene(); // the object is now a root object, add it to the parentlist CListValue<KX_GameObject> *rootlist = scene->GetRootParentList(); if (!rootlist->SearchValue(this)) // object was not in root list, add it now and increment ref count rootlist->Add(CM_AddRef(this)); if (m_pPhysicsController) { // in case this controller was added as a child shape to the parent if (rootobj != nullptr && rootobj->m_pPhysicsController != nullptr && rootobj->m_pPhysicsController->IsCompound()) { rootobj->m_pPhysicsController->RemoveCompoundChild(m_pPhysicsController); } m_pPhysicsController->RestoreDynamics(); if (m_pPhysicsController->IsDynamic() && (rootobj != nullptr && rootobj->m_pPhysicsController)) { // dynamic object should remember the velocity they had while being parented MT_Vector3 childPoint = GetSGNode()->GetWorldPosition(); MT_Vector3 rootPoint = rootobj->GetSGNode()->GetWorldPosition(); MT_Vector3 relPoint; relPoint = (childPoint - rootPoint); MT_Vector3 linVel = rootobj->m_pPhysicsController->GetVelocity(relPoint); MT_Vector3 angVel = rootobj->m_pPhysicsController->GetAngularVelocity(); m_pPhysicsController->SetLinearVelocity(linVel, false); m_pPhysicsController->SetAngularVelocity(angVel, false); } } } } BL_ActionManager *KX_GameObject::GetActionManager() { // We only want to create an action manager if we need it if (!m_actionManager) { GetScene()->AddAnimatedObject(this); m_actionManager = new BL_ActionManager(this); } return m_actionManager; } bool KX_GameObject::PlayAction(const std::string &name, float start, float end, short layer, short priority, float blendin, short play_mode, float layer_weight, short ipo_flags, float playback_speed, short blend_mode) { return GetActionManager()->PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode); } void KX_GameObject::StopAction(short layer) { GetActionManager()->StopAction(layer); } void KX_GameObject::RemoveTaggedActions() { GetActionManager()->RemoveTaggedActions(); } bool KX_GameObject::IsActionDone(short layer) { return GetActionManager()->IsActionDone(layer); } void KX_GameObject::UpdateActionManager(float curtime, bool applyToObject) { GetActionManager()->Update(curtime, applyToObject); } float KX_GameObject::GetActionFrame(short layer) { return GetActionManager()->GetActionFrame(layer); } const std::string KX_GameObject::GetActionName(short layer) { return GetActionManager()->GetActionName(layer); } void KX_GameObject::SetActionFrame(short layer, float frame) { GetActionManager()->SetActionFrame(layer, frame); } bAction *KX_GameObject::GetCurrentAction(short layer) { return GetActionManager()->GetCurrentAction(layer); } void KX_GameObject::SetPlayMode(short layer, short mode) { GetActionManager()->SetPlayMode(layer, mode); } void KX_GameObject::ProcessReplica() { SCA_IObject::ProcessReplica(); ReplicateBlenderObject(); m_pPhysicsController = nullptr; m_pSGNode = nullptr; /* Dupli group and instance list are set later in replication. * See KX_Scene::DupliGroupRecurse. */ m_pDupliGroupObject = nullptr; m_pInstanceObjects = nullptr; m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info); m_pClient_info->m_gameobject = this; m_actionManager = nullptr; m_state = 0; if (m_lodManager) { m_lodManager->AddRef(); GetScene()->AddObjToLodObjList(this); } #ifdef WITH_PYTHON if (m_attr_dict) m_attr_dict = PyDict_Copy(m_attr_dict); if (m_components) { m_components = (CListValue<KX_PythonComponent> *)m_components->GetReplica(); for (KX_PythonComponent *component : m_components) { component->SetGameObject(this); } } #endif } void KX_GameObject::SetUserCollisionGroup(unsigned short group) { m_userCollisionGroup = group; if (m_pPhysicsController) m_pPhysicsController->RefreshCollisions(); } void KX_GameObject::SetUserCollisionMask(unsigned short mask) { m_userCollisionMask = mask; if (m_pPhysicsController) m_pPhysicsController->RefreshCollisions(); } unsigned short KX_GameObject::GetUserCollisionGroup() { return m_userCollisionGroup; } unsigned short KX_GameObject::GetUserCollisionMask() { return m_userCollisionMask; } bool KX_GameObject::CheckCollision(KX_GameObject *other) { return this->m_userCollisionGroup & other->m_userCollisionMask; } CValue *KX_GameObject::GetReplica() { KX_GameObject *replica = new KX_GameObject(*this); // this will copy properties and so on... replica->ProcessReplica(); return replica; } bool KX_GameObject::IsDynamic() const { if (m_pPhysicsController) { return m_pPhysicsController->IsDynamic(); } return false; } bool KX_GameObject::IsDynamicsSuspended() const { if (m_pPhysicsController) return m_pPhysicsController->IsDynamicsSuspended(); return false; } float KX_GameObject::getLinearDamping() const { if (m_pPhysicsController) return m_pPhysicsController->GetLinearDamping(); return 0; } float KX_GameObject::getAngularDamping() const { if (m_pPhysicsController) return m_pPhysicsController->GetAngularDamping(); return 0; } void KX_GameObject::setLinearDamping(float damping) { if (m_pPhysicsController) m_pPhysicsController->SetLinearDamping(damping); } void KX_GameObject::setAngularDamping(float damping) { if (m_pPhysicsController) m_pPhysicsController->SetAngularDamping(damping); } void KX_GameObject::setDamping(float linear, float angular) { if (m_pPhysicsController) m_pPhysicsController->SetDamping(linear, angular); } void KX_GameObject::setCcdMotionThreshold(float motion_threshold) { if (m_pPhysicsController) m_pPhysicsController->SetCcdMotionThreshold(motion_threshold); } void KX_GameObject::setCcdSweptSphereRadius(float swept_sphere_radius) { if (m_pPhysicsController) m_pPhysicsController->SetCcdSweptSphereRadius(swept_sphere_radius); } void KX_GameObject::ApplyForce(const MT_Vector3 &force, bool local) { if (m_pPhysicsController) m_pPhysicsController->ApplyForce(force, local); } void KX_GameObject::ApplyTorque(const MT_Vector3 &torque, bool local) { if (m_pPhysicsController) m_pPhysicsController->ApplyTorque(torque, local); } void KX_GameObject::ApplyMovement(const MT_Vector3 &dloc, bool local) { if (m_pPhysicsController) // (IsDynamic()) { m_pPhysicsController->RelativeTranslate(dloc, local); } GetSGNode()->RelativeTranslate(dloc, GetSGNode()->GetSGParent(), local); NodeUpdateGS(0.0f); } void KX_GameObject::ApplyRotation(const MT_Vector3 &drot, bool local) { MT_Matrix3x3 rotmat(drot); GetSGNode()->RelativeRotate(rotmat, local); if (m_pPhysicsController) { // (IsDynamic()) m_pPhysicsController->RelativeRotate(rotmat, local); } NodeUpdateGS(0.0f); } void KX_GameObject::UpdateBlenderObjectMatrix(Object *blendobj) { if (!blendobj) blendobj = m_pBlenderObject; if (blendobj) { float obmat[4][4]; NodeGetWorldTransform().getValue(&obmat[0][0]); copy_m4_m4(blendobj->obmat, obmat); /* Making sure it's updated. (To move volumes) */ invert_m4_m4(blendobj->imat, blendobj->obmat); } } void KX_GameObject::UpdateBuckets() { } void KX_GameObject::RemoveMeshes() { // note: meshes can be shared, and are deleted by BL_BlenderSceneConverter m_meshes.clear(); } bool KX_GameObject::UseCulling() const { return false; } void KX_GameObject::SetLodManager(KX_LodManager *lodManager) { // Reset lod level to avoid overflow index in KX_LodManager::GetLevel. m_currentLodLevel = 0; // Restore object original mesh. if (!lodManager && m_lodManager && m_lodManager->GetLevelCount() > 0) { KX_Scene *scene = GetScene(); RAS_MeshObject *origmesh = m_lodManager->GetLevel(0)->GetMesh(); scene->ReplaceMesh(this, origmesh, true, false); } if (m_lodManager) { m_lodManager->Release(); } m_lodManager = lodManager; if (m_lodManager) { m_lodManager->AddRef(); } } KX_LodManager *KX_GameObject::GetLodManager() const { return m_lodManager; } void KX_GameObject::UpdateLod(const MT_Vector3 &cam_pos, float lodfactor) { if (!m_lodManager) { return; } KX_Scene *scene = GetScene(); const float distance2 = NodeGetWorldPosition().distance2(cam_pos) * (lodfactor * lodfactor); KX_LodLevel *lodLevel = m_lodManager->GetLevel(scene, m_currentLodLevel, distance2); if (lodLevel) { RAS_MeshObject *mesh = lodLevel->GetMesh(); if (mesh != m_meshes[0]) { scene->ReplaceMesh(this, mesh, true, false); } m_currentLodLevel = lodLevel->GetLevel(); } KX_LodLevel *currentLodLevel = m_lodManager->GetLevel(m_currentLodLevel); if (currentLodLevel) { bContext *C = KX_GetActiveEngine()->GetContext(); Depsgraph *depsgraph = CTX_data_expect_evaluated_depsgraph(C); /* Here we want to change the object which will be rendered, then the evaluated object by the * depsgraph */ Object *ob_eval = DEG_get_evaluated_object(depsgraph, GetBlenderObject()); Object *eval_lod_ob = DEG_get_evaluated_object(depsgraph, currentLodLevel->GetObject()); /* Try to get the object with all modifiers applied */ ob_eval->data = eval_lod_ob->data; } } void KX_GameObject::UpdateTransform() { // HACK: saves function call for dynamic object, they are handled differently if (m_pPhysicsController && !m_pPhysicsController->IsDynamic()) m_pPhysicsController->SetTransform(); } void KX_GameObject::UpdateTransformFunc(SG_Node *node, void *gameobj, void *scene) { ((KX_GameObject *)gameobj)->UpdateTransform(); } void KX_GameObject::SynchronizeTransform() { // only used for sensor object, do full synchronization as bullet doesn't do it if (m_pPhysicsController) m_pPhysicsController->SetTransform(); } void KX_GameObject::SynchronizeTransformFunc(SG_Node *node, void *gameobj, void *scene) { ((KX_GameObject *)gameobj)->SynchronizeTransform(); } void KX_GameObject::InitIPO(bool ipo_as_force, bool ipo_add, bool ipo_local) { SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin(); while (it != GetSGNode()->GetSGControllerList().end()) { (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true); (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force); (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add); (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local); it++; } } void KX_GameObject::UpdateIPO(float curframetime, bool recurse) { // just the 'normal' update procedure. GetSGNode()->SetSimulatedTimeThread(curframetime, recurse); GetSGNode()->UpdateWorldDataThread(curframetime); } bool KX_GameObject::GetVisible(void) { return m_bVisible; } static void setVisible_recursive(SG_Node *node, bool v) { const NodeList &children = node->GetSGChildren(); for (SG_Node *childnode : children) { KX_GameObject *clientgameobj = static_cast<KX_GameObject*>(childnode->GetSGClientObject()); if (clientgameobj != nullptr) // This is a GameObject clientgameobj->SetVisible(v, 0); // if the childobj is nullptr then this may be an inverse parent link // so a non recursive search should still look down this node. setVisible_recursive(childnode, v); } } void KX_GameObject::SetVisible(bool v, bool recursive) { Object *ob = GetBlenderObject(); if (ob) { Scene *scene = GetScene()->GetBlenderScene(); ViewLayer *view_layer = BKE_view_layer_default_view(scene); Base *base = BKE_view_layer_base_find(view_layer, ob); if (base) { // Base can be NULL for objects in linked collections... if (v) { base->flag &= ~BASE_HIDDEN; } else { base->flag |= BASE_HIDDEN; } BKE_layer_collection_sync(scene, view_layer); DEG_id_tag_update(&scene->id, ID_RECALC_BASE_FLAGS); GetScene()->ResetTaaSamples(); } } if (recursive) { setVisible_recursive(GetSGNode(), v); } m_bVisible = v; } static void setOccluder_recursive(SG_Node *node, bool v) { const NodeList &children = node->GetSGChildren(); for (SG_Node *childnode : children) { KX_GameObject *clientgameobj = static_cast<KX_GameObject*>(childnode->GetSGClientObject()); if (clientgameobj != nullptr) // This is a GameObject clientgameobj->SetOccluder(v, false); // if the childobj is nullptr then this may be an inverse parent link // so a non recursive search should still look down this node. setOccluder_recursive(childnode, v); } } void KX_GameObject::SetOccluder(bool v, bool recursive) { m_bOccluder = v; if (recursive) setOccluder_recursive(GetSGNode(), v); } static void setDebug_recursive(KX_Scene *scene, SG_Node *node, bool debug) { const NodeList &children = node->GetSGChildren(); for (SG_Node *childnode : children) { KX_GameObject *clientgameobj = static_cast<KX_GameObject*>(childnode->GetSGClientObject()); if (clientgameobj != nullptr) { if (debug) { if (!scene->ObjectInDebugList(clientgameobj)) scene->AddObjectDebugProperties(clientgameobj); } else scene->RemoveObjectDebugProperties(clientgameobj); } /* if the childobj is nullptr then this may be an inverse parent link * so a non recursive search should still look down this node. */ setDebug_recursive(scene, childnode, debug); } } void KX_GameObject::SetUseDebugProperties(bool debug, bool recursive) { KX_Scene *scene = GetScene(); if (debug) { if (!scene->ObjectInDebugList(this)) scene->AddObjectDebugProperties(this); } else scene->RemoveObjectDebugProperties(this); if (recursive) setDebug_recursive(scene, GetSGNode(), debug); } void KX_GameObject::SetLayer(int l) { m_layer = l; } int KX_GameObject::GetLayer(void) { return m_layer; } void KX_GameObject::addLinearVelocity(const MT_Vector3 &lin_vel, bool local) { if (m_pPhysicsController) { MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel; m_pPhysicsController->SetLinearVelocity(lv + m_pPhysicsController->GetLinearVelocity(), 0); } } void KX_GameObject::setLinearVelocity(const MT_Vector3 &lin_vel, bool local) { if (m_pPhysicsController) m_pPhysicsController->SetLinearVelocity(lin_vel, local); } void KX_GameObject::setAngularVelocity(const MT_Vector3 &ang_vel, bool local) { if (m_pPhysicsController) m_pPhysicsController->SetAngularVelocity(ang_vel, local); } void KX_GameObject::SetObjectColor(const MT_Vector4 &rgbavec) { m_objectColor = rgbavec; Object *ob_orig = GetBlenderObject(); if (ob_orig && OrigObCanBeTransformedInRealtime(ob_orig) && ELEM(ob_orig->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { copy_v4_v4(ob_orig->color, m_objectColor.getValue()); DEG_id_tag_update(&ob_orig->id, ID_RECALC_SHADING | ID_RECALC_TRANSFORM); GetScene()->ResetTaaSamples(); WM_main_add_notifier(NC_OBJECT | ND_DRAW, &ob_orig->id); } } const MT_Vector4 &KX_GameObject::GetObjectColor() { return m_objectColor; } void KX_GameObject::AlignAxisToVect(const MT_Vector3 &dir, int axis, float fac) { const MT_Scalar eps = 3.0f * MT_EPSILON; MT_Matrix3x3 orimat; MT_Vector3 vect, ori, z, x, y; MT_Scalar len; vect = dir; len = vect.length(); if (MT_fuzzyZero(len)) { CM_FunctionError("null vector!"); return; } if (fac <= 0.0f) { return; } // normalize vect /= len; orimat = GetSGNode()->GetWorldOrientation(); switch (axis) { case 0: // align x axis of new coord system to vect ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); // pivot axis if (1.0f - MT_abs(vect.dot(ori)) < eps) { // vect parallel to pivot? ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); // change the pivot! } if (fac == 1.0f) { x = vect; } else { x = (vect * fac) + ((orimat * MT_Vector3(1.0f, 0.0f, 0.0f)) * (1.0f - fac)); len = x.length(); if (MT_fuzzyZero(len)) x = vect; else x /= len; } y = ori.cross(x); z = x.cross(y); break; case 1: // y axis ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]); if (1.0f - MT_abs(vect.dot(ori)) < eps) { ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); } if (fac == 1.0f) { y = vect; } else { y = (vect * fac) + ((orimat * MT_Vector3(0.0f, 1.0f, 0.0f)) * (1.0f - fac)); len = y.length(); if (MT_fuzzyZero(len)) y = vect; else y /= len; } z = ori.cross(y); x = y.cross(z); break; case 2: // z axis ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); if (1.0f - MT_abs(vect.dot(ori)) < eps) { ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]); } if (fac == 1.0f) { z = vect; } else { z = (vect * fac) + ((orimat * MT_Vector3(0.0f, 0.0f, 1.0f)) * (1.0f - fac)); len = z.length(); if (MT_fuzzyZero(len)) z = vect; else z /= len; } x = ori.cross(z); y = z.cross(x); break; default: // invalid axis specified CM_FunctionWarning("invalid axis '" << axis << "'"); return; } x.normalize(); // normalize the new base vectors y.normalize(); z.normalize(); orimat.setValue(x[0], y[0], z[0], x[1], y[1], z[1], x[2], y[2], z[2]); if (GetSGNode()->GetSGParent() != nullptr) { // the object is a child, adapt its local orientation so that // the global orientation is aligned as we want (cancelling out the parent orientation) MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse(); NodeSetLocalOrientation(invori * orimat); } else { NodeSetLocalOrientation(orimat); } } MT_Scalar KX_GameObject::GetMass() { if (m_pPhysicsController) { return m_pPhysicsController->GetMass(); } return 0.0f; } MT_Vector3 KX_GameObject::GetLocalInertia() { MT_Vector3 local_inertia(0.0f, 0.0f, 0.0f); if (m_pPhysicsController) { local_inertia = m_pPhysicsController->GetLocalInertia(); } return local_inertia; } MT_Vector3 KX_GameObject::GetLinearVelocity(bool local) { MT_Vector3 velocity(0.0f, 0.0f, 0.0f), locvel; MT_Matrix3x3 ori; if (m_pPhysicsController) { velocity = m_pPhysicsController->GetLinearVelocity(); if (local) { ori = GetSGNode()->GetWorldOrientation(); locvel = velocity * ori; return locvel; } } return velocity; } MT_Vector3 KX_GameObject::GetAngularVelocity(bool local) { MT_Vector3 velocity(0.0f, 0.0f, 0.0f), locvel; MT_Matrix3x3 ori; if (m_pPhysicsController) { velocity = m_pPhysicsController->GetAngularVelocity(); if (local) { ori = GetSGNode()->GetWorldOrientation(); locvel = velocity * ori; return locvel; } } return velocity; } MT_Vector3 KX_GameObject::GetGravity() { MT_Vector3 gravity(0.0f, 0.0f, 0.0f); if (m_pPhysicsController) { gravity = m_pPhysicsController->GetGravity(); return gravity; } return gravity; } void KX_GameObject::SetGravity(const MT_Vector3 &gravity) { if (m_pPhysicsController) { m_pPhysicsController->SetGravity(gravity); } } MT_Vector3 KX_GameObject::GetVelocity(const MT_Vector3 &point) { if (m_pPhysicsController) { return m_pPhysicsController->GetVelocity(point); } return MT_Vector3(0.0f, 0.0f, 0.0f); } // scenegraph node stuff void KX_GameObject::NodeSetLocalPosition(const MT_Vector3 &trans) { if (m_pPhysicsController && !GetSGNode()->GetSGParent()) { // don't update physic controller if the object is a child: // 1) the transformation will not be right // 2) in this case, the physic controller is necessarily a static object // that is updated from the normal kinematic synchronization m_pPhysicsController->SetPosition(trans); } GetSGNode()->SetLocalPosition(trans); } void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3 &rot) { if (m_pPhysicsController && !GetSGNode()->GetSGParent()) { // see note above m_pPhysicsController->SetOrientation(rot); } GetSGNode()->SetLocalOrientation(rot); } void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3 &rot) { if (GetSGNode()->GetSGParent()) GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse() * rot); else NodeSetLocalOrientation(rot); } void KX_GameObject::NodeSetLocalScale(const MT_Vector3 &scale) { if (m_pPhysicsController && !GetSGNode()->GetSGParent()) { // see note above m_pPhysicsController->SetScaling(scale); } GetSGNode()->SetLocalScale(scale); } void KX_GameObject::NodeSetRelativeScale(const MT_Vector3 &scale) { GetSGNode()->RelativeScale(scale); if (m_pPhysicsController && (!GetSGNode()->GetSGParent())) { // see note above // we can use the local scale: it's the same thing for a root object // and the world scale is not yet updated MT_Vector3 newscale = GetSGNode()->GetLocalScale(); m_pPhysicsController->SetScaling(newscale); } } void KX_GameObject::NodeSetWorldScale(const MT_Vector3 &scale) { SG_Node *parent = GetSGNode()->GetSGParent(); if (parent != nullptr) { // Make sure the objects have some scale MT_Vector3 p_scale = parent->GetWorldScaling(); if (fabs(p_scale[0]) < (MT_Scalar)FLT_EPSILON || fabs(p_scale[1]) < (MT_Scalar)FLT_EPSILON || fabs(p_scale[2]) < (MT_Scalar)FLT_EPSILON) { return; } p_scale[0] = 1 / p_scale[0]; p_scale[1] = 1 / p_scale[1]; p_scale[2] = 1 / p_scale[2]; NodeSetLocalScale(scale * p_scale); } else { NodeSetLocalScale(scale); } } void KX_GameObject::NodeSetWorldPosition(const MT_Vector3 &trans) { SG_Node *parent = m_pSGNode->GetSGParent(); if (parent != nullptr) { // Make sure the objects have some scale MT_Vector3 scale = parent->GetWorldScaling(); if (fabs(scale[0]) < (MT_Scalar)FLT_EPSILON || fabs(scale[1]) < (MT_Scalar)FLT_EPSILON || fabs(scale[2]) < (MT_Scalar)FLT_EPSILON) { return; } scale[0] = 1.0f / scale[0]; scale[1] = 1.0f / scale[1]; scale[2] = 1.0f / scale[2]; MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse(); MT_Vector3 newpos = invori * (trans - parent->GetWorldPosition()) * scale; NodeSetLocalPosition(MT_Vector3(newpos[0], newpos[1], newpos[2])); } else { NodeSetLocalPosition(trans); } } void KX_GameObject::NodeUpdateGS(double time) { m_pSGNode->UpdateWorldData(time); } const MT_Matrix3x3 &KX_GameObject::NodeGetWorldOrientation() const { return m_pSGNode->GetWorldOrientation(); } const MT_Matrix3x3 &KX_GameObject::NodeGetLocalOrientation() const { return m_pSGNode->GetLocalOrientation(); } const MT_Vector3 &KX_GameObject::NodeGetWorldScaling() const { return m_pSGNode->GetWorldScaling(); } const MT_Vector3 &KX_GameObject::NodeGetLocalScaling() const { return m_pSGNode->GetLocalScale(); } const MT_Vector3 &KX_GameObject::NodeGetWorldPosition() const { return m_pSGNode->GetWorldPosition(); } const MT_Vector3 &KX_GameObject::NodeGetLocalPosition() const { return m_pSGNode->GetLocalPosition(); } MT_Transform KX_GameObject::NodeGetWorldTransform() const { return m_pSGNode->GetWorldTransform(); } MT_Transform KX_GameObject::NodeGetLocalTransform() const { return m_pSGNode->GetLocalTransform(); } void KX_GameObject::UnregisterCollisionCallbacks() { if (!GetPhysicsController()) { CM_Warning( "trying to unregister collision callbacks for object without collisions: " << GetName()); return; } // Unregister from callbacks KX_Scene *scene = GetScene(); PHY_IPhysicsEnvironment *pe = scene->GetPhysicsEnvironment(); PHY_IPhysicsController *spc = GetPhysicsController(); // If we are the last to unregister on this physics controller if (pe->RemoveCollisionCallback(spc)) { // If we are a sensor object if (m_pClient_info->isSensor()) // Remove sensor body from physics world pe->RemoveSensor(spc); } } void KX_GameObject::RegisterCollisionCallbacks() { if (!GetPhysicsController()) { CM_Warning( "trying to register collision callbacks for object without collisions: " << GetName()); return; } // Register from callbacks KX_Scene *scene = GetScene(); PHY_IPhysicsEnvironment *pe = scene->GetPhysicsEnvironment(); PHY_IPhysicsController *spc = GetPhysicsController(); // If we are the first to register on this physics controller if (pe->RequestCollisionCallback(spc)) { // If we are a sensor object if (m_pClient_info->isSensor()) // Add sensor body to physics world pe->AddSensor(spc); } } void KX_GameObject::RunCollisionCallbacks(KX_GameObject *collider, KX_CollisionContactPointList &contactPointList) { #ifdef WITH_PYTHON if (!m_collisionCallbacks || PyList_GET_SIZE(m_collisionCallbacks) == 0) { return; } CListWrapper *listWrapper = contactPointList.GetListWrapper(); PyObject *args[] = {collider->GetProxy(), PyObjectFrom(contactPointList.GetCollData()->GetWorldPoint( 0, contactPointList.GetFirstObject())), PyObjectFrom(contactPointList.GetCollData()->GetNormal( 0, contactPointList.GetFirstObject())), listWrapper->GetProxy()}; RunPythonCallBackList(m_collisionCallbacks, args, 1, ARRAY_SIZE(args)); for (unsigned int i = 0; i < ARRAY_SIZE(args); ++i) { Py_DECREF(args[i]); } // Invalidate the collison contact point to avoid acces to it in next frame listWrapper->InvalidateProxy(); delete listWrapper; #endif } void KX_GameObject::RunOnRemoveCallbacks() { #ifdef WITH_PYTHON PyObject *list = m_removeCallbacks; if (!list || PyList_GET_SIZE(list) == 0) { return; } PyObject *args[1] = {GetProxy()}; RunPythonCallBackList(list, args, 0, 1); #endif // WITH PYTHON } /* Suspend/ resume: for the dynamic behavior, there is a simple * method. For the residual motion, there is not. I wonder what the * correct solution is for Sumo. Remove from the motion-update tree? * * So far, only switch the physics and logic. * */ void KX_GameObject::ResumeDynamics(void) { if (m_suspended) { SCA_IObject::ResumeSensors(); // Child objects must be static, so we block changing to dynamic if (GetPhysicsController() && !GetParent()) GetPhysicsController()->RestoreDynamics(); m_suspended = false; } } void KX_GameObject::SuspendDynamics() { if ((!m_ignore_activity_culling) && (!m_suspended)) { SCA_IObject::SuspendSensors(); if (GetPhysicsController()) GetPhysicsController()->SuspendDynamics(); m_suspended = true; } } static void walk_children(SG_Node *node, CListValue<KX_GameObject> *list, bool recursive) { if (!node) return; NodeList &children = node->GetSGChildren(); for (SG_Node *childnode : children) { KX_GameObject *childobj = static_cast<KX_GameObject *>(childnode->GetSGClientObject()); if (childobj != nullptr) // This is a GameObject { // add to the list, no AddRef because the list doesn't own its items. list->Add(childobj); } // if the childobj is nullptr then this may be an inverse parent link // so a non recursive search should still look down this node. if (recursive || childobj == nullptr) { walk_children(childnode, list, recursive); } } } CListValue<KX_GameObject> *KX_GameObject::GetChildren() { CListValue<KX_GameObject> *list = new CListValue<KX_GameObject>(); /* The list must not own any data because is temporary and we can't * ensure that it will freed before item's in it (e.g python owner). */ list->SetReleaseOnDestruct(false); walk_children( GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */ return list; } CListValue<KX_GameObject> *KX_GameObject::GetChildrenRecursive() { CListValue<KX_GameObject> *list = new CListValue<KX_GameObject>(); /* The list must not own any data because is temporary and we can't * ensure that it will freed before item's in it (e.g python owner). */ list->SetReleaseOnDestruct(false); walk_children(GetSGNode(), list, 1); return list; } CListValue<KX_PythonComponent> *KX_GameObject::GetComponents() const { return m_components; } void KX_GameObject::SetComponents(CListValue<KX_PythonComponent> *components) { m_components = components; } void KX_GameObject::UpdateComponents() { #ifdef WITH_PYTHON if (!m_components) { return; } for (KX_PythonComponent *comp : m_components) { comp->Update(); } #endif // WITH_PYTHON } KX_Scene *KX_GameObject::GetScene() { BLI_assert(m_pSGNode); return static_cast<KX_Scene *>(m_pSGNode->GetSGClientInfo()); } /* --------------------------------------------------------------------- * Some stuff taken from the header * --------------------------------------------------------------------- */ void KX_GameObject::Relink(std::map<SCA_IObject *, SCA_IObject *> &map_parameter) { // we will relink the sensors and actuators that use object references // if the object is part of the replicated hierarchy, use the new // object reference instead SCA_SensorList &sensorlist = GetSensors(); SCA_SensorList::iterator sit; for (sit = sensorlist.begin(); sit != sensorlist.end(); sit++) { (*sit)->Relink(map_parameter); } SCA_ActuatorList &actuatorlist = GetActuators(); SCA_ActuatorList::iterator ait; for (ait = actuatorlist.begin(); ait != actuatorlist.end(); ait++) { (*ait)->Relink(map_parameter); } } #ifdef WITH_PYTHON # define PYTHON_CHECK_PHYSICS_CONTROLLER(obj, attr, ret) \ if (!(obj)->GetPhysicsController()) { \ PyErr_Format( \ PyExc_AttributeError, "KX_GameObject.%s, is missing a physics controller", (attr)); \ return (ret); \ } #endif #ifdef USE_MATHUTILS /* These require an SGNode */ # define MATHUTILS_VEC_CB_POS_LOCAL 1 # define MATHUTILS_VEC_CB_POS_GLOBAL 2 # define MATHUTILS_VEC_CB_SCALE_LOCAL 3 # define MATHUTILS_VEC_CB_SCALE_GLOBAL 4 # define MATHUTILS_VEC_CB_INERTIA_LOCAL 5 # define MATHUTILS_VEC_CB_OBJECT_COLOR 6 # define MATHUTILS_VEC_CB_LINVEL_LOCAL 7 # define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8 # define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9 # define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10 # define MATHUTILS_VEC_CB_GRAVITY 11 static unsigned char mathutils_kxgameob_vector_cb_index = -1; /* index for our callbacks */ static int mathutils_kxgameob_generic_check(BaseMathObject *bmo) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(bmo->cb_user); if (self == nullptr) return -1; return 0; } static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(bmo->cb_user); if (self == nullptr) return -1; switch (subtype) { case MATHUTILS_VEC_CB_POS_LOCAL: self->NodeGetLocalPosition().getValue(bmo->data); break; case MATHUTILS_VEC_CB_POS_GLOBAL: self->NodeGetWorldPosition().getValue(bmo->data); break; case MATHUTILS_VEC_CB_SCALE_LOCAL: self->NodeGetLocalScaling().getValue(bmo->data); break; case MATHUTILS_VEC_CB_SCALE_GLOBAL: self->NodeGetWorldScaling().getValue(bmo->data); break; case MATHUTILS_VEC_CB_INERTIA_LOCAL: PYTHON_CHECK_PHYSICS_CONTROLLER(self, "localInertia", -1); self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data); break; case MATHUTILS_VEC_CB_OBJECT_COLOR: self->GetObjectColor().getValue(bmo->data); break; case MATHUTILS_VEC_CB_LINVEL_LOCAL: PYTHON_CHECK_PHYSICS_CONTROLLER(self, "localLinearVelocity", -1); self->GetLinearVelocity(true).getValue(bmo->data); break; case MATHUTILS_VEC_CB_LINVEL_GLOBAL: PYTHON_CHECK_PHYSICS_CONTROLLER(self, "worldLinearVelocity", -1); self->GetLinearVelocity(false).getValue(bmo->data); break; case MATHUTILS_VEC_CB_ANGVEL_LOCAL: PYTHON_CHECK_PHYSICS_CONTROLLER(self, "localLinearVelocity", -1); self->GetAngularVelocity(true).getValue(bmo->data); break; case MATHUTILS_VEC_CB_ANGVEL_GLOBAL: PYTHON_CHECK_PHYSICS_CONTROLLER(self, "worldLinearVelocity", -1); self->GetAngularVelocity(false).getValue(bmo->data); break; case MATHUTILS_VEC_CB_GRAVITY: PYTHON_CHECK_PHYSICS_CONTROLLER(self, "gravity", -1); self->GetGravity().getValue(bmo->data); break; } # undef PHYS_ERR return 0; } static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(bmo->cb_user); if (self == nullptr) return -1; switch (subtype) { case MATHUTILS_VEC_CB_POS_LOCAL: self->NodeSetLocalPosition(MT_Vector3(bmo->data)); self->NodeUpdateGS(0.f); break; case MATHUTILS_VEC_CB_POS_GLOBAL: self->NodeSetWorldPosition(MT_Vector3(bmo->data)); self->NodeUpdateGS(0.f); break; case MATHUTILS_VEC_CB_SCALE_LOCAL: self->NodeSetLocalScale(MT_Vector3(bmo->data)); self->NodeUpdateGS(0.f); break; case MATHUTILS_VEC_CB_SCALE_GLOBAL: self->NodeSetWorldScale(MT_Vector3(bmo->data)); self->NodeUpdateGS(0.0f); break; case MATHUTILS_VEC_CB_INERTIA_LOCAL: /* read only */ break; case MATHUTILS_VEC_CB_OBJECT_COLOR: self->SetObjectColor(MT_Vector4(bmo->data)); break; case MATHUTILS_VEC_CB_LINVEL_LOCAL: self->setLinearVelocity(MT_Vector3(bmo->data), true); break; case MATHUTILS_VEC_CB_LINVEL_GLOBAL: self->setLinearVelocity(MT_Vector3(bmo->data), false); break; case MATHUTILS_VEC_CB_ANGVEL_LOCAL: self->setAngularVelocity(MT_Vector3(bmo->data), true); break; case MATHUTILS_VEC_CB_ANGVEL_GLOBAL: self->setAngularVelocity(MT_Vector3(bmo->data), false); break; case MATHUTILS_VEC_CB_GRAVITY: self->SetGravity(MT_Vector3(bmo->data)); break; } return 0; } static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index) { /* lazy, avoid repeteing the case statement */ if (mathutils_kxgameob_vector_get(bmo, subtype) == -1) return -1; return 0; } static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index) { float f = bmo->data[index]; /* lazy, avoid repeteing the case statement */ if (mathutils_kxgameob_vector_get(bmo, subtype) == -1) return -1; bmo->data[index] = f; return mathutils_kxgameob_vector_set(bmo, subtype); } static Mathutils_Callback mathutils_kxgameob_vector_cb = {mathutils_kxgameob_generic_check, mathutils_kxgameob_vector_get, mathutils_kxgameob_vector_set, mathutils_kxgameob_vector_get_index, mathutils_kxgameob_vector_set_index}; /* Matrix */ # define MATHUTILS_MAT_CB_ORI_LOCAL 1 # define MATHUTILS_MAT_CB_ORI_GLOBAL 2 static unsigned char mathutils_kxgameob_matrix_cb_index = -1; /* index for our callbacks */ static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(bmo->cb_user); if (self == nullptr) return -1; switch (subtype) { case MATHUTILS_MAT_CB_ORI_LOCAL: self->NodeGetLocalOrientation().getValue3x3(bmo->data); break; case MATHUTILS_MAT_CB_ORI_GLOBAL: self->NodeGetWorldOrientation().getValue3x3(bmo->data); break; } return 0; } static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(bmo->cb_user); if (self == nullptr) return -1; MT_Matrix3x3 mat3x3; switch (subtype) { case MATHUTILS_MAT_CB_ORI_LOCAL: mat3x3.setValue3x3(bmo->data); self->NodeSetLocalOrientation(mat3x3); self->NodeUpdateGS(0.f); break; case MATHUTILS_MAT_CB_ORI_GLOBAL: mat3x3.setValue3x3(bmo->data); self->NodeSetLocalOrientation(mat3x3); self->NodeUpdateGS(0.f); break; } return 0; } static Mathutils_Callback mathutils_kxgameob_matrix_cb = {mathutils_kxgameob_generic_check, mathutils_kxgameob_matrix_get, mathutils_kxgameob_matrix_set, nullptr, nullptr}; void KX_GameObject_Mathutils_Callback_Init(void) { // register mathutils callbacks, ok to run more than once. mathutils_kxgameob_vector_cb_index = Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb); mathutils_kxgameob_matrix_cb_index = Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb); } #endif // USE_MATHUTILS #ifdef WITH_PYTHON /* ------- python stuff ---------------------------------------------------*/ PyMethodDef KX_GameObject::Methods[] = { {"applyForce", (PyCFunction)KX_GameObject::sPyApplyForce, METH_VARARGS}, {"applyTorque", (PyCFunction)KX_GameObject::sPyApplyTorque, METH_VARARGS}, {"applyRotation", (PyCFunction)KX_GameObject::sPyApplyRotation, METH_VARARGS}, {"applyMovement", (PyCFunction)KX_GameObject::sPyApplyMovement, METH_VARARGS}, {"getLinearVelocity", (PyCFunction)KX_GameObject::sPyGetLinearVelocity, METH_VARARGS}, {"setLinearVelocity", (PyCFunction)KX_GameObject::sPySetLinearVelocity, METH_VARARGS}, {"getAngularVelocity", (PyCFunction)KX_GameObject::sPyGetAngularVelocity, METH_VARARGS}, {"setAngularVelocity", (PyCFunction)KX_GameObject::sPySetAngularVelocity, METH_VARARGS}, {"getVelocity", (PyCFunction)KX_GameObject::sPyGetVelocity, METH_VARARGS}, {"setDamping", (PyCFunction)KX_GameObject::sPySetDamping, METH_VARARGS}, {"getReactionForce", (PyCFunction)KX_GameObject::sPyGetReactionForce, METH_NOARGS}, {"alignAxisToVect", (PyCFunction)KX_GameObject::sPyAlignAxisToVect, METH_VARARGS | METH_KEYWORDS}, {"getAxisVect", (PyCFunction)KX_GameObject::sPyGetAxisVect, METH_O}, {"suspendPhysics", (PyCFunction)KX_GameObject::sPySuspendPhysics, METH_VARARGS}, {"restorePhysics", (PyCFunction)KX_GameObject::sPyRestorePhysics, METH_NOARGS}, {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics, METH_VARARGS}, {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics, METH_NOARGS}, {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody, METH_NOARGS}, {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody, METH_NOARGS}, {"applyImpulse", (PyCFunction)KX_GameObject::sPyApplyImpulse, METH_VARARGS}, {"setCollisionMargin", (PyCFunction)KX_GameObject::sPySetCollisionMargin, METH_O}, {"setParent", (PyCFunction)KX_GameObject::sPySetParent, METH_VARARGS | METH_KEYWORDS}, {"setVisible", (PyCFunction)KX_GameObject::sPySetVisible, METH_VARARGS}, {"setOcclusion", (PyCFunction)KX_GameObject::sPySetOcclusion, METH_VARARGS}, {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent, METH_NOARGS}, {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId, METH_NOARGS}, {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames, METH_NOARGS}, {"replaceMesh", (PyCFunction)KX_GameObject::sPyReplaceMesh, METH_VARARGS | METH_KEYWORDS}, {"endObject", (PyCFunction)KX_GameObject::sPyEndObject, METH_NOARGS}, {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh, METH_VARARGS | METH_KEYWORDS}, {"replacePhysicsShape", (PyCFunction)KX_GameObject::sPyReplacePhysicsShape, METH_O}, {"setCcdMotionThreshold", (PyCFunction)KX_GameObject::sPySetCcdMotionThreshold, METH_VARARGS}, {"setCcdSweptSphereRadius", (PyCFunction)KX_GameObject::sPySetCcdSweptSphereRadius, METH_VARARGS}, KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, rayCastTo), KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, rayCast), KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo), KX_PYMETHODTABLE_O(KX_GameObject, getVectTo), KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, sendMessage), KX_PYMETHODTABLE(KX_GameObject, addDebugProperty), KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction), KX_PYMETHODTABLE(KX_GameObject, stopAction), KX_PYMETHODTABLE(KX_GameObject, getActionFrame), KX_PYMETHODTABLE(KX_GameObject, getActionName), KX_PYMETHODTABLE(KX_GameObject, setActionFrame), KX_PYMETHODTABLE(KX_GameObject, isPlayingAction), KX_PYMETHODTABLE(KX_GameObject, recalcGeometry), KX_PYMETHODTABLE(KX_GameObject, recalcTransform), // dict style access for props {"get", (PyCFunction)KX_GameObject::sPyget, METH_VARARGS}, {nullptr, nullptr} // Sentinel }; PyAttributeDef KX_GameObject::Attributes[] = { KX_PYATTRIBUTE_SHORT_RO("currentLodLevel", KX_GameObject, m_currentLodLevel), KX_PYATTRIBUTE_RW_FUNCTION( "lodManager", KX_GameObject, pyattr_get_lodManager, pyattr_set_lodManager), KX_PYATTRIBUTE_RW_FUNCTION("name", KX_GameObject, pyattr_get_name, pyattr_set_name), KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent), KX_PYATTRIBUTE_RO_FUNCTION("groupMembers", KX_GameObject, pyattr_get_group_members), KX_PYATTRIBUTE_RO_FUNCTION("groupObject", KX_GameObject, pyattr_get_group_object), KX_PYATTRIBUTE_RO_FUNCTION("scene", KX_GameObject, pyattr_get_scene), KX_PYATTRIBUTE_RO_FUNCTION("life", KX_GameObject, pyattr_get_life), KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass), KX_PYATTRIBUTE_RO_FUNCTION("isSuspendDynamics", KX_GameObject, pyattr_get_is_suspend_dynamics), KX_PYATTRIBUTE_RW_FUNCTION( "linVelocityMin", KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min), KX_PYATTRIBUTE_RW_FUNCTION( "linVelocityMax", KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max), KX_PYATTRIBUTE_RW_FUNCTION( "angularVelocityMin", KX_GameObject, pyattr_get_ang_vel_min, pyattr_set_ang_vel_min), KX_PYATTRIBUTE_RW_FUNCTION( "angularVelocityMax", KX_GameObject, pyattr_get_ang_vel_max, pyattr_set_ang_vel_max), KX_PYATTRIBUTE_RW_FUNCTION("layer", KX_GameObject, pyattr_get_layer, pyattr_set_layer), KX_PYATTRIBUTE_RW_FUNCTION("visible", KX_GameObject, pyattr_get_visible, pyattr_set_visible), KX_PYATTRIBUTE_BOOL_RW("occlusion", KX_GameObject, m_bOccluder), KX_PYATTRIBUTE_RW_FUNCTION( "position", KX_GameObject, pyattr_get_worldPosition, pyattr_set_localPosition), KX_PYATTRIBUTE_RO_FUNCTION("localInertia", KX_GameObject, pyattr_get_localInertia), KX_PYATTRIBUTE_RW_FUNCTION( "orientation", KX_GameObject, pyattr_get_worldOrientation, pyattr_set_localOrientation), KX_PYATTRIBUTE_RW_FUNCTION( "scaling", KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling), KX_PYATTRIBUTE_RW_FUNCTION( "timeOffset", KX_GameObject, pyattr_get_timeOffset, pyattr_set_timeOffset), KX_PYATTRIBUTE_RW_FUNCTION("collisionCallbacks", KX_GameObject, pyattr_get_collisionCallbacks, pyattr_set_collisionCallbacks), KX_PYATTRIBUTE_RW_FUNCTION( "onRemove", KX_GameObject, pyattr_get_remove_callback, pyattr_set_remove_callback), KX_PYATTRIBUTE_RW_FUNCTION( "collisionGroup", KX_GameObject, pyattr_get_collisionGroup, pyattr_set_collisionGroup), KX_PYATTRIBUTE_RW_FUNCTION( "collisionMask", KX_GameObject, pyattr_get_collisionMask, pyattr_set_collisionMask), KX_PYATTRIBUTE_RW_FUNCTION("state", KX_GameObject, pyattr_get_state, pyattr_set_state), KX_PYATTRIBUTE_RO_FUNCTION("meshes", KX_GameObject, pyattr_get_meshes), KX_PYATTRIBUTE_RW_FUNCTION("localOrientation", KX_GameObject, pyattr_get_localOrientation, pyattr_set_localOrientation), KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation", KX_GameObject, pyattr_get_worldOrientation, pyattr_set_worldOrientation), KX_PYATTRIBUTE_RW_FUNCTION( "localPosition", KX_GameObject, pyattr_get_localPosition, pyattr_set_localPosition), KX_PYATTRIBUTE_RW_FUNCTION( "worldPosition", KX_GameObject, pyattr_get_worldPosition, pyattr_set_worldPosition), KX_PYATTRIBUTE_RW_FUNCTION( "localScale", KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling), KX_PYATTRIBUTE_RW_FUNCTION( "worldScale", KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling), KX_PYATTRIBUTE_RW_FUNCTION( "localTransform", KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform), KX_PYATTRIBUTE_RW_FUNCTION( "worldTransform", KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform), KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity), KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity), KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity), KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity), KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity), KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity), KX_PYATTRIBUTE_RW_FUNCTION( "linearDamping", KX_GameObject, pyattr_get_linearDamping, pyattr_set_linearDamping), KX_PYATTRIBUTE_RW_FUNCTION( "angularDamping", KX_GameObject, pyattr_get_angularDamping, pyattr_set_angularDamping), KX_PYATTRIBUTE_RO_FUNCTION("children", KX_GameObject, pyattr_get_children), KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive), KX_PYATTRIBUTE_RO_FUNCTION("attrDict", KX_GameObject, pyattr_get_attrDict), KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor), KX_PYATTRIBUTE_RW_FUNCTION("debug", KX_GameObject, pyattr_get_debug, pyattr_set_debug), KX_PYATTRIBUTE_RW_FUNCTION( "debugRecursive", KX_GameObject, pyattr_get_debugRecursive, pyattr_set_debugRecursive), KX_PYATTRIBUTE_RW_FUNCTION("gravity", KX_GameObject, pyattr_get_gravity, pyattr_set_gravity), KX_PYATTRIBUTE_RO_FUNCTION("blenderObject", KX_GameObject, pyattr_get_blender_object), /* experimental, don't rely on these yet */ KX_PYATTRIBUTE_RO_FUNCTION("sensors", KX_GameObject, pyattr_get_sensors), KX_PYATTRIBUTE_RO_FUNCTION("controllers", KX_GameObject, pyattr_get_controllers), KX_PYATTRIBUTE_RO_FUNCTION("actuators", KX_GameObject, pyattr_get_actuators), KX_PYATTRIBUTE_RO_FUNCTION("components", KX_GameObject, pyattr_get_components), KX_PYATTRIBUTE_NULL // Sentinel }; PyObject *KX_GameObject::PyReplaceMesh(PyObject *args, PyObject *kwds) { SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); PyObject *value; int use_gfx = 1, use_phys = 0; RAS_MeshObject *new_mesh; static const char *kwlist[] = {"mesh", "useDisplayMesh", "usePhysicsMesh", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ii:replaceMesh", const_cast<char**>(kwlist), &value, &use_gfx, &use_phys)) { return nullptr; } if (!ConvertPythonToMesh( logicmgr, value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject")) return nullptr; GetScene()->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys); Py_RETURN_NONE; } PyObject *KX_GameObject::PyEndObject() { GetScene()->DelayedRemoveObject(this); Py_RETURN_NONE; } PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args, PyObject *kwds) { KX_GameObject *gameobj = nullptr; RAS_MeshObject *mesh = nullptr; SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); int dupli = 0; int evaluated; PyObject *gameobj_py = nullptr; PyObject *mesh_py = nullptr; static const char *kwlist[] = {"gameObject", "meshObject", "dupli", "evaluated", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOii:reinstancePhysicsMesh", const_cast<char**>(kwlist), &gameobj_py, &mesh_py, &dupli, &evaluated) || (gameobj_py && !ConvertPythonToGameObject( logicmgr, gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh, dupli): KX_GameObject")) || (mesh_py && !ConvertPythonToMesh(logicmgr, mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh, dupli): KX_GameObject"))) { return nullptr; } /* gameobj and mesh can be nullptr */ if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh, dupli, evaluated)) Py_RETURN_TRUE; Py_RETURN_FALSE; } PyObject *KX_GameObject::PyReplacePhysicsShape(PyObject *value) { KX_GameObject *gameobj; SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); if (!ConvertPythonToGameObject( logicmgr, value, &gameobj, false, "gameOb.replacePhysicsShape(obj): KX_GameObject")) { return nullptr; } if (!GetPhysicsController() || !gameobj->GetPhysicsController()) { PyErr_SetString(PyExc_AttributeError, "gameOb.replacePhysicsShape(obj): function only available for objects with " "collisions enabled"); return nullptr; } GetPhysicsController()->ReplacePhysicsShape(gameobj->GetPhysicsController()); Py_RETURN_NONE; } static PyObject *Map_GetItem(PyObject *self_v, PyObject *item) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(self_v); const char *attr_str = _PyUnicode_AsString(item); CValue *resultattr; PyObject *pyconvert; if (self == nullptr) { PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG); return nullptr; } /* first see if the attributes a string and try get the cvalue attribute */ if (attr_str && (resultattr = self->GetProperty(attr_str))) { pyconvert = resultattr->ConvertValueToPython(); return pyconvert ? pyconvert : resultattr->GetProxy(); } /* no CValue attribute, try get the python only m_attr_dict attribute */ else if (self->m_attr_dict && (pyconvert = PyDict_GetItem(self->m_attr_dict, item))) { if (attr_str) PyErr_Clear(); Py_INCREF(pyconvert); return pyconvert; } else { if (attr_str) PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str); else PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist"); return nullptr; } } static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(self_v); const char *attr_str = _PyUnicode_AsString(key); if (attr_str == nullptr) PyErr_Clear(); if (self == nullptr) { PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG); return -1; } if (val == nullptr) { /* del ob["key"] */ int del = 0; /* try remove both just in case */ if (attr_str) del |= (self->RemoveProperty(attr_str) == true) ? 1 : 0; if (self->m_attr_dict) del |= (PyDict_DelItem(self->m_attr_dict, key) == 0) ? 1 : 0; if (del == 0) { if (attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str); else PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted"); return -1; } else if (self->m_attr_dict) { PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */ } } else { /* ob["key"] = value */ bool set = false; /* as CValue */ if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type) == 0) /* don't allow GameObjects for eg to be assigned to CValue props */ { CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: "); if (vallie) { CValue *oldprop = self->GetProperty(attr_str); if (oldprop) oldprop->SetValue(vallie); else self->SetProperty(attr_str, vallie); vallie->Release(); set = true; /* try remove dict value to avoid double ups */ if (self->m_attr_dict) { if (PyDict_DelItem(self->m_attr_dict, key) != 0) PyErr_Clear(); } } else if (PyErr_Occurred()) { return -1; } } if (set == false) { if (self->m_attr_dict == nullptr) /* lazy init */ self->m_attr_dict = PyDict_New(); if (PyDict_SetItem(self->m_attr_dict, key, val) == 0) { if (attr_str) self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */ set = true; } else { if (attr_str) PyErr_Format( PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str); else PyErr_SetString( PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary"); } } if (set == false) { return -1; /* pythons error value */ } } return 0; /* success */ } static int Seq_Contains(PyObject *self_v, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *> BGE_PROXY_REF(self_v); if (self == nullptr) { PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG); return -1; } if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value))) return 1; if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value)) return 1; return 0; } PyMappingMethods KX_GameObject::Mapping = { (lenfunc) nullptr, /*inquiry mp_length */ (binaryfunc)Map_GetItem, /*binaryfunc mp_subscript */ (objobjargproc)Map_SetItem, /*objobjargproc mp_ass_subscript */ }; PySequenceMethods KX_GameObject::Sequence = { nullptr, /* Cant set the len otherwise it can evaluate as false */ nullptr, /* sq_concat */ nullptr, /* sq_repeat */ nullptr, /* sq_item */ nullptr, /* sq_slice */ nullptr, /* sq_ass_item */ nullptr, /* sq_ass_slice */ (objobjproc)Seq_Contains, /* sq_contains */ (binaryfunc) nullptr, /* sq_inplace_concat */ (ssizeargfunc) nullptr, /* sq_inplace_repeat */ }; PyTypeObject KX_GameObject::Type = {PyVarObject_HEAD_INIT(nullptr, 0) "KX_GameObject", sizeof(PyObjectPlus_Proxy), 0, py_base_dealloc, 0, 0, 0, 0, py_base_repr, 0, &Sequence, &Mapping, 0, 0, 0, nullptr, nullptr, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, 0, 0, 0, 0, 0, 0, 0, Methods, 0, 0, &SCA_IObject::Type, 0, 0, 0, 0, 0, 0, py_base_new}; PyObject *KX_GameObject::pyattr_get_name(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyUnicode_FromStdString(self->GetName()); } int KX_GameObject::pyattr_set_name(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); if (!PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "gameOb.name = str: KX_GameObject, expected a string"); return PY_SET_ATTR_FAIL; } std::string newname = std::string(_PyUnicode_AsString(value)); std::string oldname = self->GetName(); SCA_LogicManager *manager = self->GetScene()->GetLogicManager(); // If true, it mean that's this game object is not a replica and was added at conversion time. if (manager->GetGameObjectByName(oldname) == self) { /* Two non-replica objects can have the same name bacause these objects are register in the * logic manager and that the result of GetGameObjectByName will be undefined. */ if (manager->GetGameObjectByName(newname)) { PyErr_Format( PyExc_TypeError, "gameOb.name = str: name %s is already used by an other non-replica game object", oldname.c_str()); return PY_SET_ATTR_FAIL; } // Unregister the old name. manager->UnregisterGameObjectName(oldname); // Register the object under the new name. manager->RegisterGameObjectName(newname, self); } // Change the name self->SetName(newname); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_parent(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); KX_GameObject *parent = self->GetParent(); if (parent) { return parent->GetProxy(); } Py_RETURN_NONE; } PyObject *KX_GameObject::pyattr_get_group_members(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); CListValue<KX_GameObject> *instances = self->GetInstanceObjects(); if (instances) { return instances->GetProxy(); } Py_RETURN_NONE; } PyObject *KX_GameObject::pyattr_get_collisionCallbacks(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); // Only objects with a physics controller should have collision callbacks PYTHON_CHECK_PHYSICS_CONTROLLER(self, "collisionCallbacks", nullptr); // Return the existing callbacks if (self->m_collisionCallbacks == nullptr) { self->m_collisionCallbacks = PyList_New(0); // Subscribe to collision update from KX_CollisionEventManager self->RegisterCollisionCallbacks(); } Py_INCREF(self->m_collisionCallbacks); return self->m_collisionCallbacks; } int KX_GameObject::pyattr_set_collisionCallbacks(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); // Only objects with a physics controller should have collision callbacks PYTHON_CHECK_PHYSICS_CONTROLLER(self, "collisionCallbacks", PY_SET_ATTR_FAIL); if (!PyList_CheckExact(value)) { PyErr_SetString(PyExc_ValueError, "Expected a list"); return PY_SET_ATTR_FAIL; } if (self->m_collisionCallbacks == nullptr) { self->RegisterCollisionCallbacks(); } else { Py_DECREF(self->m_collisionCallbacks); } Py_INCREF(value); self->m_collisionCallbacks = value; return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_remove_callback(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); if (!self->m_removeCallbacks) { self->m_removeCallbacks = PyList_New(0); } Py_INCREF(self->m_removeCallbacks); return self->m_removeCallbacks; } int KX_GameObject::pyattr_set_remove_callback(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); if (!PyList_CheckExact(value)) { PyErr_SetString(PyExc_ValueError, "Expected a list"); return PY_SET_ATTR_FAIL; } Py_XDECREF(self->m_removeCallbacks); Py_INCREF(value); self->m_removeCallbacks = value; return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_collisionGroup(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyLong_FromLong(self->GetUserCollisionGroup()); } int KX_GameObject::pyattr_set_collisionGroup(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int val = PyLong_AsLong(value); if (val == -1 && PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "gameOb.collisionGroup = int: KX_GameObject, expected an int bit field"); return PY_SET_ATTR_FAIL; } if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) { PyErr_Format( PyExc_AttributeError, "gameOb.collisionGroup = int: KX_GameObject, expected a int bit field, 0 < group < %i", (1 << OB_MAX_COL_MASKS)); return PY_SET_ATTR_FAIL; } self->SetUserCollisionGroup(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_collisionMask(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyLong_FromLong(self->GetUserCollisionMask()); } int KX_GameObject::pyattr_set_collisionMask(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int val = PyLong_AsLong(value); if (val == -1 && PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "gameOb.collisionMask = int: KX_GameObject, expected an int bit field"); return PY_SET_ATTR_FAIL; } if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) { PyErr_Format( PyExc_AttributeError, "gameOb.collisionMask = int: KX_GameObject, expected a int bit field, 0 < mask < %i", (1 << OB_MAX_COL_MASKS)); return PY_SET_ATTR_FAIL; } self->SetUserCollisionMask(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_scene(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); KX_Scene *scene = self->GetScene(); if (scene) { return scene->GetProxy(); } Py_RETURN_NONE; } PyObject *KX_GameObject::pyattr_get_group_object(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); KX_GameObject *pivot = self->GetDupliGroupObject(); if (pivot) { return pivot->GetProxy(); } Py_RETURN_NONE; } PyObject *KX_GameObject::pyattr_get_life(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); CValue *life = self->GetProperty("::timebomb"); if (life) // this convert the timebomb seconds to frames, hard coded 50.0f (assuming 50fps) // value hardcoded in KX_Scene::AddReplicaObject() return PyFloat_FromDouble(life->GetNumber() * 50.0); else Py_RETURN_NONE; } PyObject *KX_GameObject::pyattr_get_mass(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f); } int KX_GameObject::pyattr_set_mass(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); MT_Scalar val = PyFloat_AsDouble(value); if (val < 0.0f) { /* also accounts for non float */ PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above"); return PY_SET_ATTR_FAIL; } if (spc) spc->SetMass(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_is_suspend_dynamics(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); // Only objects with a physics controller can be suspended PYTHON_CHECK_PHYSICS_CONTROLLER(self, attrdef->m_name.c_str(), nullptr); return PyBool_FromLong(self->IsDynamicsSuspended()); } PyObject *KX_GameObject::pyattr_get_lin_vel_min(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f); } int KX_GameObject::pyattr_set_lin_vel_min(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); MT_Scalar val = PyFloat_AsDouble(value); if (val < 0.0f) { /* also accounts for non float */ PyErr_SetString( PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above"); return PY_SET_ATTR_FAIL; } if (spc) spc->SetLinVelocityMin(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_lin_vel_max(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f); } int KX_GameObject::pyattr_set_lin_vel_max(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); MT_Scalar val = PyFloat_AsDouble(value); if (val < 0.0f) { /* also accounts for non float */ PyErr_SetString( PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above"); return PY_SET_ATTR_FAIL; } if (spc) spc->SetLinVelocityMax(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_ang_vel_min(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMin() : 0.0f); } int KX_GameObject::pyattr_set_ang_vel_min(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); MT_Scalar val = PyFloat_AsDouble(value); if (val < 0.0f) { /* also accounts for non float */ PyErr_SetString( PyExc_AttributeError, "gameOb.angularVelocityMin = float: KX_GameObject, expected a nonnegative float"); return PY_SET_ATTR_FAIL; } if (spc) spc->SetAngularVelocityMin(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_ang_vel_max(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMax() : 0.0f); } int KX_GameObject::pyattr_set_ang_vel_max(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PHY_IPhysicsController *spc = self->GetPhysicsController(); MT_Scalar val = PyFloat_AsDouble(value); if (val < 0.0f) { /* also accounts for non float */ PyErr_SetString( PyExc_AttributeError, "gameOb.angularVelocityMax = float: KX_GameObject, expected a nonnegative float"); return PY_SET_ATTR_FAIL; } if (spc) spc->SetAngularVelocityMax(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_layer(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyLong_FromLong(self->GetLayer()); } # define MAX_LAYERS ((1 << 20) - 1) int KX_GameObject::pyattr_set_layer(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int layer = PyLong_AsLong(value); if (layer == -1 && PyErr_Occurred()) { PyErr_Format( PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name.c_str()); return PY_SET_ATTR_FAIL; } if (layer < 1) { PyErr_Format(PyExc_TypeError, "expected an integer greater than 1 for attribute \"%s\"", attrdef->m_name.c_str()); return PY_SET_ATTR_FAIL; } else if (layer > MAX_LAYERS) { PyErr_Format(PyExc_TypeError, "expected an integer less than %i for attribute \"%s\"", MAX_LAYERS, attrdef->m_name.c_str()); return PY_SET_ATTR_FAIL; } self->SetLayer(layer); return PY_SET_ATTR_SUCCESS; } # undef MAX_LAYERS PyObject *KX_GameObject::pyattr_get_visible(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyBool_FromLong(self->GetVisible()); } int KX_GameObject::pyattr_set_visible(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int param = PyObject_IsTrue(value); if (param == -1) { PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False"); return PY_SET_ATTR_FAIL; } self->SetVisible(param, false); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_worldPosition(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->NodeGetWorldPosition()); # endif } int KX_GameObject::pyattr_set_worldPosition(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 pos; if (!PyVecTo(value, pos)) return PY_SET_ATTR_FAIL; self->NodeSetWorldPosition(pos); self->NodeUpdateGS(0.f); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_localPosition(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->NodeGetLocalPosition()); # endif } int KX_GameObject::pyattr_set_localPosition(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 pos; if (!PyVecTo(value, pos)) return PY_SET_ATTR_FAIL; self->NodeSetLocalPosition(pos); self->NodeUpdateGS(0.f); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_localInertia(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); if (self->GetPhysicsController1()) return PyObjectFrom(self->GetPhysicsController1()->GetLocalInertia()); return PyObjectFrom(MT_Vector3(0.0f, 0.0f, 0.0f)); # endif } PyObject *KX_GameObject::pyattr_get_worldOrientation(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->NodeGetWorldOrientation()); # endif } int KX_GameObject::pyattr_set_worldOrientation(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); /* if value is not a sequence PyOrientationTo makes an error */ MT_Matrix3x3 rot; if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, ")) return PY_SET_ATTR_FAIL; self->NodeSetGlobalOrientation(rot); self->NodeUpdateGS(0.f); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_localOrientation(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->NodeGetLocalOrientation()); # endif } int KX_GameObject::pyattr_set_localOrientation(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); /* if value is not a sequence PyOrientationTo makes an error */ MT_Matrix3x3 rot; if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, ")) return PY_SET_ATTR_FAIL; self->NodeSetLocalOrientation(rot); self->NodeUpdateGS(0.f); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_worldScaling(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->NodeGetWorldScaling()); # endif } int KX_GameObject::pyattr_set_worldScaling(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 scale; if (!PyVecTo(value, scale)) return PY_SET_ATTR_FAIL; self->NodeSetWorldScale(scale); self->NodeUpdateGS(0.f); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_localScaling(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->NodeGetLocalScaling()); # endif } int KX_GameObject::pyattr_set_localScaling(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 scale; if (!PyVecTo(value, scale)) return PY_SET_ATTR_FAIL; self->NodeSetLocalScale(scale); self->NodeUpdateGS(0.f); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_localTransform(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->NodeGetLocalTransform().toMatrix()); } int KX_GameObject::pyattr_set_localTransform(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Matrix4x4 temp; if (!PyMatTo(value, temp)) return PY_SET_ATTR_FAIL; float transform[4][4]; float loc[3], size[3]; float rot[3][3]; MT_Matrix3x3 orientation; temp.getValue(*transform); mat4_to_loc_rot_size(loc, rot, size, transform); self->NodeSetLocalPosition(MT_Vector3(loc)); // MT_Matrix3x3's constructor expects a 4x4 matrix orientation = MT_Matrix3x3(); orientation.setValue3x3(*rot); self->NodeSetLocalOrientation(orientation); self->NodeSetLocalScale(MT_Vector3(size)); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_worldTransform(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(MT_Matrix4x4(self->NodeGetWorldTransform())); } int KX_GameObject::pyattr_set_worldTransform(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Matrix4x4 temp; if (!PyMatTo(value, temp)) return PY_SET_ATTR_FAIL; float transform[4][4]; float loc[3], size[3]; float rot[3][3]; MT_Matrix3x3 orientation; temp.getValue(*transform); mat4_to_loc_rot_size(loc, rot, size, transform); self->NodeSetWorldPosition(MT_Vector3(loc)); // MT_Matrix3x3's constructor expects a 4x4 matrix orientation = MT_Matrix3x3(); orientation.setValue3x3(*rot); self->NodeSetGlobalOrientation(orientation); self->NodeSetWorldScale(MT_Vector3(size)); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(GetLinearVelocity(false)); # endif } int KX_GameObject::pyattr_set_worldLinearVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 velocity; if (!PyVecTo(value, velocity)) return PY_SET_ATTR_FAIL; self->setLinearVelocity(velocity, false); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_localLinearVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(GetLinearVelocity(true)); # endif } int KX_GameObject::pyattr_set_localLinearVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 velocity; if (!PyVecTo(value, velocity)) return PY_SET_ATTR_FAIL; self->setLinearVelocity(velocity, true); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(GetAngularVelocity(false)); # endif } int KX_GameObject::pyattr_set_worldAngularVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 velocity; if (!PyVecTo(value, velocity)) return PY_SET_ATTR_FAIL; self->setAngularVelocity(velocity, false); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_localAngularVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(GetAngularVelocity(true)); # endif } int KX_GameObject::pyattr_set_localAngularVelocity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 velocity; if (!PyVecTo(value, velocity)) return PY_SET_ATTR_FAIL; self->setAngularVelocity(velocity, true); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_gravity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { # ifdef USE_MATHUTILS return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF_BORROW(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_GRAVITY); # else KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(GetGravity()); # endif } int KX_GameObject::pyattr_set_gravity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector3 gravity; if (!PyVecTo(value, gravity)) return PY_SET_ATTR_FAIL; self->SetGravity(gravity); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_linearDamping(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyFloat_FromDouble(self->getLinearDamping()); } int KX_GameObject::pyattr_set_linearDamping(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); float val = PyFloat_AsDouble(value); self->setLinearDamping(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_angularDamping(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyFloat_FromDouble(self->getAngularDamping()); } int KX_GameObject::pyattr_set_angularDamping(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); float val = PyFloat_AsDouble(value); self->setAngularDamping(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_timeOffset(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); SG_Node *sg_parent; if ((sg_parent = self->GetSGNode()->GetSGParent()) != nullptr && sg_parent->IsSlowParent()) { return PyFloat_FromDouble( static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset()); } else { return PyFloat_FromDouble(0.0f); } } int KX_GameObject::pyattr_set_timeOffset(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Scalar val = PyFloat_AsDouble(value); SG_Node *sg_parent = self->GetSGNode()->GetSGParent(); if (val < 0.0f) { /* also accounts for non float */ PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above"); return PY_SET_ATTR_FAIL; } if (sg_parent && sg_parent->IsSlowParent()) static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_state(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int state = 0; state |= self->GetState(); return PyLong_FromLong(state); } int KX_GameObject::pyattr_set_state(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int state_i = PyLong_AsLong(value); unsigned int state = 0; if (state_i == -1 && PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field"); return PY_SET_ATTR_FAIL; } state |= state_i; if ((state & ((1 << 30) - 1)) == 0) { PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 " "(1<<0 and 1<<29)"); return PY_SET_ATTR_FAIL; } self->SetState(state); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_meshes(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); PyObject *meshes = PyList_New(self->m_meshes.size()); int i; for (i = 0; i < (int)self->m_meshes.size(); i++) { KX_MeshProxy *meshproxy = new KX_MeshProxy(self->m_meshes[i]); PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true)); } return meshes; } PyObject *KX_GameObject::pyattr_get_obcolor(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyObjectFrom(self->m_objectColor); } int KX_GameObject::pyattr_set_obcolor(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); MT_Vector4 obcolor; if (!PyVecTo(value, obcolor)) return PY_SET_ATTR_FAIL; self->SetObjectColor(obcolor); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_components(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); CListValue<KX_PythonComponent> *components = self->GetComponents(); return components ? components->GetProxy() : (new CListValue<KX_PythonComponent>())->NewProxy(true); } static int kx_game_object_get_sensors_size_cb(void *self_v) { return ((KX_GameObject *)self_v)->GetSensors().size(); } static PyObject *kx_game_object_get_sensors_item_cb(void *self_v, int index) { return ((KX_GameObject *)self_v)->GetSensors()[index]->GetProxy(); } static const std::string kx_game_object_get_sensors_item_name_cb(void *self_v, int index) { return ((KX_GameObject *)self_v)->GetSensors()[index]->GetName(); } /* These are experimental! */ PyObject *KX_GameObject::pyattr_get_sensors(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { return (new CListWrapper(self_v, ((KX_GameObject *)self_v)->GetProxy(), nullptr, kx_game_object_get_sensors_size_cb, kx_game_object_get_sensors_item_cb, kx_game_object_get_sensors_item_name_cb, nullptr)) ->NewProxy(true); } static int kx_game_object_get_controllers_size_cb(void *self_v) { return ((KX_GameObject *)self_v)->GetControllers().size(); } static PyObject *kx_game_object_get_controllers_item_cb(void *self_v, int index) { return ((KX_GameObject *)self_v)->GetControllers()[index]->GetProxy(); } static const std::string kx_game_object_get_controllers_item_name_cb(void *self_v, int index) { return ((KX_GameObject *)self_v)->GetControllers()[index]->GetName(); } PyObject *KX_GameObject::pyattr_get_controllers(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { return (new CListWrapper(self_v, ((KX_GameObject *)self_v)->GetProxy(), nullptr, kx_game_object_get_controllers_size_cb, kx_game_object_get_controllers_item_cb, kx_game_object_get_controllers_item_name_cb, nullptr)) ->NewProxy(true); } static int kx_game_object_get_actuators_size_cb(void *self_v) { return ((KX_GameObject *)self_v)->GetActuators().size(); } static PyObject *kx_game_object_get_actuators_item_cb(void *self_v, int index) { return ((KX_GameObject *)self_v)->GetActuators()[index]->GetProxy(); } static const std::string kx_game_object_get_actuators_item_name_cb(void *self_v, int index) { return ((KX_GameObject *)self_v)->GetActuators()[index]->GetName(); } PyObject *KX_GameObject::pyattr_get_actuators(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { return (new CListWrapper(self_v, ((KX_GameObject *)self_v)->GetProxy(), nullptr, kx_game_object_get_actuators_size_cb, kx_game_object_get_actuators_item_cb, kx_game_object_get_actuators_item_name_cb, nullptr)) ->NewProxy(true); } /* End experimental */ PyObject *KX_GameObject::pyattr_get_children(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return self->GetChildren()->NewProxy(true); } PyObject *KX_GameObject::pyattr_get_children_recursive(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return self->GetChildrenRecursive()->NewProxy(true); } PyObject *KX_GameObject::pyattr_get_attrDict(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); if (self->m_attr_dict == nullptr) self->m_attr_dict = PyDict_New(); Py_INCREF(self->m_attr_dict); return self->m_attr_dict; } PyObject *KX_GameObject::pyattr_get_debug(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyBool_FromLong(self->GetScene()->ObjectInDebugList(self)); } int KX_GameObject::pyattr_set_debug(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int param = PyObject_IsTrue(value); if (param == -1) { PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False"); return PY_SET_ATTR_FAIL; } self->SetUseDebugProperties(param, false); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_debugRecursive(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return PyBool_FromLong(self->GetScene()->ObjectInDebugList(self)); } int KX_GameObject::pyattr_set_debugRecursive(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); int param = PyObject_IsTrue(value); if (param == -1) { PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False"); return PY_SET_ATTR_FAIL; } self->SetUseDebugProperties(param, true); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::pyattr_get_lodManager(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); return (self->m_lodManager) ? self->m_lodManager->GetProxy() : Py_None; } int KX_GameObject::pyattr_set_lodManager(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); KX_LodManager *lodManager = nullptr; if (!ConvertPythonToLodManager(value, &lodManager, true, "gameobj.lodManager: KX_GameObject")) { return PY_SET_ATTR_FAIL; } self->SetLodManager(lodManager); self->GetScene()->AddObjToLodObjList(self); return PY_SET_ATTR_SUCCESS; } PyObject *KX_GameObject::PyApplyForce(PyObject *args) { int local = 0; PyObject *pyvect; if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) { MT_Vector3 force; if (PyVecTo(pyvect, force)) { ApplyForce(force, (local != 0)); Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PyApplyTorque(PyObject *args) { int local = 0; PyObject *pyvect; if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) { MT_Vector3 torque; if (PyVecTo(pyvect, torque)) { ApplyTorque(torque, (local != 0)); Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PyApplyRotation(PyObject *args) { int local = 0; PyObject *pyvect; if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) { MT_Vector3 rotation; if (PyVecTo(pyvect, rotation)) { ApplyRotation(rotation, (local != 0)); Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PyApplyMovement(PyObject *args) { int local = 0; PyObject *pyvect; if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) { MT_Vector3 movement; if (PyVecTo(pyvect, movement)) { ApplyMovement(movement, (local != 0)); Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args) { // only can get the velocity if we have a physics object connected to us... int local = 0; if (PyArg_ParseTuple(args, "|i:getLinearVelocity", &local)) { return PyObjectFrom(GetLinearVelocity((local != 0))); } else { return nullptr; } } PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args) { int local = 0; PyObject *pyvect; if (PyArg_ParseTuple(args, "O|i:setLinearVelocity", &pyvect, &local)) { MT_Vector3 velocity; if (PyVecTo(pyvect, velocity)) { setLinearVelocity(velocity, (local != 0)); Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args) { // only can get the velocity if we have a physics object connected to us... int local = 0; if (PyArg_ParseTuple(args, "|i:getAngularVelocity", &local)) { return PyObjectFrom(GetAngularVelocity((local != 0))); } else { return nullptr; } } PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args) { int local = 0; PyObject *pyvect; if (PyArg_ParseTuple(args, "O|i:setAngularVelocity", &pyvect, &local)) { MT_Vector3 velocity; if (PyVecTo(pyvect, velocity)) { setAngularVelocity(velocity, (local != 0)); Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PySetDamping(PyObject *args) { float linear; float angular; if (!PyArg_ParseTuple(args, "ff:setDamping", &linear, &angular)) { return nullptr; } setDamping(linear, angular); Py_RETURN_NONE; } PyObject *KX_GameObject::PySetCcdMotionThreshold(PyObject *args) { float motion_threshold; if (!PyArg_ParseTuple(args, "f:setCcdMotionThreshold", &motion_threshold)) { return nullptr; } if ((motion_threshold < 0.0f) || (motion_threshold > 100.0f)) { PyErr_SetString(PyExc_TypeError, "gameOb.setCcdMotionThreshold: KX_GameObject, " "expected a float in range 0.0 - 100.0"); return nullptr; } setCcdMotionThreshold(motion_threshold); Py_RETURN_NONE; } PyObject *KX_GameObject::PySetCcdSweptSphereRadius(PyObject *args) { float swept_sphere_radius; if (!PyArg_ParseTuple(args, "f:setCcdSweptSphereRadius", &swept_sphere_radius)) { return nullptr; } if ((swept_sphere_radius < 0.0f) || (swept_sphere_radius > 10.0f)) { PyErr_SetString(PyExc_TypeError, "gameOb.setCcdSweptSphereRadius: KX_GameObject, " "expected a float in range 0.0 - 10.0"); return nullptr; } setCcdSweptSphereRadius(swept_sphere_radius); Py_RETURN_NONE; } PyObject *KX_GameObject::PySetVisible(PyObject *args) { int visible, recursive = 0; if (!PyArg_ParseTuple(args, "i|i:setVisible", &visible, &recursive)) { return nullptr; } SetVisible(visible ? true : false, recursive ? true : false); Py_RETURN_NONE; } PyObject *KX_GameObject::PySetOcclusion(PyObject *args) { int occlusion, recursive = 0; if (!PyArg_ParseTuple(args, "i|i:setOcclusion", &occlusion, &recursive)) { return nullptr; } SetOccluder(occlusion ? true : false, recursive ? true : false); Py_RETURN_NONE; } PyObject *KX_GameObject::PyGetVelocity(PyObject *args) { // only can get the velocity if we have a physics object connected to us... MT_Vector3 point(0.0f, 0.0f, 0.0f); PyObject *pypos = nullptr; if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point))) { return nullptr; } return PyObjectFrom(GetVelocity(point)); } PyObject *KX_GameObject::PyGetReactionForce() { // only can get the velocity if we have a physics object connected to us... // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's // getReactionForce # if 0 if (GetPhysicsController1()) return PyObjectFrom(GetPhysicsController1()->getReactionForce()); return PyObjectFrom(dummy_point); # endif return PyObjectFrom(MT_Vector3(0.0f, 0.0f, 0.0f)); } PyObject *KX_GameObject::PyEnableRigidBody() { if (GetPhysicsController()) GetPhysicsController()->SetRigidBody(true); Py_RETURN_NONE; } PyObject *KX_GameObject::PyDisableRigidBody() { if (GetPhysicsController()) GetPhysicsController()->SetRigidBody(false); Py_RETURN_NONE; } PyObject *KX_GameObject::PySetParent(PyObject *args, PyObject *kwds) { SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); PyObject *pyobj; KX_GameObject *obj; int addToCompound = 1, ghost = 1; static const char *kwlist[] = {"parent", "compound", "ghost", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ii:setParent", const_cast<char**>(kwlist), &pyobj, &addToCompound, &ghost)) { return nullptr; // Python sets a simple error } if (!ConvertPythonToGameObject( logicmgr, pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject")) return nullptr; if (obj) SetParent(obj, addToCompound, ghost); Py_RETURN_NONE; } PyObject *KX_GameObject::PyRemoveParent() { RemoveParent(); Py_RETURN_NONE; } PyObject *KX_GameObject::PySetCollisionMargin(PyObject *value) { float collisionMargin = PyFloat_AsDouble(value); if (collisionMargin == -1 && PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "expected a float"); return nullptr; } PYTHON_CHECK_PHYSICS_CONTROLLER(this, "setCollisionMargin", nullptr); m_pPhysicsController->SetMargin(collisionMargin); Py_RETURN_NONE; } PyObject *KX_GameObject::PyApplyImpulse(PyObject *args) { PyObject *pyattach; PyObject *pyimpulse; int local = 0; PYTHON_CHECK_PHYSICS_CONTROLLER(this, "applyImpulse", nullptr); if (PyArg_ParseTuple(args, "OO|i:applyImpulse", &pyattach, &pyimpulse, &local)) { MT_Vector3 attach; MT_Vector3 impulse; if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse)) { m_pPhysicsController->ApplyImpulse(attach, impulse, (local != 0)); Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PySuspendPhysics(PyObject *args) { int freeConstraints = false; if (!PyArg_ParseTuple(args, "|i:suspendPhysics", &freeConstraints)) { return nullptr; } if (GetPhysicsController()) { GetPhysicsController()->SuspendPhysics((bool)freeConstraints); } Py_RETURN_NONE; } PyObject *KX_GameObject::PyRestorePhysics() { if (GetPhysicsController()) { GetPhysicsController()->RestorePhysics(); } Py_RETURN_NONE; } PyObject *KX_GameObject::PySuspendDynamics(PyObject *args) { bool ghost = false; if (!PyArg_ParseTuple(args, "|b", &ghost)) { return nullptr; } if (GetPhysicsController()) GetPhysicsController()->SuspendDynamics(ghost); Py_RETURN_NONE; } PyObject *KX_GameObject::PyRestoreDynamics() { // Child objects must be static, so we block changing to dynamic if (GetPhysicsController() && !GetParent()) GetPhysicsController()->RestoreDynamics(); Py_RETURN_NONE; } PyObject *KX_GameObject::PyAlignAxisToVect(PyObject *args, PyObject *kwds) { PyObject *pyvect; int axis = 2; // z axis is the default float fac = 1.0f; static const char *kwlist[] = {"vect", "axis", "factor", nullptr}; if (PyArg_ParseTupleAndKeywords(args, kwds, "O|if:alignAxisToVect", const_cast<char**>(kwlist), &pyvect, &axis, &fac)) { MT_Vector3 vect; if (PyVecTo(pyvect, vect)) { if (fac > 0.0f) { if (fac > 1.0f) fac = 1.0f; AlignAxisToVect(vect, axis, fac); NodeUpdateGS(0.f); } Py_RETURN_NONE; } } return nullptr; } PyObject *KX_GameObject::PyGetAxisVect(PyObject *value) { MT_Vector3 vect; if (PyVecTo(value, vect)) { return PyObjectFrom(NodeGetWorldOrientation() * vect); } return nullptr; } PyObject *KX_GameObject::PyGetPhysicsId() { PHY_IPhysicsController *ctrl = GetPhysicsController(); unsigned long long physid = 0; if (ctrl) { physid = (unsigned long long)ctrl; } return PyLong_FromUnsignedLongLong(physid); } PyObject *KX_GameObject::PyGetPropertyNames() { PyObject *list = ConvertKeysToPython(); if (m_attr_dict) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(m_attr_dict, &pos, &key, &value)) { PyList_Append(list, key); } } return list; } PyObject *KX_GameObject::pyattr_get_blender_object(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_GameObject *self = static_cast<KX_GameObject *>(self_v); Object *ob = self->GetBlenderObject(); if (ob) { PyObject *py_blender_object = pyrna_id_CreatePyObject(&ob->id); return py_blender_object; } Py_RETURN_NONE; } KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo, "getDistanceTo(other): get distance to another point/KX_GameObject") { MT_Vector3 b; if (PyVecTo(value, b)) { return PyFloat_FromDouble(NodeGetWorldPosition().distance(b)); } PyErr_Clear(); SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); KX_GameObject *other; if (ConvertPythonToGameObject( logicmgr, value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject")) { return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition())); } return nullptr; } KX_PYMETHODDEF_DOC_O( KX_GameObject, getVectTo, "getVectTo(other): get vector and the distance to another point/KX_GameObject\n" "Returns a 3-tuple with (distance,worldVector,localVector)\n") { MT_Vector3 toPoint, fromPoint; MT_Vector3 toDir, locToDir; MT_Scalar distance; SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); PyObject *returnValue; if (!PyVecTo(value, toPoint)) { PyErr_Clear(); KX_GameObject *other; if (ConvertPythonToGameObject( logicmgr, value, &other, false, "")) /* error will be overwritten */ { toPoint = other->NodeGetWorldPosition(); } else { PyErr_SetString( PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type"); return nullptr; } } fromPoint = NodeGetWorldPosition(); toDir = toPoint - fromPoint; distance = toDir.length(); if (MT_fuzzyZero(distance)) { locToDir = toDir = MT_Vector3(0.0f, 0.0f, 0.0f); distance = 0.0f; } else { toDir.normalize(); locToDir = toDir * NodeGetWorldOrientation(); } returnValue = PyTuple_New(3); if (returnValue) { // very unlikely to fail, python sets a memory error here. PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance)); PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir)); PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir)); } return returnValue; } struct KX_GameObject::RayCastData { RayCastData(std::string prop, bool xray, unsigned int mask) : m_prop(prop), m_xray(xray), m_mask(mask), m_hitObject(nullptr) { } std::string m_prop; bool m_xray; unsigned int m_mask; KX_GameObject *m_hitObject; }; bool KX_GameObject::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, RayCastData *rayData) { KX_GameObject *hitKXObj = client->m_gameobject; // if X-ray option is selected, the unwnted objects were not tested, so get here only with true // hit if not, all objects were tested and the front one may not be the correct one. if ((rayData->m_xray || rayData->m_prop.empty() || hitKXObj->GetProperty(rayData->m_prop) != nullptr) && hitKXObj->GetUserCollisionGroup() & rayData->m_mask) { rayData->m_hitObject = hitKXObj; return true; } // return true to stop RayCast::RayTest from looping, the above test was decisive // We would want to loop only if we want to get more than one hit point return true; } /* this function is used to pre-filter the object before casting the ray on them. * This is useful for "X-Ray" option when we want to see "through" unwanted object. */ bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo *client, RayCastData *rayData) { KX_GameObject *hitKXObj = client->m_gameobject; if (client->m_type > KX_ClientObjectInfo::ACTOR) { // Unknown type of object, skip it. // Should not occur as the sensor objects are filtered in RayTest() CM_Error("invalid client type " << client->m_type << " found in ray casting"); return false; } // if X-Ray option is selected, skip object that don't match the criteria as we see through them // if not, test all objects because we don't know yet which one will be on front if ((!rayData->m_xray || rayData->m_prop.empty() || hitKXObj->GetProperty(rayData->m_prop) != nullptr) && hitKXObj->GetUserCollisionGroup() & rayData->m_mask) { return true; } // skip the object return false; } KX_PYMETHODDEF_DOC( KX_GameObject, rayCastTo, "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object " "hit within dist that matches prop\n" " prop = property name that object must have; can be omitted => detect any object\n" " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to " "other\n" " other = 3-tuple or object reference") { MT_Vector3 toPoint; PyObject *pyarg; float dist = 0.0f; const char *propName = ""; SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); static const char *kwlist[] = {"other", "dist", "prop", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|fs:rayCastTo", const_cast<char**>(kwlist), &pyarg, &dist, &propName)) { return nullptr; // python sets simple error } if (!PyVecTo(pyarg, toPoint)) { KX_GameObject *other; PyErr_Clear(); if (ConvertPythonToGameObject( logicmgr, pyarg, &other, false, "")) /* error will be overwritten */ { toPoint = other->NodeGetWorldPosition(); } else { PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to " "rayCastTo must be a vector or a KX_GameObject"); return nullptr; } } MT_Vector3 fromPoint = NodeGetWorldPosition(); if (dist != 0.0f) toPoint = fromPoint + dist * (toPoint - fromPoint).safe_normalized(); PHY_IPhysicsEnvironment *pe = GetScene()->GetPhysicsEnvironment(); PHY_IPhysicsController *spc = GetPhysicsController(); KX_GameObject *parent = GetParent(); if (!spc && parent) spc = parent->GetPhysicsController(); RayCastData rayData(propName, false, (1u << OB_MAX_COL_MASKS) - 1); KX_RayCast::Callback<KX_GameObject, RayCastData> callback(this, spc, &rayData); if (KX_RayCast::RayTest(pe, fromPoint, toPoint, callback) && rayData.m_hitObject) { return rayData.m_hitObject->GetProxy(); } Py_RETURN_NONE; } /* faster then Py_BuildValue since some scripts call raycast a lot */ static PyObject *none_tuple_3() { PyObject *ret = PyTuple_New(3); PyTuple_SET_ITEM(ret, 0, Py_None); PyTuple_SET_ITEM(ret, 1, Py_None); PyTuple_SET_ITEM(ret, 2, Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); return ret; } static PyObject *none_tuple_4() { PyObject *ret = PyTuple_New(4); PyTuple_SET_ITEM(ret, 0, Py_None); PyTuple_SET_ITEM(ret, 1, Py_None); PyTuple_SET_ITEM(ret, 2, Py_None); PyTuple_SET_ITEM(ret, 3, Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); return ret; } static PyObject *none_tuple_5() { PyObject *ret = PyTuple_New(5); PyTuple_SET_ITEM(ret, 0, Py_None); PyTuple_SET_ITEM(ret, 1, Py_None); PyTuple_SET_ITEM(ret, 2, Py_None); PyTuple_SET_ITEM(ret, 3, Py_None); PyTuple_SET_ITEM(ret, 4, Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); return ret; } KX_PYMETHODDEF_DOC( KX_GameObject, rayCast, "rayCast(to,from,dist,prop,face,xray,poly,mask): cast a ray and return 3-tuple " "(object,hit,normal) or 4-tuple (object,hit,normal,polygon) or 4-tuple " "(object,hit,normal,polygon,hituv) of contact point with object within dist that matches " "prop.\n" " If no hit, return (None,None,None) or (None,None,None,None) or (None,None,None,None,None).\n" " to = 3-tuple or object reference for destination of ray (if object, use center of " "object)\n" " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n" " Can be None or omitted => start from self object center\n" " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to " "to\n" " prop = property name that object must have; can be omitted => detect any object\n" " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards " "origin\n" " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first " "object\n" " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy " "object\n" " which can be None if hit object has no mesh or if there is no " "hit\n" " 2=>return value is a 5-tuple, the 4th element is the KX_PolyProxy " "object\n" " and the 5th element is the vector of UV coordinates at the hit " "point of the None if there is no UV mapping\n" " If 0 or omitted, return value is a 3-tuple\n" " mask = collision mask: the collision mask that ray can hit, 0 < mask < 65536\n" "Note: The object on which you call this method matters: the ray will ignore it.\n" " prop and xray option interact as follow:\n" " prop off, xray off: return closest hit or no hit if there is no object on the full " "extend of the ray\n" " prop off, xray on : idem\n" " prop on, xray off: return closest hit if it matches prop, no hit otherwise\n" " prop on, xray on : return closest hit matching prop or no hit if there is no object " "matching prop on the full extend of the ray\n") { MT_Vector3 toPoint; MT_Vector3 fromPoint; PyObject *pyto; PyObject *pyfrom = Py_None; float dist = 0.0f; const char *propName = ""; KX_GameObject *other; int face = 0, xray = 0, poly = 0; int mask = (1 << OB_MAX_COL_MASKS) - 1; SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); static const char *kwlist[] = {"objto", "objfrom", "dist", "prop", "face", "xray", "poly", "mask", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Ofsiiii:rayCast", const_cast<char**>(kwlist), &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly, &mask)) { return nullptr; // Python sets a simple error } if (!PyVecTo(pyto, toPoint)) { PyErr_Clear(); if (ConvertPythonToGameObject( logicmgr, pyto, &other, false, "")) /* error will be overwritten */ { toPoint = other->NodeGetWorldPosition(); } else { PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject"); return nullptr; } } if (pyfrom == Py_None) { fromPoint = NodeGetWorldPosition(); } else if (!PyVecTo(pyfrom, fromPoint)) { PyErr_Clear(); if (ConvertPythonToGameObject( logicmgr, pyfrom, &other, false, "")) /* error will be overwritten */ { fromPoint = other->NodeGetWorldPosition(); } else { PyErr_SetString(PyExc_TypeError, "gameOb.rayCast(to,from,dist,prop,face,xray,poly,mask): KX_GameObject, the " "second optional argument to rayCast must be a vector or a KX_GameObject"); return nullptr; } } if (mask == 0 || mask & ~((1 << OB_MAX_COL_MASKS) - 1)) { PyErr_Format(PyExc_TypeError, "gameOb.rayCast(to,from,dist,prop,face,xray,poly,mask): KX_GameObject, mask " "argument to rayCast must be a int bitfield, 0 < mask < %i", (1 << OB_MAX_COL_MASKS)); return nullptr; } if (dist != 0.0f) { MT_Vector3 toDir = toPoint - fromPoint; if (MT_fuzzyZero(toDir.length2())) { // return Py_BuildValue("OOO", Py_None, Py_None, Py_None); return none_tuple_3(); } toDir.normalize(); toPoint = fromPoint + (dist)*toDir; } else if (MT_fuzzyZero((toPoint - fromPoint).length2())) { // return Py_BuildValue("OOO", Py_None, Py_None, Py_None); return none_tuple_3(); } PHY_IPhysicsEnvironment *pe = GetScene()->GetPhysicsEnvironment(); PHY_IPhysicsController *spc = GetPhysicsController(); KX_GameObject *parent = GetParent(); if (!spc && parent) spc = parent->GetPhysicsController(); // to get the hit results RayCastData rayData(propName, xray, mask); KX_RayCast::Callback<KX_GameObject, RayCastData> callback( this, spc, &rayData, face, (poly == 2)); if (KX_RayCast::RayTest(pe, fromPoint, toPoint, callback) && rayData.m_hitObject) { PyObject *returnValue = (poly == 2) ? PyTuple_New(5) : (poly) ? PyTuple_New(4) : PyTuple_New(3); if (returnValue) { // unlikely this would ever fail, if it does python sets an error PyTuple_SET_ITEM(returnValue, 0, rayData.m_hitObject->GetProxy()); PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint)); PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal)); if (poly) { if (callback.m_hitMesh) { KX_MeshProxy *meshProxy = new KX_MeshProxy(callback.m_hitMesh); // if this field is set, then we can trust that m_hitPolygon is a valid polygon RAS_Polygon *polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon); KX_PolyProxy *polyproxy = new KX_PolyProxy(meshProxy, callback.m_hitMesh, polygon); PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true)); if (poly == 2) { if (callback.m_hitUVOK) PyTuple_SET_ITEM(returnValue, 4, PyObjectFrom(callback.m_hitUV)); else { Py_INCREF(Py_None); PyTuple_SET_ITEM(returnValue, 4, Py_None); } } } else { Py_INCREF(Py_None); PyTuple_SET_ITEM(returnValue, 3, Py_None); if (poly == 2) { Py_INCREF(Py_None); PyTuple_SET_ITEM(returnValue, 4, Py_None); } } } } return returnValue; } // no hit if (poly == 2) return none_tuple_5(); else if (poly) return none_tuple_4(); else return none_tuple_3(); } KX_PYMETHODDEF_DOC(KX_GameObject, sendMessage, "sendMessage(subject, [body, to])\n" "sends a message in same manner as a message actuator" "subject = Subject of the message (string)" "body = Message body (string)" "to = Name of object to send the message to") { char *subject; char *body = (char *)""; char *to = (char *)""; static const char *kwlist[] = {"subject", "body", "to", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|ss:sendMessage", const_cast<char**>(kwlist), &subject, &body, &to)) { return nullptr; } GetScene()->GetNetworkMessageScene()->SendMessage(to, this, subject, body); Py_RETURN_NONE; } static void layer_check(short &layer, const char *method_name) { if (layer < 0 || layer >= MAX_ACTION_LAYERS) { CM_PythonFunctionWarning("KX_GameObject", method_name, "given layer (" << layer << ") is out of range (0 - " << (MAX_ACTION_LAYERS - 1) << "), setting to 0."); layer = 0; } } KX_PYMETHODDEF_DOC(KX_GameObject, playAction, "playAction(name, start_frame, end_frame, layer=0, priority=0 blendin=0, " "play_mode=ACT_MODE_PLAY, layer_weight=0.0, ipo_flags=0, speed=1.0)\n" "Plays an action\n") { const char *name; float start, end, blendin = 0.f, speed = 1.f, layer_weight = 0.f; short layer = 0, priority = 0; short ipo_flags = 0; short play_mode = 0; short blend_mode = 0; static const char *kwlist[] = {"name", "start_frame", "end_frame", "layer", "priority", "blendin", "play_mode", "layer_weight", "ipo_flags", "speed", "blend_mode", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "sff|hhfhfhfh:playAction", const_cast<char **>(kwlist), &name, &start, &end, &layer, &priority, &blendin, &play_mode, &layer_weight, &ipo_flags, &speed, &blend_mode)) { return nullptr; } layer_check(layer, "playAction"); if (play_mode < 0 || play_mode > BL_Action::ACT_MODE_MAX) { CM_PythonFunctionWarning("KX_GameObject", "playAction", "given play_mode (" << play_mode << ") is out of range (0 - " << (BL_Action::ACT_MODE_MAX - 1) << "), setting to ACT_MODE_PLAY"); play_mode = BL_Action::ACT_MODE_PLAY; } if (blend_mode < 0 || blend_mode > BL_Action::ACT_BLEND_MAX) { CM_PythonFunctionWarning("KX_GameObject", "playAction", "given blend_mode (" << blend_mode << ") is out of range (0 - " << (BL_Action::ACT_BLEND_MAX - 1) << "), setting to ACT_BLEND_BLEND"); blend_mode = BL_Action::ACT_BLEND_BLEND; } if (layer_weight < 0.f || layer_weight > 1.f) { CM_PythonFunctionWarning( "KX_GameObject", "playAction", "given layer_weight (" << layer_weight << ") is out of range (0.0 - 1.0), setting to 0.0"); layer_weight = 0.f; } PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, speed, blend_mode); Py_RETURN_NONE; } KX_PYMETHODDEF_DOC(KX_GameObject, stopAction, "stopAction(layer=0)\n" "Stop playing the action on the given layer\n") { short layer = 0; if (!PyArg_ParseTuple(args, "|h:stopAction", &layer)) { return nullptr; } layer_check(layer, "stopAction"); StopAction(layer); Py_RETURN_NONE; } KX_PYMETHODDEF_DOC(KX_GameObject, getActionFrame, "getActionFrame(layer=0)\n" "Gets the current frame of the action playing in the supplied layer\n") { short layer = 0; if (!PyArg_ParseTuple(args, "|h:getActionFrame", &layer)) { return nullptr; } layer_check(layer, "getActionFrame"); return PyFloat_FromDouble(GetActionFrame(layer)); } KX_PYMETHODDEF_DOC(KX_GameObject, getActionName, "getActionName(layer=0)\n" "Gets the name of the current action playing in the supplied layer\n") { short layer = 0; if (!PyArg_ParseTuple(args, "|h:getActionName", &layer)) { return nullptr; } layer_check(layer, "getActionName"); return PyUnicode_FromStdString(GetActionName(layer)); } KX_PYMETHODDEF_DOC(KX_GameObject, setActionFrame, "setActionFrame(frame, layer=0)\n" "Set the current frame of the action playing in the supplied layer\n") { short layer = 0; float frame; if (!PyArg_ParseTuple(args, "f|h:setActionFrame", &frame, &layer)) { return nullptr; } layer_check(layer, "setActionFrame"); SetActionFrame(layer, frame); Py_RETURN_NONE; } KX_PYMETHODDEF_DOC(KX_GameObject, isPlayingAction, "isPlayingAction(layer=0)\n" "Checks to see if there is an action playing in the given layer\n") { short layer = 0; if (!PyArg_ParseTuple(args, "|h:isPlayingAction", &layer)) { return nullptr; } layer_check(layer, "isPlayingAction"); return PyBool_FromLong(!IsActionDone(layer)); } KX_PYMETHODDEF_DOC(KX_GameObject, recalcGeometry, "ID_RECALC_GEOMETRY depsgraph notifier\n") { RecalcGeometry(); Py_RETURN_NONE; } KX_PYMETHODDEF_DOC(KX_GameObject, recalcTransform, "ID_RECALC_TRANSFORM depsgraph notifier\n") { Object *ob = GetBlenderObject(); if (ob && OrigObCanBeTransformedInRealtime(ob)) { DEG_id_tag_update(&GetBlenderObject()->id, ID_RECALC_TRANSFORM); } Py_RETURN_NONE; } KX_PYMETHODDEF_DOC(KX_GameObject, addDebugProperty, "addDebugProperty(name, visible=1)\n" "Added or remove a debug property to the debug list.\n") { KX_Scene *scene = GetScene(); char *name; int visible = 1; if (!PyArg_ParseTuple(args, "s|i:debugProperty", &name, &visible)) { return nullptr; } if (visible) { if (!scene->PropertyInDebugList(this, name)) scene->AddDebugProperty(this, name); } else { scene->RemoveDebugProperty(this, name); } Py_RETURN_NONE; } /* dict style access */ /* Matches python dict.get(key, [default]) */ PyObject *KX_GameObject::Pyget(PyObject *args) { PyObject *key; PyObject *def = Py_None; PyObject *ret; if (!PyArg_ParseTuple(args, "O|O:get", &key, &def)) { return nullptr; } if (PyUnicode_Check(key)) { CValue *item = GetProperty(_PyUnicode_AsString(key)); if (item) { ret = item->ConvertValueToPython(); if (ret) return ret; else return item->GetProxy(); } } if (m_attr_dict && (ret = PyDict_GetItem(m_attr_dict, key))) { Py_INCREF(ret); return ret; } Py_INCREF(def); return def; } bool ConvertPythonToGameObject(SCA_LogicManager *manager, PyObject *value, KX_GameObject **object, bool py_none_ok, const char *error_prefix) { if (value == nullptr) { PyErr_Format(PyExc_TypeError, "%s, python pointer nullptr, should never happen", error_prefix); *object = nullptr; return false; } if (value == Py_None) { *object = nullptr; if (py_none_ok) { return true; } else { PyErr_Format(PyExc_TypeError, "%s, expected KX_GameObject or a KX_GameObject name, None is invalid", error_prefix); return false; } } if (PyUnicode_Check(value)) { *object = (KX_GameObject *)manager->GetGameObjectByName( std::string(_PyUnicode_AsString(value))); if (*object) { return true; } else { PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_GameObject in this scene", error_prefix, _PyUnicode_AsString(value)); return false; } } if (PyObject_TypeCheck(value, &KX_GameObject::Type) || PyObject_TypeCheck(value, &KX_LightObject::Type) || PyObject_TypeCheck(value, &KX_Camera::Type) || PyObject_TypeCheck(value, &KX_FontObject::Type) || PyObject_TypeCheck(value, &KX_NavMeshObject::Type)) { *object = static_cast<KX_GameObject *> BGE_PROXY_REF(value); /* sets the error */ if (*object == nullptr) { PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix); return false; } return true; } *object = nullptr; if (py_none_ok) { PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject, a string or None", error_prefix); } else { PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject or a string", error_prefix); } return false; } #endif // WITH_PYTHON
/* * Copyright (c) 2019, 2021, Oracle and/or its affiliates. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "modules/adminapi/cluster/cluster_join.h" #include <mysql.h> #include <mysqld_error.h> #include <climits> #include <memory> #include <utility> #include <vector> #include "modules/adminapi/common/clone_options.h" #include "modules/adminapi/common/common.h" #include "modules/adminapi/common/dba_errors.h" #include "modules/adminapi/common/errors.h" #include "modules/adminapi/common/gtid_validations.h" #include "modules/adminapi/common/member_recovery_monitoring.h" #include "modules/adminapi/common/metadata_storage.h" #include "modules/adminapi/common/provision.h" #include "modules/adminapi/common/sql.h" #include "modules/adminapi/common/validations.h" #include "modules/adminapi/mod_dba_cluster.h" #include "mysqlshdk/include/shellcore/console.h" #include "mysqlshdk/libs/mysql/clone.h" #include "mysqlshdk/libs/mysql/group_replication.h" #include "mysqlshdk/libs/mysql/replication.h" #include "mysqlshdk/libs/textui/textui.h" #include "mysqlshdk/libs/utils/debug.h" #include "mysqlshdk/libs/utils/utils_net.h" namespace mysqlsh { namespace dba { namespace cluster { // # of seconds to wait until recovery starts constexpr const int k_recovery_start_timeout = 30; Cluster_join::Cluster_join( Cluster_impl *cluster, mysqlsh::dba::Instance *primary_instance, const std::shared_ptr<mysqlsh::dba::Instance> &target_instance, const Group_replication_options &gr_options, const Clone_options &clone_options, bool interactive) : m_cluster(cluster), m_primary_instance(primary_instance), m_target_instance(target_instance), m_gr_opts(gr_options), m_clone_opts(clone_options), m_interactive(interactive) { // Validate the GR options. // Note: If the user provides no group_seeds value, it is automatically // assigned a value with the local_address values of the existing cluster // members and those local_address values are already validated on the // validate_local_address_ip_compatibility method, so we only need to validate // the group_seeds value provided by the user. m_gr_opts.check_option_values(m_target_instance->get_version()); // Validate the Clone options. m_clone_opts.check_option_values(m_target_instance->get_version()); } void Cluster_join::ensure_instance_check_installed_schema_version() const { // Get the lowest server version of the online members of the cluster. mysqlshdk::utils::Version lowest_cluster_version = m_cluster->get_lowest_instance_version(); try { // Check instance version compatibility according to Group Replication. mysqlshdk::gr::check_instance_check_installed_schema_version( *m_target_instance, lowest_cluster_version); } catch (const std::runtime_error &err) { auto console = mysqlsh::current_console(); console->print_error( "Cannot join instance '" + m_target_instance->descr() + "' to cluster: instance version is incompatible with the cluster."); throw; } // Print a warning if the instance is only read compatible. if (mysqlshdk::gr::is_instance_only_read_compatible(*m_target_instance, lowest_cluster_version)) { auto console = mysqlsh::current_console(); console->print_warning("The instance '" + m_target_instance->descr() + "' is only read compatible with the cluster, thus " "it will join the cluster in R/O mode."); } } void Cluster_join::resolve_local_address( Group_replication_options *gr_options, const Group_replication_options &user_gr_options, checks::Check_type check_type) { std::string hostname = m_target_instance->get_canonical_hostname(); gr_options->local_address = mysqlsh::dba::resolve_gr_local_address( user_gr_options.local_address.get_safe().empty() ? gr_options->local_address : user_gr_options.local_address, hostname, *m_target_instance->get_sysvar_int("port"), !m_already_member && check_type == checks::Check_type::JOIN, check_type != checks::Check_type::JOIN); // Validate that the local_address value we want to use as well as the // local address values in use on the cluster are compatible with the // version of the instance being added to the cluster. validate_local_address_ip_compatibility(gr_options->local_address.get_safe(), gr_options->group_seeds.get_safe(), check_type); } void Cluster_join::validate_local_address_ip_compatibility( const std::string &local_address, const std::string &group_seeds, checks::Check_type check_type) const { // local_address must have some value assert(!local_address.empty()); // Validate that the group_replication_local_address is valid for the version // of the target instance. if (!mysqlshdk::gr::is_endpoint_supported_by_gr( local_address, m_target_instance->get_version())) { auto console = mysqlsh::current_console(); console->print_error("Cannot join instance '" + m_target_instance->descr() + "' to cluster: unsupported localAddress value."); throw shcore::Exception::argument_error(shcore::str_format( "Cannot use value '%s' for option localAddress because it has " "an IPv6 address which is only supported by Group Replication " "from MySQL version >= 8.0.14 and the target instance version is %s.", local_address.c_str(), m_target_instance->get_version().get_base().c_str())); } if (check_type != checks::Check_type::BOOTSTRAP) { // Validate that the localAddress values of the cluster members are // compatible with the target instance we are adding auto local_address_list = shcore::str_split(group_seeds, ","); std::vector<std::string> unsupported_addresses; for (const auto &raw_local_addr : local_address_list) { std::string local_addr = shcore::str_strip(raw_local_addr); if (!mysqlshdk::gr::is_endpoint_supported_by_gr( local_addr, m_target_instance->get_version())) { unsupported_addresses.push_back(local_addr); } } if (!unsupported_addresses.empty()) { std::string value_str = (unsupported_addresses.size() == 1) ? "value" : "values"; auto console = mysqlsh::current_console(); console->print_error( "Cannot join instance '" + m_target_instance->descr() + "' to cluster: unsupported localAddress value on the cluster."); throw shcore::Exception::runtime_error(shcore::str_format( "Instance does not support the following localAddress %s of the " "cluster: '%s'. IPv6 " "addresses/hostnames are only supported by Group " "Replication from MySQL version >= 8.0.14 and the target instance " "version is %s.", value_str.c_str(), shcore::str_join(unsupported_addresses.cbegin(), unsupported_addresses.cend(), ", ") .c_str(), m_target_instance->get_version().get_base().c_str())); } // validate that the value of the localAddress is supported by all // existing cluster members // Get the lowest cluster version mysqlshdk::utils::Version lowest_cluster_version = m_cluster->get_lowest_instance_version(); if (!mysqlshdk::gr::is_endpoint_supported_by_gr(local_address, lowest_cluster_version)) { auto console = mysqlsh::current_console(); console->print_error( "Cannot join instance '" + m_target_instance->descr() + "' to cluster: localAddress value not supported by the cluster."); throw shcore::Exception::argument_error(shcore::str_format( "Cannot use value '%s' for option localAddress because it has " "an IPv6 address which is only supported by Group Replication " "from MySQL version >= 8.0.14 but the cluster " "contains at least one member with version %s.", local_address.c_str(), lowest_cluster_version.get_base().c_str())); } } } /** * Resolves SSL mode based on the given options. * * Determine the SSL mode for the instance based on the cluster SSL mode and * if SSL is enabled on the target instance. The same SSL mode of the cluster * is used for new instance joining it. */ void Cluster_join::resolve_ssl_mode() { // Set SSL Mode to AUTO by default (not defined). if (m_gr_opts.ssl_mode.is_null()) { m_gr_opts.ssl_mode = dba::kMemberSSLModeAuto; } if (m_primary_instance) { resolve_instance_ssl_mode(*m_target_instance, *m_primary_instance, &m_gr_opts.ssl_mode); log_info("SSL mode used to configure the instance: '%s'", m_gr_opts.ssl_mode->c_str()); } } void Cluster_join::ensure_unique_server_id() const { try { m_cluster->validate_server_id(*m_target_instance); } catch (const std::runtime_error &err) { auto console = mysqlsh::current_console(); console->print_error("Cannot join instance '" + m_target_instance->descr() + "' to the cluster because it has the same server ID " "of a member of the cluster. Please change the server " "ID of the instance to add: all members must have a " "unique server ID."); throw; } } void Cluster_join::handle_recovery_account() const { /* Since clone copies all the data, including mysql.slave_master_info (where the CHANGE MASTER credentials are stored), the following issue may happen: 1) Group is bootstrapped on server1. user_account: mysql_innodb_cluster_1 2) server2 is added to the group user_account: mysql_innodb_cluster_2 But server2 is cloned from server1, which means its recovery account will be mysql_innodb_cluster_1 3) server3 is added to the group user_account: mysql_innodb_cluster_3 But server3 is cloned from server1, which means its recovery account will be mysql_innodb_cluster_1 4) server1 is removed from the group mysql_innodb_cluster_1 account is dropped on all group servers. To avoid such situation, we will re-issue the CHANGE MASTER query after clone to ensure the Metadata Schema for each instance holds the user used by GR. On top of that, we will make sure that the account is not dropped if any other cluster member is using it. The approach to tackle the usage of the recovery accounts is to store them in the Metadata, i.e. in addInstance() the user created in the "donor" is stored in the Metadata table referring to the instance being added. In removeInstance(), the Metadata is verified to check whether the recovery user of that instance is registered for more than one instance and if that's the case then it won't be dropped. createCluster() @ instance1: 1) create recovery acct: foo1@% 2) insert into MD for instance1: foo1 3) start GR addInstance(instance2): 1) create recovery acct on primary: foo2@% 2) insert into MD for instance2: foo1@% 3) clone 4) change master to use foo2@% 5) update MD for instance2 with user: foo2@% */ // Get the "donor" recovery account auto md_inst = m_cluster->get_metadata_storage()->get_md_server(); std::string recovery_user, recovery_user_host; std::tie(recovery_user, recovery_user_host) = m_cluster->get_metadata_storage()->get_instance_recovery_account( md_inst->get_uuid()); // Insert the "donor" recovery account into the MD of the target instance log_debug("Adding donor recovery account to metadata"); m_cluster->get_metadata_storage()->update_instance_recovery_account( m_target_instance->get_uuid(), recovery_user, "%"); } void Cluster_join::update_change_master() const { // See note in handle_recovery_account() std::string source_term = mysqlshdk::mysql::get_replication_source_keyword( m_target_instance->get_version()); log_debug("Re-issuing the CHANGE %s command", source_term.c_str()); mysqlshdk::gr::change_recovery_credentials( *m_target_instance, m_gr_opts.recovery_credentials->user, m_gr_opts.recovery_credentials->password.get_safe()); // Update the recovery account to the right one log_debug("Adding recovery account to metadata"); m_cluster->get_metadata_storage()->update_instance_recovery_account( m_target_instance->get_uuid(), m_gr_opts.recovery_credentials->user, "%"); } void Cluster_join::refresh_target_connections() { { try { m_target_instance->query("SELECT 1"); } catch (const shcore::Error &err) { auto e = shcore::Exception::mysql_error_with_code(err.what(), err.code()); if (CR_SERVER_LOST == e.code()) { log_debug( "Target instance connection lost: %s. Re-establishing a " "connection.", e.format().c_str()); try { m_target_instance->get_session()->connect( m_target_instance->get_connection_options()); } catch (const shcore::Error &ie) { auto cluster_coptions = m_cluster->get_target_server()->get_connection_options(); if (ie.code() == ER_ACCESS_DENIED_ERROR && m_target_instance->get_connection_options().get_user() != cluster_coptions.get_user()) { // try again with cluster credentials auto copy = m_target_instance->get_connection_options(); copy.set_login_options_from(cluster_coptions); m_target_instance->get_session()->connect(copy); } else { throw; } } m_target_instance->prepare_session(); } else { throw; } } try { m_cluster->get_metadata_storage()->get_md_server()->query("SELECT 1"); } catch (const shcore::Error &err) { auto e = shcore::Exception::mysql_error_with_code(err.what(), err.code()); if (CR_SERVER_LOST == e.code()) { log_debug( "Metadata connection lost: %s. Re-establishing a " "connection.", e.format().c_str()); auto md_server = m_cluster->get_metadata_storage()->get_md_server(); md_server->get_session()->connect(md_server->get_connection_options()); md_server->prepare_session(); } else { throw; } } } } void Cluster_join::handle_clone_plugin_state(bool enable_clone) { // First, handle the target instance if (enable_clone) { log_info("Installing the clone plugin on instance '%s'.", m_target_instance->get_canonical_address().c_str()); mysqlshdk::mysql::install_clone_plugin(*m_target_instance, nullptr); } else { log_info("Uninstalling the clone plugin on instance '%s'.", m_target_instance->get_canonical_address().c_str()); mysqlshdk::mysql::uninstall_clone_plugin(*m_target_instance, nullptr); } // Then, handle the cluster members m_cluster->setup_clone_plugin(enable_clone); } void Cluster_join::check_cluster_members_limit() const { const std::vector<Instance_metadata> all_instances = m_cluster->get_metadata_storage()->get_all_instances(m_cluster->get_id()); if (all_instances.size() >= mysqlsh::dba::k_group_replication_members_limit) { auto console = mysqlsh::current_console(); console->print_error( "Cannot join instance '" + m_target_instance->descr() + "' to cluster: InnoDB Cluster maximum limit of " + std::to_string(mysqlsh::dba::k_group_replication_members_limit) + " members has been reached."); throw shcore::Exception::runtime_error( "InnoDB Cluster already has the maximum number of " + std::to_string(mysqlsh::dba::k_group_replication_members_limit) + " members."); } } Member_recovery_method Cluster_join::check_recovery_method( bool clone_disabled) { // Check GTID consistency and whether clone is needed auto check_recoverable = [this](mysqlshdk::mysql::IInstance *target) { // Check if the GTIDs were purged from the whole cluster bool recoverable = false; m_cluster->execute_in_members( {mysqlshdk::gr::Member_state::ONLINE}, target->get_connection_options(), {}, [&recoverable, &target](const std::shared_ptr<Instance> &instance) { // Get the gtid state in regards to the cluster_session mysqlshdk::mysql::Replica_gtid_state state = mysqlshdk::mysql::check_replica_gtid_state(*instance, *target, nullptr, nullptr); if (state != mysqlshdk::mysql::Replica_gtid_state::IRRECOVERABLE) { recoverable = true; // stop searching as soon as we find a possible donor return false; } return true; }); return recoverable; }; std::shared_ptr<Instance> donor_instance = m_cluster->get_target_server(); auto recovery_method = mysqlsh::dba::validate_instance_recovery( Cluster_type::GROUP_REPLICATION, Member_op_action::ADD_INSTANCE, donor_instance.get(), m_target_instance.get(), check_recoverable, *m_clone_opts.recovery_method, m_cluster->get_gtid_set_is_complete(), m_interactive, clone_disabled); // If recovery method was selected as clone, check that there is at least one // ONLINE cluster instance not using IPV6, otherwise throw an error if (recovery_method == Member_recovery_method::CLONE) { bool found_ipv4 = false; std::string full_msg; // get online members const auto online_instances = m_cluster->get_instances({mysqlshdk::gr::Member_state::ONLINE}); // check if at least one of them is not IPv6, otherwise throw an error for (const auto &instance : online_instances) { if (!mysqlshdk::utils::Net::is_ipv6( mysqlshdk::utils::split_host_and_port(instance.endpoint).first)) { found_ipv4 = true; break; } else { std::string msg = "Instance '" + instance.endpoint + "' is not a suitable clone donor: Instance " "hostname/report_host is an IPv6 address, which is " "not supported for cloning."; log_info("%s", msg.c_str()); full_msg += msg + "\n"; } } if (!found_ipv4) { auto console = current_console(); console->print_error( "None of the ONLINE members in the cluster are compatible to be used " "as clone donors for " + m_target_instance->descr()); console->print_info(full_msg); throw shcore::Exception("The Cluster has no compatible clone donors.", SHERR_DBA_CLONE_NO_DONORS); } } return recovery_method; } void Cluster_join::check_instance_configuration(checks::Check_type type) { Group_replication_options user_options(m_gr_opts); if (type != checks::Check_type::BOOTSTRAP) { // Check instance version compatibility with cluster. ensure_instance_check_installed_schema_version(); // Resolve the SSL Mode to use to configure the instance. resolve_ssl_mode(); } if (type == checks::Check_type::BOOTSTRAP) { // The current 'group_replication_group_name' must be kept otherwise // if instances are rejoined later the operation may fail because // a new group_name started being used. m_gr_opts.group_name = m_cluster->get_group_name(); } if (type != checks::Check_type::JOIN) { // Read actual GR configurations to preserve them when rejoining the // instance. m_gr_opts.read_option_values(*m_target_instance); } // Check instance configuration and state, like dba.checkInstance // But don't do it if it was already done by the caller ensure_gr_instance_configuration_valid(m_target_instance.get(), type == checks::Check_type::JOIN); // Validate the lower_case_table_names and default_table_encryption // variables. Their values must be the same on the target instance as they // are on the cluster. if (type != checks::Check_type::BOOTSTRAP) { // The lower_case_table_names can only be set the first time the server // boots, as such there is no need to validate it other than the first time // the instance is added to the cluster. m_cluster->validate_variable_compatibility(*m_target_instance, "lower_case_table_names"); // The default_table_encryption is a dynamic variable, so we validate it on // the Cluster_join and on the rejoin operation. The reboot operation does a // rejoin in the background, so running the check on the rejoin will cover // both operations. if (m_cluster->get_lowest_instance_version() >= mysqlshdk::utils::Version(8, 0, 16) && m_target_instance->get_version() >= mysqlshdk::utils::Version(8, 0, 16)) { m_cluster->validate_variable_compatibility(*m_target_instance, "default_table_encryption"); } } // Verify if the instance is running asynchronous // replication // NOTE: Verify for all operations: addInstance(), rejoinInstance() and // rebootClusterFromCompleteOutage() validate_async_channels(*m_target_instance, type); if (type != checks::Check_type::BOOTSTRAP) { // If this is not seed instance, then we should try to read the // failoverConsistency and expelTimeout values from a a cluster member. m_cluster->query_group_wide_option_values(m_target_instance.get(), &m_gr_opts.consistency, &m_gr_opts.expel_timeout); } if (type == checks::Check_type::JOIN) { if (!m_already_member) { // Check instance server UUID (must be unique among the cluster members). m_cluster->validate_server_uuid(*m_target_instance); // Ensure instance server ID is unique among the cluster members. ensure_unique_server_id(); } } // If no group_seeds value was provided by the user, then, // before joining instance to cluster, get the values of the // gr_local_address from all the active members of the cluster if (user_options.group_seeds.is_null() || user_options.group_seeds->empty()) { if (type == checks::Check_type::REJOIN) m_gr_opts.group_seeds = m_cluster->get_cluster_group_seeds(m_target_instance); else if (type == checks::Check_type::JOIN) m_gr_opts.group_seeds = m_cluster->get_cluster_group_seeds(); } // Resolve and validate GR local address. // NOTE: Must be done only after getting the report_host used by GR and for // the metadata; resolve_local_address(&m_gr_opts, user_options, type); } namespace { bool check_auto_rejoining(Instance *instance) { // Check if instance was doing auto-rejoin and let the user know that the // rejoin operation will override the auto-rejoin if (mysqlshdk::gr::is_running_gr_auto_rejoin(*instance) || mysqlshdk::gr::is_group_replication_delayed_starting(*instance)) { auto console = current_console(); console->print_note( "The instance '" + instance->get_connection_options().uri_endpoint() + "' is running auto-rejoin process, which will be cancelled."); console->print_info(); return true; } return false; } void ensure_not_auto_rejoining(Instance *instance) { auto console = current_console(); console->print_note("Cancelling active GR auto-initialization at " + instance->descr()); mysqlshdk::gr::stop_group_replication(*instance); } } // namespace bool Cluster_join::check_rejoinable(bool *out_uuid_mistmatch) { // Check if the instance is part of the Metadata auto status = validate_instance_rejoinable( *m_target_instance, m_cluster->get_metadata_storage(), m_cluster->get_id(), out_uuid_mistmatch); switch (status) { case Instance_rejoinability::NOT_MEMBER: throw shcore::Exception::runtime_error( "The instance '" + m_target_instance->descr() + "' " + "does not belong to the cluster: '" + m_cluster->get_name() + "'."); case Instance_rejoinability::ONLINE: current_console()->print_note( m_target_instance->descr() + " is already an active (ONLINE) member of cluster '" + m_cluster->get_name() + "'."); return false; case Instance_rejoinability::RECOVERING: current_console()->print_note( m_target_instance->descr() + " is already an active (RECOVERING) member of cluster '" + m_cluster->get_name() + "'."); return false; case Instance_rejoinability::REJOINABLE: break; } std::string nice_error = "The instance '" + m_target_instance->descr() + "' may belong to a different cluster as the one registered " "in the Metadata since the value of " "'group_replication_group_name' does not match the one " "registered in the cluster's Metadata: possible split-brain " "scenario. Please remove the instance from the cluster."; try { if (!validate_cluster_group_name(*m_target_instance, m_cluster->get_group_name())) { throw shcore::Exception::runtime_error(nice_error); } } catch (const shcore::Error &e) { // If the GR plugin is not installed, we can get this error. // In that case, we install the GR plugin and retry. if (e.code() == ER_UNKNOWN_SYSTEM_VARIABLE) { log_info("%s: installing GR plugin (%s)", m_target_instance->descr().c_str(), e.format().c_str()); mysqlshdk::gr::install_group_replication_plugin(*m_target_instance, nullptr); if (!validate_cluster_group_name(*m_target_instance, m_cluster->get_group_name())) { throw shcore::Exception::runtime_error(nice_error); } } else { throw; } } return true; } void Cluster_join::prepare_reboot() { m_is_autorejoining = check_auto_rejoining(m_target_instance.get()); // Make sure the target instance does not already belong to a different // cluster. mysqlsh::dba::checks::ensure_instance_not_belong_to_cluster( *m_target_instance, m_cluster->get_target_server(), &m_already_member); check_instance_configuration(checks::Check_type::BOOTSTRAP); } void Cluster_join::prepare_join( const mysqlshdk::utils::nullable<std::string> &instance_label) { m_instance_label = instance_label; check_cluster_members_limit(); // Make sure there isn't some leftover auto-rejoin active m_is_autorejoining = check_auto_rejoining(m_target_instance.get()); // Make sure the target instance does not already belong to a cluster. // Unless it's our cluster, in that case we keep adding it since it // may be a retry. if (mysqlsh::dba::checks::ensure_instance_not_belong_to_cluster( *m_target_instance, m_cluster->get_target_server(), &m_already_member) == InstanceType::InnoDBCluster) { throw shcore::Exception::runtime_error( "The instance '" + m_target_instance->descr() + "' is already part of this InnoDB cluster"); } // Pick recovery method and check if it's actually usable // Done last to not request interaction before validations m_clone_opts.recovery_method = check_recovery_method(m_cluster->get_disable_clone_option()); // Check for various instance specific configuration issues check_instance_configuration(checks::Check_type::JOIN); } bool Cluster_join::prepare_rejoin(bool *out_uuid_mistmatch) { m_is_autorejoining = check_auto_rejoining(m_target_instance.get()); if (!check_rejoinable(out_uuid_mistmatch)) return false; // Check for various instance specific configuration issues check_instance_configuration(checks::Check_type::REJOIN); // Check GTID consistency to determine if the instance can safely rejoin the // cluster BUG#29953812: ADD_INSTANCE() PICKY ABOUT GTID_EXECUTED, // REJOIN_INSTANCE() NOT: DATA NOT COPIED m_cluster->validate_rejoin_gtid_consistency(*m_target_instance); return true; } bool Cluster_join::handle_replication_user() { // Creates the replication user ONLY if not already given. // NOTE: User always created at the seed instance. if (!m_gr_opts.recovery_credentials || m_gr_opts.recovery_credentials->user.empty()) { m_gr_opts.recovery_credentials = m_cluster->create_replication_user(m_target_instance.get()); return true; } return false; } /** * Clean (drop) the replication user, in case the operation fails. */ void Cluster_join::clean_replication_user() { if (m_gr_opts.recovery_credentials && !m_gr_opts.recovery_credentials->user.empty()) { auto primary = m_cluster->get_target_server(); log_debug("Dropping recovery user '%s'@'%%' at instance '%s'.", m_gr_opts.recovery_credentials->user.c_str(), primary->descr().c_str()); primary->drop_user(m_gr_opts.recovery_credentials->user, "%", true); } } void Cluster_join::log_used_gr_options() { auto console = mysqlsh::current_console(); if (!m_gr_opts.local_address.is_null() && !m_gr_opts.local_address->empty()) { log_info("Using Group Replication local address: %s", m_gr_opts.local_address->c_str()); } if (!m_gr_opts.group_seeds.is_null() && !m_gr_opts.group_seeds->empty()) { log_info("Using Group Replication group seeds: %s", m_gr_opts.group_seeds->c_str()); } if (!m_gr_opts.exit_state_action.is_null() && !m_gr_opts.exit_state_action->empty()) { log_info("Using Group Replication exit state action: %s", m_gr_opts.exit_state_action->c_str()); } if (!m_gr_opts.member_weight.is_null()) { log_info("Using Group Replication member weight: %s", std::to_string(*m_gr_opts.member_weight).c_str()); } if (!m_gr_opts.consistency.is_null() && !m_gr_opts.consistency->empty()) { log_info("Using Group Replication failover consistency: %s", m_gr_opts.consistency->c_str()); } if (!m_gr_opts.expel_timeout.is_null()) { log_info("Using Group Replication expel timeout: %s", std::to_string(*m_gr_opts.expel_timeout).c_str()); } if (!m_gr_opts.auto_rejoin_tries.is_null()) { log_info("Using Group Replication auto-rejoin tries: %s", std::to_string(*m_gr_opts.auto_rejoin_tries).c_str()); } } void Cluster_join::update_group_peers(int cluster_member_count, const std::string &self_address) { // Get the gr_address of the instance being added std::string added_instance_gr_address = *m_gr_opts.local_address; // Create a configuration object for the cluster, ignoring the added // instance, to update the remaining cluster members. // NOTE: only members that already belonged to the cluster and are either // ONLINE or RECOVERING will be considered. std::vector<std::string> ignore_instances_vec = {self_address}; std::unique_ptr<mysqlshdk::config::Config> cluster_cfg = m_cluster->create_config_object(ignore_instances_vec, true); // Update the group_replication_group_seeds of the cluster members // by adding the gr_local_address of the instance that was just added. log_debug("Updating Group Replication seeds on all active members..."); mysqlshdk::gr::update_group_seeds(cluster_cfg.get(), added_instance_gr_address, mysqlshdk::gr::Gr_seeds_change_type::ADD); cluster_cfg->apply(); // Increase the cluster_member_count counter cluster_member_count++; // Auto-increment values must be updated according to: // // Set auto-increment for single-primary topology: // - auto_increment_increment = 1 // - auto_increment_offset = 2 // // Set auto-increment for multi-primary topology: // - auto_increment_increment = n; // - auto_increment_offset = 1 + server_id % n; // where n is the size of the GR group if > 7, otherwise n = 7. // // We must update the auto-increment values in Cluster_join for 2 // scenarios // - Multi-primary Cluster // - Cluster that has 7 or more members after the Cluster_join // operation // // NOTE: in the other scenarios, the Cluster_join operation is in // charge of updating auto-increment accordingly // Get the topology mode of the replicaSet mysqlshdk::gr::Topology_mode topology_mode = m_cluster->get_metadata_storage()->get_cluster_topology_mode( m_cluster->get_id()); if (topology_mode == mysqlshdk::gr::Topology_mode::MULTI_PRIMARY && cluster_member_count > 7) { log_debug("Updating auto-increment settings on all active members..."); mysqlshdk::gr::update_auto_increment( cluster_cfg.get(), mysqlshdk::gr::Topology_mode::MULTI_PRIMARY); cluster_cfg->apply(); } } void Cluster_join::wait_recovery(const std::string &join_begin_time, Recovery_progress_style progress_style) { auto console = current_console(); try { auto post_clone_auth = m_target_instance->get_connection_options(); post_clone_auth.set_login_options_from( m_cluster->get_target_server()->get_connection_options()); monitor_gr_recovery_status( m_target_instance->get_connection_options(), post_clone_auth, join_begin_time, progress_style, k_recovery_start_timeout, current_shell_options()->get().dba_restart_wait_timeout); } catch (const shcore::Exception &e) { // If the recovery itself failed we abort, but monitoring errors can be // ignored. if (e.code() == SHERR_DBA_CLONE_RECOVERY_FAILED || e.code() == SHERR_DBA_DISTRIBUTED_RECOVERY_FAILED) { console->print_error("Recovery error in added instance: " + e.format()); throw; } else { console->print_warning( "Error while waiting for recovery of the added instance: " + e.format()); } } catch (const restart_timeout &) { console->print_warning( "Clone process appears to have finished and tried to restart the " "MySQL server, but it has not yet started back up."); console->print_info(); console->print_info( "Please make sure the MySQL server at '" + m_target_instance->descr() + "' is restarted and call <Cluster>.rescan() to complete the process. " "To increase the timeout, change " "shell.options[\"dba.restartWaitTimeout\"]."); throw shcore::Exception("Timeout waiting for server to restart", SHERR_DBA_SERVER_RESTART_TIMEOUT); } } void Cluster_join::join(Recovery_progress_style progress_style) { auto console = mysqlsh::current_console(); // Set the internal configuration object: read/write configs from the server. auto cfg = mysqlsh::dba::create_server_config( m_target_instance.get(), mysqlshdk::config::k_dft_cfg_server_handler); // Common informative logging log_used_gr_options(); console->print_info("Adding instance to the cluster..."); console->print_info(); // Make sure the GR plugin is installed (only installed if needed). // NOTE: An error is issued if it fails to be installed (e.g., DISABLED). // Disable read-only temporarily to install the plugin if needed. mysqlshdk::gr::install_group_replication_plugin(*m_target_instance, nullptr); // Validate group_replication_gtid_assignment_block_size. Its value must be // the same on the instance as it is on the cluster but can only be checked // after the GR plugin is installed. This check is also done on the rejoin // operation which covers the rejoin and rebootCluster operations. m_cluster->validate_variable_compatibility( *m_target_instance, "group_replication_gtid_assignment_block_size"); // Note: We used to auto-downgrade the GR protocol version if the joining // member is too old, but that's not allowed for other reasons anyway // Get the current number of cluster members uint64_t cluster_member_count = m_cluster->get_metadata_storage()->get_cluster_size(m_cluster->get_id()); // Clone handling bool clone_disabled = m_cluster->get_disable_clone_option(); bool clone_supported = mysqlshdk::mysql::is_clone_available(*m_target_instance); int64_t restore_clone_threshold = 0; if (clone_supported) { bool enable_clone = !clone_disabled; // Force clone if requested if (*m_clone_opts.recovery_method == Member_recovery_method::CLONE) { restore_clone_threshold = mysqlshdk::mysql::force_clone(*m_target_instance); // RESET MASTER to clear GTID_EXECUTED in case it's diverged, otherwise // clone is not executed and GR rejects the instance m_target_instance->query("RESET MASTER"); } else if (*m_clone_opts.recovery_method == Member_recovery_method::INCREMENTAL) { // Force incremental distributed recovery if requested enable_clone = false; } // Make sure the Clone plugin is installed or uninstalled depending on the // value of disableClone // // NOTE: If the clone usage is not disabled on the cluster (disableClone), // we must ensure the clone plugin is installed on all members. Otherwise, // if the cluster was creating an Older shell (<8.0.17) or if the cluster // was set up using the Incremental recovery only and the primary is removed // (or a failover happened) the instances won't have the clone plugin // installed and GR's recovery using clone will fail. // // See BUG#29954085 and BUG#29960838 handle_clone_plugin_state(enable_clone); } // Handle the replication user creation. bool owns_repl_user = handle_replication_user(); try { // we need a point in time as close as possible, but still earlier than // when recovery starts to monitor the recovery phase. The timestamp // resolution is timestamp(3) irrespective of platform std::string join_begin_time = m_target_instance->queryf_one_string(0, "", "SELECT NOW(3)"); { if (m_already_member) { // START GROUP_REPLICATION is the last thing that happens in // join_cluster, so if it's already running, we don't need to do that // again log_info("%s is already a group member, skipping join", m_target_instance->descr().c_str()); } else { log_info( "Joining '%s' to cluster using account %s to peer '%s'.", m_target_instance->descr().c_str(), m_primary_instance->get_connection_options().get_user().c_str(), m_primary_instance->descr().c_str()); // Join the instance to the Group Replication group. mysqlsh::dba::join_cluster(*m_target_instance, *m_primary_instance, m_gr_opts, cluster_member_count, cfg.get()); } // Wait until recovery done. Will throw an exception if recovery fails. wait_recovery(join_begin_time, progress_style); // When clone is used, the target instance will restart and all // connections are closed so we need to test if the connection to the // target instance and MD are closed and re-open if necessary refresh_target_connections(); } // Get the address used by GR for the added instance (used in MD). std::string address_in_metadata = m_target_instance->get_canonical_address(); // Check if instance address already belong to cluster (metadata). bool is_instance_on_md = m_cluster->contains_instance_with_address(address_in_metadata); log_debug("Cluster %s: Instance '%s' %s", m_cluster->get_name().c_str(), m_target_instance->descr().c_str(), is_instance_on_md ? "is already in the Metadata." : "is being added to the Metadata..."); MetadataStorage::Transaction trx(m_cluster->get_metadata_storage()); // If the instance is not on the Metadata, we must add it. if (!is_instance_on_md) { m_cluster->add_metadata_for_instance(*m_target_instance, m_instance_label.get_safe()); m_cluster->get_metadata_storage()->update_instance_attribute( m_target_instance->get_uuid(), k_instance_attribute_join_time, shcore::Value(join_begin_time)); // Store the username in the Metadata instances table if (owns_repl_user) { handle_recovery_account(); } } // Update group_seeds and auto_increment in other members update_group_peers(cluster_member_count, address_in_metadata); // Re-issue the CHANGE MASTER command // See note in handle_recovery_account() // NOTE: if waitRecover is zero we cannot do it since distributed recovery // may be running and the change master command will fail as the slave io // thread is running if (owns_repl_user && progress_style != Recovery_progress_style::NOWAIT) { update_change_master(); } // Only commit transaction once everything is done, so that things don't // look all fine if something fails in the middle trx.commit(); log_debug("Instance add finished"); console->print_info("The instance '" + m_target_instance->descr() + "' was successfully added to the cluster."); console->print_info(); } catch (...) { if (owns_repl_user) clean_replication_user(); try { // Check if group_replication_clone_threshold must be restored. // This would only be needed if the clone failed and the server didn't // restart. if (restore_clone_threshold != 0) { // TODO(miguel): 'start group_replication' returns before reading the // threshold value so we can have a race condition. We should wait until // the instance is 'RECOVERING' log_debug( "Restoring value of group_replication_clone_threshold to: %s.", std::to_string(restore_clone_threshold).c_str()); // If -1 we must restore it's default, otherwise we restore the initial // value if (restore_clone_threshold == -1) { m_target_instance->set_sysvar_default( "group_replication_clone_threshold"); } else { m_target_instance->set_sysvar("group_replication_clone_threshold", restore_clone_threshold); } } } catch (const shcore::Error &e) { log_info( "Could not restore value of group_replication_clone_threshold: %s. " "Not a fatal error.", e.what()); } throw; } } void Cluster_join::rejoin() { auto console = current_console(); // Set a Config object for the target instance (required to configure GR). std::unique_ptr<mysqlshdk::config::Config> cfg = create_server_config( m_target_instance.get(), mysqlshdk::config::k_dft_cfg_server_handler); console->print_info("Rejoining instance '" + m_target_instance->descr() + "' to cluster '" + m_cluster->get_name() + "'..."); // Make sure the GR plugin is installed (only installed if needed). // NOTE: An error is issued if it fails to be installed (e.g., DISABLED). // Disable read-only temporarily to install the plugin if needed. mysqlshdk::gr::install_group_replication_plugin(*m_target_instance, nullptr); // Ensure GR is not auto-rejoining, but after the GR plugin is installed if (m_is_autorejoining) ensure_not_auto_rejoining(m_target_instance.get()); // Validate group_replication_gtid_assignment_block_size. Its value must be // the same on the instance as it is on the cluster but can only be checked // after the GR plugin is installed. This check is also done on the rejoin // operation which covers the rejoin and rebootCluster operations. m_cluster->validate_variable_compatibility( *m_target_instance, "group_replication_gtid_assignment_block_size"); // TODO(alfredo) - when clone support is added to rejoin, join() can probably // be simplified into create repl user + rejoin() + update metadata // (Re-)join the instance to the cluster (setting up GR properly). // NOTE: the join_cluster() function expects the number of members in // the cluster excluding the joining node, thus cluster_count must // exclude the rejoining node (cluster size - 1) since it already // belongs to the metadata (BUG#30174191). mysqlshdk::utils::nullable<uint64_t> cluster_count = m_cluster->get_metadata_storage()->get_cluster_size(m_cluster->get_id()) - 1; mysqlsh::dba::join_cluster(*m_target_instance, *m_primary_instance, m_gr_opts, cluster_count, cfg.get()); console->print_info("The instance '" + m_target_instance->descr() + "' was successfully rejoined to the cluster."); console->print_info(); } void Cluster_join::reboot() { auto console = mysqlsh::current_console(); // Set the internal configuration object: read/write configs from the server. auto cfg = mysqlsh::dba::create_server_config( m_target_instance.get(), mysqlshdk::config::k_dft_cfg_server_handler); // Common informative logging log_used_gr_options(); // Make sure the GR plugin is installed (only installed if needed). // NOTE: An error is issued if it fails to be installed (e.g., DISABLED). // Disable read-only temporarily to install the plugin if needed. mysqlshdk::gr::install_group_replication_plugin(*m_target_instance, nullptr); if (m_is_autorejoining) ensure_not_auto_rejoining(m_target_instance.get()); if (!m_gr_opts.group_name.is_null() && !m_gr_opts.group_name->empty()) { log_info("Using Group Replication group name: %s", m_gr_opts.group_name->c_str()); } log_info("Starting cluster with '%s' using account %s", m_target_instance->descr().c_str(), m_target_instance->get_connection_options().get_user().c_str()); // Determine the topology mode to use. mysqlshdk::utils::nullable<bool> multi_primary = m_cluster->get_cluster_topology_type() == mysqlshdk::gr::Topology_mode::MULTI_PRIMARY; // Start the cluster to bootstrap Group Replication. mysqlsh::dba::start_cluster(*m_target_instance, m_gr_opts, multi_primary, cfg.get()); log_debug("Instance add finished"); } } // namespace cluster } // namespace dba } // namespace mysqlsh
#include "O4_2d.h" using namespace itensor; void Measurements::GroundStates(const O4& O4, int n, const std::vector<MPS>& psi_ini, std::vector<Real>& en, std::vector<MPS>& psi) { int sweep_count_total = 0; std::vector<int> sweep_count(n,0); auto wfs = std::vector<MPS>(0); std::ofstream pfile; pfile.open (energy_file); pfile.precision(15); for (int i = 0; i < n; ++i) { auto [en_,psi_] = dmrg(O4.H, wfs, psi_ini[i], ini_sweeps,{"Quiet",true,"Weight=",penalty_weight}); en[i] = en_; psi[i] = psi_; sweep_count[i] += ini_nsweep; sweep_count_total += ini_nsweep; double en_change = 1; while(abs(en_change) > precision) { auto [en_,psi_] = dmrg(O4.H, wfs, psi[i],sweeps,{"Quiet",true,"Weight=",penalty_weight}); psi[i] = psi_; en_change = en_ - en[i]; en[i] = en_; sweep_count[i] += nsweep; sweep_count_total += nsweep; auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); printfln("Ground State Energy Change = %.2E", en_change); std::cout << "Sweep count = " << sweep_count << "Time taken = " << duration.count() << " seconds\n"; } wfs.push_back(psi[i]); writeToFile(mps_file[i], psi[i]); pfile << en[i] << "\n"; } pfile.close(); for (int i = 0; i < n; ++i) printfln("\nen[%d] = %.10f",i,en[i]); for (int i = 0; i < n; ++i) { for (int j = i+1; j < n; ++j) printfln("\nOverlap <psi%d|psi%d> = %.2E",i,j,inner(psi[i],psi[j])); } } Real Measurements::TwopointCorrelation(const Electron& sites, MPS& psi, string Opi, string Opj, int site_i, int site_j) { int N = length(sites); //Make the operators you want to measure auto op_i = op(sites,Opi,site_i); auto op_j = op(sites,Opj,site_j); //'gauge' the MPS to site i //any 'position' between i and j, inclusive, would work here psi.position(site_i); //Create the bra/dual version of the MPS psi auto psidag = dag(psi); //Prime the link indices to make them distinct from //the original ket links psidag.prime("Link"); //index linking i-1 to i: auto li_1 = leftLinkIndex(psi,site_i); auto C = prime(psi(site_i),li_1) * op_i * prime(psidag(site_i),"Site"); for(int k = site_i+1; k < site_j; ++k) { C *= psi(k) * psidag(k); } //index linking j to j+1: auto lj = rightLinkIndex(psi,site_j); C *= prime(psi(site_j),lj) * op_j * prime(psidag(site_j),"Site"); auto result = elt(C); //or eltC(C) if expecting complex //printfln("\nCorrelation = %.10f",4*result); return result; } Real Measurements::FourpointCorrelation(const Electron& sites, MPS& psi, string Op, int site_i, int site_j, int site_k, int site_l) { int N = length(sites); //Make the operators you want to measure auto op_i = op(sites,Op,site_i); auto op_j = op(sites,Op,site_j); auto op_k = op(sites,Op,site_k); auto op_l = op(sites,Op,site_l); //'gauge' the MPS to site i //any 'position' between i and j, inclusive, would work here psi.position(site_i); //Create the bra/dual version of the MPS psi auto psidag = dag(psi); //Prime the link indices to make them distinct from //the original ket links psidag.prime("Link"); //index linking i-1 to i: auto li_1 = leftLinkIndex(psi,site_i); auto C = prime(psi(site_i),li_1) * op_i * prime(psidag(site_i),"Site"); for(int i = site_i+1; i < site_j; ++i) { C *= psi(i) * psidag(i); } C *= psi(site_j) * op_j * prime(psidag(site_j),"Site"); for(int i = site_j+1; i < site_k; ++i) { C *= psi(i) * psidag(i); } C *= psi(site_k) * op_k * prime(psidag(site_k),"Site"); for(int i = site_k+1; i < site_l; ++i) { C *= psi(i) * psidag(i); } //index linking j to j+1: auto ll = rightLinkIndex(psi,site_l); C *= prime(psi(site_l),ll) * op_l * prime(psidag(site_l),"Site"); auto result = elt(C); //or eltC(C) if expecting complex //printfln("\nCorrelation = %.10f",4*result); return result; } Real Measurements::DimerCorrelation(const Electron& sites, MPS& psi, string Op, int site_i, int site_j) { int N = length(sites); //Make the operators you want to measure auto op_i = op(sites,Op,site_i); auto op_i1 = op(sites,Op,site_i+1); auto op_j = op(sites,Op,site_j); auto op_j1 = op(sites,Op,site_j+1); //'gauge' the MPS to site i //any 'position' between i and j, inclusive, would work here psi.position(site_i); //Create the bra/dual version of the MPS psi auto psidag = dag(psi); //Prime the link indices to make them distinct from //the original ket links psidag.prime("Link"); //index linking i-1 to i: auto li_1 = leftLinkIndex(psi,site_i); auto C = prime(psi(site_i),li_1) * op_i * prime(psidag(site_i),"Site"); C *= psi(site_i+1) * op_i1 * prime(psidag(site_i+1),"Site"); for(int k = site_i+2; k < site_j; ++k) { C *= psi(k) * psidag(k); } //index linking j to j+1: auto lj = rightLinkIndex(psi,site_j+1); C *= psi(site_j) * op_j * prime(psidag(site_j),"Site"); C *= prime(psi(site_j+1),lj) * op_j1 * prime(psidag(site_j+1),"Site"); auto result = elt(C); //or eltC(C) if expecting complex //printfln("\nCorrelation = %.10f",4*result); return result; } Real Measurements::EntanglementEntropy(MPS& psi, int b) { int N = length(psi); psi.position(b); //SVD this wavefunction to get the spectrum //of density-matrix eigenvalues auto l = leftLinkIndex(psi,b); auto s = siteIndex(psi,b); auto [U,S,V] = svd(psi(b),{l,s}); auto u = commonIndex(U,S); //Apply von Neumann formula //to the squares of the singular values Real SvN = 0.; for(auto n : range1(dim(u))) { auto Sn = elt(S,n,n); auto p = sqr(Sn); if(p > 1E-12) SvN += -p*log(p); } //printfln("Across bond b=%d, SvN = %.10f",b,SvN); return SvN; } void Measurements::PrintfSpinCorrelation(const O4& O4, MPS& psi) { auto N = O4.N; auto Nx = O4.Nx; auto Ny = O4.Ny; auto file = format("data/spin_Nx%dNy%d_a2%.1f_a3%.1f_U%.5f.dat", Nx, Ny, O4.a2, O4.a3, O4.U); //println(psi); if (!utils::fileExists(file) || new_measurements) { auto sites = O4.sites; std::ofstream ofile; ofile.open (file); for (int i = 1; i<= N/2-dist_to_boundary; ++i) { auto cor = TwopointCorrelation(sites, psi, "Sz", "Sz", N/2, N/2 + i); ofile << i << "\t" << std::pow(1, i) * cor << "\n"; } ofile.close(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "Spin time = " << duration.count() << " seconds\n"; } } void Measurements::PrintfSpinxCorrelation(const O4& O4, MPS& psi) { auto N = O4.N; auto Nx = O4.Nx; auto Ny = O4.Ny; auto file = format("data/spinx_Nx%dNy%d_a2%.1f_a3%.1f_U%.5f.dat", Nx, Ny, O4.a2, O4.a3, O4.U); if (!utils::fileExists(file) || new_measurements) { auto sites = O4.sites; std::ofstream ofile; ofile.open (file); for (int i = 1; i<= N/2-dist_to_boundary; ++i) { auto cor = TwopointCorrelation(sites, psi, "S+", "S-", N/2, N/2 + i); ofile << i << "\t" << std::pow(1, i) * cor << "\n"; } ofile.close(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "Spinx time = " << duration.count() << " seconds\n"; } } void Measurements::PrintfDimerCorrelation(const O4& O4, MPS& psi) { auto N = O4.N; auto Nx = O4.Nx; auto Ny = O4.Ny; auto file = format("data/dimer_Nx%dNy%d_a2%.1f_a3%.1f_U%.5f.dat", Nx, Ny, O4.a2, O4.a3, O4.U); if (!utils::fileExists(file) || new_measurements) { auto sites = O4.sites; std::ofstream ofile; ofile.open (file); int max_dist = N/2-dist_to_boundary-1; std::vector<Real> corN(max_dist); std::vector<Real> corN_1(max_dist); for (int i = 0; i <= max_dist - 1; ++i) { auto corN_1i = DimerCorrelation(sites, psi, "Sz", N/2-2, N/2+i+1); corN_1[i] = corN_1i; auto corNi = DimerCorrelation(sites, psi, "Sz", N/2-1, N/2+i+1); corN[i] = corNi; } for (int i = 3; i <= max_dist+1; ++i) { ofile << i << "\t" << std::pow(1, i) * (corN_1[i-3]-corN_1[i-2]-corN[i-3]+corN[i-2])/4.0 << "\n"; } ofile.close(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "Dimer time = " << duration.count() << " seconds\n"; } } void Measurements::PrintfDimer2Correlation(const O4& O4, MPS& psi) { auto N = O4.N; auto Nx = O4.Nx; auto Ny = O4.Ny; auto file = format("data/dimer2_Nx%dNy%d_a2%.1f_a3%.1f_U%.5f.dat", Nx, Ny, O4.a2, O4.a3, O4.U); if (!utils::fileExists(file) || new_measurements) { auto sites = O4.sites; std::ofstream ofile; ofile.open (file); int max_dist = N/2-dist_to_boundary-1; for (int i = 2; i<= max_dist; ++i) { auto cor = FourpointCorrelation(sites, psi, "Sz", N/2, N/2+1, N/2+i, N/2+i+1)*16; ofile << i << "\t" << cor << "\n"; } ofile.close(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "Dimer2 time = " << duration.count() << " seconds\n"; } } void Measurements::PrintfEntanglementEntropy(const O4& O4, MPS& psi) { auto file = format("data/entropy_Nx%dNy%d_a2%.1f_a3%.1f_U%.5f.dat", O4.Nx, O4.Ny, O4.a2, O4.a3, O4.U); if (!utils::fileExists(file) || new_measurements) { std::ofstream ofile; ofile.open (file); for (int i = 1; i<O4.N; ++i) { auto cor = EntanglementEntropy(psi, i); ofile << i << "\t" << cor << "\n"; } ofile.close(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "Entropy time = " << duration.count() << " seconds\n"; } } void Measurements::PrintS2(const O4& O4, MPS& psi) { auto S2mpo = S2(O4.sites); auto S2num = inner(psi, S2mpo, psi); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); printfln("Total spin = %.5f", S2num); std::cout << "Total spin time = " << duration.count() << " seconds\n"; } void Measurements::PrintMomentum(const O4& O4, MPS& psi) { auto Pmpo1 = Momentum(O4.sites); auto Pmpo2 = nmultMPO(Pmpo1, prime(Pmpo1)); auto Pmpo3 = nmultMPO(Pmpo1, prime(Pmpo2)); auto Pmpo4 = nmultMPO(Pmpo1, prime(Pmpo3)); auto Pmpo5 = nmultMPO(Pmpo1, prime(Pmpo4)); auto Pmpo6 = nmultMPO(Pmpo1, prime(Pmpo5)); auto Pnum1 = innerC(psi, Pmpo1, psi); auto Pnum2 = innerC(psi, Pmpo2, psi); auto Pnum3 = innerC(psi, Pmpo3, psi); auto Pnum4 = innerC(psi, Pmpo4, psi); auto Pnum5 = innerC(psi, Pmpo5, psi); auto Pnum6 = innerC(psi, Pmpo6, psi); auto Pnum = 1 + Pnum1 + Pnum2/2.0 + Pnum3/6.0 + Pnum4/24.0 + Pnum5/120.0 + Pnum6/720.0; auto Pnum_r = fmod(real(Pnum),2); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); printfln("P = %.5f pi", Pnum); printfln("Momentum = %.5f pi", Pnum_r); std::cout << "Momentum time = " << duration.count() << " seconds\n"; } void Measurements::PrintSpin(const O4& O4, MPS& psi) { for (int i=1; i<=O4.N; ++i) { auto spin_mpo = Spin(O4.sites, 1, i); auto spin_num = inner(psi, spin_mpo, psi); //auto stop = std::chrono::high_resolution_clock::now(); //auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); printfln("i = %d, spin correlation = %.10f", i, spin_num); //std::cout << "Total spin time = " << duration.count() << " seconds\n"; } } void Measurements::PrintxDimer(const O4& O4, MPS& psi) { for (int i=1; i<=O4.N; ++i) { auto dimer_mpo = Dimer(O4.sites, 1, 3, i, (i+1)%O4.N+1); auto dimer_num = inner(psi, dimer_mpo, psi); //auto stop = std::chrono::high_resolution_clock::now(); //auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); printfln("i = %d, dimer correlation = %.10f", i, dimer_num); //std::cout << "Total dimer time = " << duration.count() << " seconds\n"; } } void Measurements::PrintyDimer(const O4& O4, MPS& psi) { for (int i=1; i<=O4.N; i+=2) { auto dimer_mpo = Dimer(O4.sites, 1, 2, i, i+1); auto dimer_num = inner(psi, dimer_mpo, psi); //auto stop = std::chrono::high_resolution_clock::now(); //auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); printfln("i = %d, dimer correlation = %.10f", i, dimer_num); //std::cout << "Total dimer time = " << duration.count() << " seconds\n"; } } void Measurements::PrintxyDimer(const O4& O4, MPS& psi) { for (int i=1; i<=O4.N; i+=2) { auto dimer_mpo = Dimer(O4.sites, 1, 3, i, i+1); auto dimer_num = inner(psi, dimer_mpo, psi); //auto stop = std::chrono::high_resolution_clock::now(); //auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); printfln("i = %d, dimer correlation = %.10f", i, dimer_num); //std::cout << "Total dimer time = " << duration.count() << " seconds\n"; } }
#ifndef _TRANSACTION_HPP_ #define _TRANSACTION_HPP_ #include <iomanip> #include <iostream> #include <string> class Transaction { public: // Constructor // Transaction( std::string ticker_symbol, unsigned int day_date, unsigned int month_date, unsigned year_date, bool buy_sell_trans, unsigned int number_shares, double trans_amount ); // Destructor // ~Transaction(); // Overloaded < operator. // bool operator<( Transaction const &other ); // Member functions to get values. // std::string get_symbol() const; unsigned int get_day() const; unsigned int get_month() const; unsigned int get_year() const; unsigned int get_shares() const; double get_amount() const; double get_acb() const; double get_acb_per_share() const; unsigned int get_share_balance() const; double get_cgl() const; bool get_trans_type() const; unsigned int get_trans_id() const; Transaction *get_next(); // Member functions to set values. // void set_acb( double acb_value ); void set_acb_per_share( double acb_share_value ); void set_share_balance( unsigned int bal ); void set_cgl( double value ); void set_next( Transaction *p_new_next ); // Print the transaction. // void print(); private: std::string symbol; unsigned int day; unsigned int month; unsigned int year; std::string trans_type; unsigned int shares; double amount; unsigned int trans_id; // These private members have to be populated. double acb; double acb_per_share; unsigned int share_balance; double cgl; Transaction *p_next; // A unique identifier class variable to assign identifiers (trans_id). // static unsigned int assigned_trans_id; }; #endif
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2020 The PIVX developers // Copyright (c) 2020 The CryptoDev developers // Copyright (c) 2020 The peony developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script.h" #include "tinyformat.h" #include "utilstrencodings.h" namespace { inline std::string ValueString(const std::vector<unsigned char>& vch) { if (vch.size() <= 4) return strprintf("%d", CScriptNum(vch, false).getint()); else return HexStr(vch); } } // anon namespace const char* GetOpName(opcodetype opcode) { switch (opcode) { // push value case OP_0 : return "0"; case OP_PUSHDATA1 : return "OP_PUSHDATA1"; case OP_PUSHDATA2 : return "OP_PUSHDATA2"; case OP_PUSHDATA4 : return "OP_PUSHDATA4"; case OP_1NEGATE : return "-1"; case OP_RESERVED : return "OP_RESERVED"; case OP_1 : return "1"; case OP_2 : return "2"; case OP_3 : return "3"; case OP_4 : return "4"; case OP_5 : return "5"; case OP_6 : return "6"; case OP_7 : return "7"; case OP_8 : return "8"; case OP_9 : return "9"; case OP_10 : return "10"; case OP_11 : return "11"; case OP_12 : return "12"; case OP_13 : return "13"; case OP_14 : return "14"; case OP_15 : return "15"; case OP_16 : return "16"; // control case OP_NOP : return "OP_NOP"; case OP_VER : return "OP_VER"; case OP_IF : return "OP_IF"; case OP_NOTIF : return "OP_NOTIF"; case OP_VERIF : return "OP_VERIF"; case OP_VERNOTIF : return "OP_VERNOTIF"; case OP_ELSE : return "OP_ELSE"; case OP_ENDIF : return "OP_ENDIF"; case OP_VERIFY : return "OP_VERIFY"; case OP_RETURN : return "OP_RETURN"; // stack ops case OP_TOALTSTACK : return "OP_TOALTSTACK"; case OP_FROMALTSTACK : return "OP_FROMALTSTACK"; case OP_2DROP : return "OP_2DROP"; case OP_2DUP : return "OP_2DUP"; case OP_3DUP : return "OP_3DUP"; case OP_2OVER : return "OP_2OVER"; case OP_2ROT : return "OP_2ROT"; case OP_2SWAP : return "OP_2SWAP"; case OP_IFDUP : return "OP_IFDUP"; case OP_DEPTH : return "OP_DEPTH"; case OP_DROP : return "OP_DROP"; case OP_DUP : return "OP_DUP"; case OP_NIP : return "OP_NIP"; case OP_OVER : return "OP_OVER"; case OP_PICK : return "OP_PICK"; case OP_ROLL : return "OP_ROLL"; case OP_ROT : return "OP_ROT"; case OP_SWAP : return "OP_SWAP"; case OP_TUCK : return "OP_TUCK"; // splice ops case OP_CAT : return "OP_CAT"; case OP_SUBSTR : return "OP_SUBSTR"; case OP_LEFT : return "OP_LEFT"; case OP_RIGHT : return "OP_RIGHT"; case OP_SIZE : return "OP_SIZE"; // bit logic case OP_INVERT : return "OP_INVERT"; case OP_AND : return "OP_AND"; case OP_OR : return "OP_OR"; case OP_XOR : return "OP_XOR"; case OP_EQUAL : return "OP_EQUAL"; case OP_EQUALVERIFY : return "OP_EQUALVERIFY"; case OP_RESERVED1 : return "OP_RESERVED1"; case OP_RESERVED2 : return "OP_RESERVED2"; // numeric case OP_1ADD : return "OP_1ADD"; case OP_1SUB : return "OP_1SUB"; case OP_2MUL : return "OP_2MUL"; case OP_2DIV : return "OP_2DIV"; case OP_NEGATE : return "OP_NEGATE"; case OP_ABS : return "OP_ABS"; case OP_NOT : return "OP_NOT"; case OP_0NOTEQUAL : return "OP_0NOTEQUAL"; case OP_ADD : return "OP_ADD"; case OP_SUB : return "OP_SUB"; case OP_MUL : return "OP_MUL"; case OP_DIV : return "OP_DIV"; case OP_MOD : return "OP_MOD"; case OP_LSHIFT : return "OP_LSHIFT"; case OP_RSHIFT : return "OP_RSHIFT"; case OP_BOOLAND : return "OP_BOOLAND"; case OP_BOOLOR : return "OP_BOOLOR"; case OP_NUMEQUAL : return "OP_NUMEQUAL"; case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY"; case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL"; case OP_LESSTHAN : return "OP_LESSTHAN"; case OP_GREATERTHAN : return "OP_GREATERTHAN"; case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL"; case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL"; case OP_MIN : return "OP_MIN"; case OP_MAX : return "OP_MAX"; case OP_WITHIN : return "OP_WITHIN"; // crypto case OP_RIPEMD160 : return "OP_RIPEMD160"; case OP_SHA1 : return "OP_SHA1"; case OP_SHA256 : return "OP_SHA256"; case OP_HASH160 : return "OP_HASH160"; case OP_HASH256 : return "OP_HASH256"; case OP_CODESEPARATOR : return "OP_CODESEPARATOR"; case OP_CHECKSIG : return "OP_CHECKSIG"; case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY"; case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG"; case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY"; // expansion case OP_NOP1 : return "OP_NOP1"; // OP_NOP1 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY"; // OP_NOP2 case OP_NOP3 : return "OP_NOP3"; // OP_NOP3 case OP_NOP4 : return "OP_NOP4"; // OP_NOP4 case OP_NOP5 : return "OP_NOP5"; // OP_NOP5 case OP_NOP6 : return "OP_NOP6"; // OP_NOP6 case OP_NOP7 : return "OP_NOP7"; // OP_NOP7 case OP_NOP8 : return "OP_NOP8"; // OP_NOP8 case OP_NOP9 : return "OP_NOP9"; // OP_NOP9 case OP_NOP10 : return "OP_NOP10"; // OP_NOP10 // zerocoin case OP_ZEROCOINMINT : return "OP_ZEROCOINMINT"; case OP_ZEROCOINSPEND : return "OP_ZEROCOINSPEND"; case OP_ZEROCOINPUBLICSPEND : return "OP_ZEROCOINPUBLICSPEND"; // cold staking case OP_CHECKCOLDSTAKEVERIFY : return "OP_CHECKCOLDSTAKEVERIFY"; case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE"; // Note: // The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum // as kind of implementation hack, they are *NOT* real opcodes. If found in real // Script, just let the default: case deal with them. default: return "OP_UNKNOWN"; } } unsigned int CScript::GetSigOpCount(bool fAccurate) const { unsigned int n = 0; const_iterator pc = begin(); opcodetype lastOpcode = OP_INVALIDOPCODE; while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) break; if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY) n++; else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY) { if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16) n += DecodeOP_N(lastOpcode); else n += 20; } lastOpcode = opcode; } return n; } unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const { if (!IsPayToScriptHash()) return GetSigOpCount(true); // This is a pay-to-script-hash scriptPubKey; // get the last item that the scriptSig // pushes onto the stack: const_iterator pc = scriptSig.begin(); std::vector<unsigned char> data; while (pc < scriptSig.end()) { opcodetype opcode; if (!scriptSig.GetOp(pc, opcode, data)) return 0; if (opcode > OP_16) return 0; } /// ... and return its opcount: CScript subscript(data.begin(), data.end()); return subscript.GetSigOpCount(true); } bool CScript::IsNormalPaymentScript() const { if(this->size() != 25) return false; std::string str; opcodetype opcode; const_iterator pc = begin(); int i = 0; while (pc < end()) { GetOp(pc, opcode); if( i == 0 && opcode != OP_DUP) return false; else if(i == 1 && opcode != OP_HASH160) return false; else if(i == 3 && opcode != OP_EQUALVERIFY) return false; else if(i == 4 && opcode != OP_CHECKSIG) return false; else if(i == 5) return false; i++; } return true; } bool CScript::IsPayToScriptHash() const { // Extra-fast test for pay-to-script-hash CScripts: return (this->size() == 23 && this->at(0) == OP_HASH160 && this->at(1) == 0x14 && this->at(22) == OP_EQUAL); } bool CScript::IsPayToColdStaking() const { // Extra-fast test for pay-to-cold-staking CScripts: return (this->size() == 51 && this->at(2) == OP_ROT && this->at(4) == OP_CHECKCOLDSTAKEVERIFY && this->at(5) == 0x14 && this->at(27) == 0x14 && this->at(49) == OP_EQUALVERIFY && this->at(50) == OP_CHECKSIG); } bool CScript::StartsWithOpcode(const opcodetype opcode) const { return (!this->empty() && this->at(0) == opcode); } bool CScript::IsZerocoinMint() const { return StartsWithOpcode(OP_ZEROCOINMINT); } bool CScript::IsZerocoinSpend() const { return StartsWithOpcode(OP_ZEROCOINSPEND); } bool CScript::IsZerocoinPublicSpend() const { return StartsWithOpcode(OP_ZEROCOINPUBLICSPEND); } bool CScript::IsPushOnly(const_iterator pc) const { while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) return false; // Note that IsPushOnly() *does* consider OP_RESERVED to be a // push-type opcode, however execution of OP_RESERVED fails, so // it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to // the P2SH special validation code being executed. if (opcode > OP_16) return false; } return true; } bool CScript::IsPushOnly() const { return this->IsPushOnly(begin()); } std::string CScript::ToString() const { std::string str; opcodetype opcode; std::vector<unsigned char> vch; const_iterator pc = begin(); while (pc < end()) { if (!str.empty()) str += " "; if (!GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { str += ValueString(vch); } else { str += GetOpName(opcode); if (opcode == OP_ZEROCOINSPEND) { //Zerocoinspend has no further op codes. break; } } } return str; }
#ifndef SRC_TESTS_TEST_OLARANK_CPP_ #define SRC_TESTS_TEST_OLARANK_CPP_ #include <cmath> #include <vector> #include <glog/logging.h> #include "TestOLaRank.h" #include "../arma/arma_supportData.h" bool isEqual(const arma::mat &m1, const cv::Mat &m2) { int rows = m1.n_rows; int cols = m1.n_cols; int cv_rows = m2.rows; int cv_cols = m2.cols; if (rows != cv_rows) return false; if (cols != cv_cols) return false; const double precision = 0.0001; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (abs(m1(i, j) - m2.at<double>(i, j)) > precision) { return false; } } } return true; } cv::Mat convertMatToCV(const arma::mat &m1) { cv::Mat c = cv::Mat::zeros(m1.n_rows, m1.n_cols, CV_64F); int count = 0; for (int i = 0; i < m1.n_rows; i++) { for (int j = 0; j < m1.n_cols; j++) { c.at<double>(i, j) = m1(i, j); } } return c; } arma::mat convertCVToMat(const cv::Mat &m1) { arma::mat c = arma::zeros(m1.rows, m1.cols); uchar depth = m1.type() & CV_MAT_DEPTH_MASK; CHECK(depth == CV_64F); for (int i = 0; i < m1.rows; i++) { for (int j = 0; j < m1.cols; j++) { c(i, j) = m1.at<double>(i, j); } } return c; } bool TestOLaRank::isSupportVectorEqual(supportData *s, armadillo::supportData *arma_s) { bool equal = true; if (!(isEqual(*arma_s->x, s->x))) equal = false; if (!(isEqual(*arma_s->y, s->y))) equal = false; if (!(isEqual(*arma_s->beta, s->beta))) equal = false; if (!(isEqual(*arma_s->grad, s->grad))) equal = false; if (arma_s->label != s->label) equal = false; if (arma_s->frameNumber != s->frameNumber) equal = false; return equal; } bool TestOLaRank::isSetOLaRankSetS_equal() { int num = olarank->S.size(); int arma_num = arma_olarank->S.size(); if (num != arma_num) return false; for (int i = 0; i < num; i++) { if (!isSupportVectorEqual(olarank->S[i], arma_olarank->S[i])) return false; } return true; } std::vector<cv::Rect> TestOLaRank::getLocations(const cv::Mat &image, int boxes) { int r = image.rows; int c = image.cols; CHECK_GT(boxes, 0); int count = 0; std::vector<cv::Rect> locations; while (count < boxes) { cv::Mat cvbox = draw->getRandomBoundingBox(r, c); cv::Rect box(cvbox.at<double>(0, 1), cvbox.at<double>(0, 2), cvbox.at<double>(0, 3), cvbox.at<double>(0, 4)); locations.push_back(box); count++; } return locations; } void TestOLaRank::performProcessNewAndSMOAndbudget() { boost::tuple<cv::Mat, cv::Mat, int, int> processNewData = this->prepareForProcessNew(); cv::Mat newX = boost::get<0>(processNewData); cv::Mat y_hat = boost::get<1>(processNewData); int label = boost::get<2>(processNewData); int frameNumber = boost::get<3>(processNewData); arma::mat arma_newX = convertCVToMat(newX); arma::mat arma_y_hat = convertCVToMat(y_hat); boost::tuple<cv::Mat, cv::Mat, cv::Mat> p_new = this->olarank->processNew(newX, y_hat, label, frameNumber); boost::tuple<arma::mat, arma::mat, arma::mat> arma_p_new = this->arma_olarank->processNew(arma_newX, arma_y_hat, label, frameNumber); cv::Mat y_plus, y_neg; cv::Mat grad = cv::Mat::zeros(1, newX.rows, CV_64F); boost::tie(y_plus, y_neg, grad) = p_new; // add new element into set S supportData *support = new supportData(newX, y_hat, label, 0, newX.rows, frameNumber); (support->grad) = grad; // delete support; double i = this->olarank->S.size(); this->olarank->S.push_back(support); arma::mat mat_y_plus, mat_y_neg; arma::mat mat_grad(1, arma_newX.n_rows, arma::fill::zeros); boost::tie(mat_y_plus, mat_y_neg, mat_grad) = arma_p_new; // add new element into set S armadillo::supportData *arma_support = new armadillo::supportData( arma_newX, arma_y_hat, label, arma_newX.size(), newX.rows, frameNumber); (*arma_support->grad) = mat_grad; this->arma_olarank->S.push_back(arma_support); assert(isSetOLaRankSetS_equal()); this->olarank->smoStep(i, y_plus, y_neg); this->arma_olarank->smoStep(i, mat_y_plus, mat_y_neg); assert(isSetOLaRankSetS_equal()); this->olarank->budgetMaintance(); this->arma_olarank->budgetMaintance(); assert(isSetOLaRankSetS_equal()); } TEST_F(TestOLaRank, testProcessOld) { this->performProcessNewAndSMOAndbudget(); double i; cv::Mat y_plus, y_neg; boost::tuple<double, cv::Mat, cv::Mat> p_old = this->olarank->processOld(); boost::tie(i, y_plus, y_neg) = p_old; arma::mat arma_y_plus, arma_y_neg; boost::tuple<double, arma::mat, arma::mat> arma_p_old = this->arma_olarank->processOld(); boost::tie(i, arma_y_plus, arma_y_neg) = arma_p_old; assert(isSetOLaRankSetS_equal()); this->olarank->smoStep(i, y_plus, y_neg); this->arma_olarank->smoStep(i, arma_y_plus, arma_y_neg); assert(isSetOLaRankSetS_equal()); this->olarank->budgetMaintance(); this->arma_olarank->budgetMaintance(); assert(isSetOLaRankSetS_equal()); } TEST_F(TestOLaRank, testOptimize) { this->performProcessNewAndSMOAndbudget(); double i; cv::Mat y_plus, y_neg; boost::tuple<double, cv::Mat, cv::Mat> p_old = this->olarank->processOld(); boost::tie(i, y_plus, y_neg) = p_old; arma::mat arma_y_plus, arma_y_neg; boost::tuple<double, arma::mat, arma::mat> arma_p_old = this->arma_olarank->processOld(); double arma_i; boost::tie(arma_i, arma_y_plus, arma_y_neg) = arma_p_old; assert(isSetOLaRankSetS_equal()); this->olarank->smoStep(i, y_plus, y_neg); this->arma_olarank->smoStep(i, arma_y_plus, arma_y_neg); assert(isSetOLaRankSetS_equal()); this->olarank->budgetMaintance(); this->arma_olarank->budgetMaintance(); assert(isSetOLaRankSetS_equal()); boost::tuple<double, cv::Mat, cv::Mat> optimize = this->olarank->optimize(); boost::tie(i, y_plus, y_neg) = optimize; boost::tuple<double, arma::mat, arma::mat> arma_optimize = this->arma_olarank->optimize(); boost::tie(arma_i, arma_y_plus, arma_y_neg) = arma_optimize; assert(i == arma_i); assert(isEqual(arma_y_plus, y_plus)); assert(isEqual(arma_y_neg, y_neg)); assert(isSetOLaRankSetS_equal()); this->olarank->smoStep(i, y_plus, y_neg); this->arma_olarank->smoStep(arma_i, arma_y_plus, arma_y_neg); assert(isSetOLaRankSetS_equal()); } boost::tuple<cv::Mat, cv::Mat, int, int> TestOLaRank::prepareForProcessNew(int boxes) { cv::Mat image = draw->getRandomImage(); std::vector<cv::Rect> locations = this->getLocations(image, boxes); cv::Mat processedImage = this->feature->prepareImage(&image); cv::Mat x = this->feature->calculateFeature(processedImage, locations); cv::Mat y = this->feature->reshapeYs(locations); arma::mat arma_x = convertCVToMat(x); arma::mat arma_y = convertCVToMat(y); int m = this->feature->calculateFeatureDimension(); int label = 0; int frameNumber = 0; supportData *s1 = new supportData(x, y, label, m, x.rows, frameNumber); armadillo::supportData *arma_s1 = new armadillo::supportData( arma_x, arma_y, label, m, x.rows, frameNumber); this->olarank->S.push_back(s1); this->arma_olarank->S.push_back(arma_s1); boost::tuple<cv::Mat, cv::Mat, int, int> result = boost::make_tuple(x, y, label, frameNumber); return result; } TEST_F(TestOLaRank, smoStep) { boost::tuple<cv::Mat, cv::Mat, int, int> processNewData = this->prepareForProcessNew(); cv::Mat newX = boost::get<0>(processNewData); cv::Mat y_hat = boost::get<1>(processNewData); int label = boost::get<2>(processNewData); int frameNumber = boost::get<3>(processNewData); arma::mat arma_newX = convertCVToMat(newX); arma::mat arma_y_hat = convertCVToMat(y_hat); boost::tuple<cv::Mat, cv::Mat, cv::Mat> p_new = this->olarank->processNew(newX, y_hat, label, frameNumber); boost::tuple<arma::mat, arma::mat, arma::mat> arma_p_new = this->arma_olarank->processNew(arma_newX, arma_y_hat, label, frameNumber); cv::Mat y_plus, y_neg; cv::Mat grad = cv::Mat::zeros(1, newX.rows, CV_64F); boost::tie(y_plus, y_neg, grad) = p_new; // add new element into set S supportData *support = new supportData(newX, y_hat, label, 0, newX.rows, frameNumber); (support->grad) = grad; // delete support; double i = this->olarank->S.size(); this->olarank->S.push_back(support); arma::mat mat_y_plus, mat_y_neg; arma::mat mat_grad(1, arma_newX.n_rows, arma::fill::zeros); boost::tie(mat_y_plus, mat_y_neg, mat_grad) = arma_p_new; // add new element into set S armadillo::supportData *arma_support = new armadillo::supportData( arma_newX, arma_y_hat, label, arma_newX.size(), newX.rows, frameNumber); (*arma_support->grad) = mat_grad; this->arma_olarank->S.push_back(arma_support); assert(isSetOLaRankSetS_equal()); this->olarank->smoStep(i, y_plus, y_neg); this->arma_olarank->smoStep(i, mat_y_plus, mat_y_neg); assert(isSetOLaRankSetS_equal()); this->olarank->budgetMaintance(); this->arma_olarank->budgetMaintance(); assert(isSetOLaRankSetS_equal()); } TEST_F(TestOLaRank, processNew) { boost::tuple<cv::Mat, cv::Mat, int, int> processNewData = this->prepareForProcessNew(); cv::Mat x = boost::get<0>(processNewData); cv::Mat y = boost::get<1>(processNewData); int label = boost::get<2>(processNewData); int frameNumber = boost::get<3>(processNewData); arma::mat arma_x = convertCVToMat(x); arma::mat arma_y = convertCVToMat(y); boost::tuple<cv::Mat, cv::Mat, cv::Mat> processNewOutput = this->olarank->processNew(x, y, label, frameNumber); boost::tuple<arma::mat, arma::mat, arma::mat> arma_processNewOutput = this->arma_olarank->processNew(arma_x, arma_y, label, frameNumber); cv::Mat r_1 = boost::get<0>(processNewOutput); cv::Mat r_2 = boost::get<1>(processNewOutput); cv::Mat r_3 = boost::get<2>(processNewOutput); arma::mat arma_r_1 = boost::get<0>(arma_processNewOutput); arma::mat arma_r_2 = boost::get<1>(arma_processNewOutput); arma::mat arma_r_3 = boost::get<2>(arma_processNewOutput); assert(isEqual(arma_r_1, r_1)); assert(isEqual(arma_r_2, r_2)); assert(isEqual(arma_r_3, r_3)); } TEST_F(TestOLaRank, calculate_kernel) { cv::Mat cvf1 = draw->getRandomFloatMatrix(); cv::Mat cvf2 = draw->getRandomFloatMatrix(); arma::mat armaf1 = convertCVToMat(cvf1); arma::mat armaf2 = convertCVToMat(cvf2); int r = draw->window_height; int c = draw->window_width; for (int i = 0; i < r; i++) { for (int j = 0; j < r; j++) { ASSERT_NEAR(olarank->calculate_kernel(cvf1, i, cvf2, j), arma_olarank->calculate_kernel(armaf1, i, armaf2, j), this->PRECISION); } } } TEST_F(TestOLaRank, kernel_fast) { cv::Mat cvf1 = draw->getRandomFloatMatrix(); cv::Mat cvf2 = draw->getRandomFloatMatrix(); arma::mat armaf1 = convertCVToMat(cvf1); arma::mat armaf2 = convertCVToMat(cvf2); int r = draw->window_height; int c = draw->window_width; cv::Mat cvBox1 = draw->getRandomBoundingBox(r, c); cv::Mat cvBox2 = draw->getRandomBoundingBox(r, c); CHECK(cvBox1.at<double>(0, 1) + cvBox1.at<double>(0, 3) < r); CHECK(cvBox1.at<double>(0, 2) + cvBox1.at<double>(0, 4) < c); CHECK(cvBox2.at<double>(0, 1) + cvBox2.at<double>(0, 3) < r); CHECK(cvBox2.at<double>(0, 2) + cvBox2.at<double>(0, 4) < c); arma::mat armaBox1 = convertCVToMat(cvBox1); arma::mat armaBox2 = convertCVToMat(cvBox2); for (int i = 0; i < r; i++) { for (int j = 0; j < r; j++) { // The implementation is not using cvBox1, cvBox2, armaBox1, // armaBox2 arugments ASSERT_NEAR( olarank->kernel_fast(cvf1, cvBox1, i, -1, cvf2, cvBox2, j, -2), arma_olarank->kernel_fast(armaf1, armaBox1, i, -1, armaf2, armaBox2, j, -2), this->PRECISION); } } } TEST_F(TestOLaRank, matToCVConversion) { cv::Mat image = draw->getRandomFloatMatrix(); arma::mat m = convertCVToMat(image); cv::Mat image_back = convertMatToCV(m); assert(true == isEqual(m, image_back)); } TEST_F(TestOLaRank, loss) { cv::Mat cv_y = cv::Mat::zeros(1, 5, CV_64F); cv::Mat cv_yhat = cv::Mat::zeros(1, 5, CV_64F); arma::mat arma_y = arma::zeros(1, 5); arma::mat arma_yhat = arma::zeros(1, 5); cv_y.at<double>(0, 1) = 5; cv_y.at<double>(0, 2) = 10; cv_y.at<double>(0, 3) = 3; cv_y.at<double>(0, 4) = 7; arma_y(0, 1) = 5; arma_y(0, 2) = 10; arma_y(0, 3) = 3; arma_y(0, 4) = 7; cv_yhat.at<double>(0, 1) = 7; cv_yhat.at<double>(0, 2) = 9; cv_yhat.at<double>(0, 3) = 6; cv_yhat.at<double>(0, 4) = 4; arma_yhat(0, 1) = 7; arma_yhat(0, 2) = 9; arma_yhat(0, 3) = 6; arma_yhat(0, 4) = 4; ASSERT_NE(0, olarank->loss(cv_y, cv_yhat)); ASSERT_NEAR(olarank->loss(cv_y, cv_yhat), arma_olarank->loss(arma_y, arma_yhat), PRECISION); ASSERT_NEAR(olarank->loss(cv_yhat, cv_y), arma_olarank->loss(arma_yhat, arma_y), PRECISION); } #endif
//===--- SILFunctionType.cpp - Giving SIL types to AST functions ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the native Swift ownership transfer conventions // and works in concert with the importer to give the correct // conventions to imported functions and types. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "libsil" #include "swift/AST/AnyFunctionRef.h" #include "swift/AST/Decl.h" #include "swift/AST/DiagnosticsSIL.h" #include "swift/AST/ForeignInfo.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/Module.h" #include "swift/AST/ProtocolConformance.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "clang/AST/Attr.h" #include "clang/AST/DeclObjC.h" #include "clang/Analysis/DomainSpecific/CocoaConventions.h" #include "clang/Basic/CharInfo.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SaveAndRestore.h" using namespace swift; using namespace swift::Lowering; SILType SILFunctionType::getDirectFormalResultsType() { CanType type; if (getNumDirectFormalResults() == 0) { type = getASTContext().TheEmptyTupleType; } else if (getNumDirectFormalResults() == 1) { type = getSingleDirectFormalResult().getType(); } else { auto &cache = getMutableFormalResultsCache(); if (cache) { type = cache; } else { SmallVector<TupleTypeElt, 4> elts; for (auto result : getResults()) if (!result.isFormalIndirect()) elts.push_back(result.getType()); type = CanType(TupleType::get(elts, getASTContext())); cache = type; } } return SILType::getPrimitiveObjectType(type); } SILType SILFunctionType::getAllResultsType() { CanType type; if (getNumResults() == 0) { type = getASTContext().TheEmptyTupleType; } else if (getNumResults() == 1) { type = getResults()[0].getType(); } else { auto &cache = getMutableAllResultsCache(); if (cache) { type = cache; } else { SmallVector<TupleTypeElt, 4> elts; for (auto result : getResults()) elts.push_back(result.getType()); type = CanType(TupleType::get(elts, getASTContext())); cache = type; } } return SILType::getPrimitiveObjectType(type); } SILType SILFunctionType::getFormalCSemanticResult() { assert(getLanguage() == SILFunctionLanguage::C); assert(getNumResults() <= 1); return getDirectFormalResultsType(); } CanType SILFunctionType::getSelfInstanceType() const { auto selfTy = getSelfParameter().getType(); // If this is a static method, get the instance type. if (auto metaTy = dyn_cast<AnyMetatypeType>(selfTy)) return metaTy.getInstanceType(); return selfTy; } ProtocolDecl * SILFunctionType::getDefaultWitnessMethodProtocol() const { assert(getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod); auto selfTy = getSelfInstanceType(); if (auto paramTy = dyn_cast<GenericTypeParamType>(selfTy)) { assert(paramTy->getDepth() == 0 && paramTy->getIndex() == 0); auto superclass = GenericSig->getSuperclassBound(paramTy); if (superclass) return nullptr; auto protos = GenericSig->getConformsTo(paramTy); assert(protos.size() == 1); return protos[0]; } return nullptr; } ClassDecl * SILFunctionType::getWitnessMethodClass(ModuleDecl &M) const { auto selfTy = getSelfInstanceType(); auto genericSig = getGenericSignature(); if (auto paramTy = dyn_cast<GenericTypeParamType>(selfTy)) { assert(paramTy->getDepth() == 0 && paramTy->getIndex() == 0); auto superclass = genericSig->getSuperclassBound(paramTy); if (superclass) return superclass->getClassOrBoundGenericClass(); } return nullptr; } static CanType getKnownType(Optional<CanType> &cacheSlot, ASTContext &C, StringRef moduleName, StringRef typeName) { if (!cacheSlot) { cacheSlot = ([&] { ModuleDecl *mod = C.getLoadedModule(C.getIdentifier(moduleName)); if (!mod) return CanType(); // Do a general qualified lookup instead of a direct lookupValue because // some of the types we want are reexported through overlays and // lookupValue would only give us types actually declared in the overlays // themselves. SmallVector<ValueDecl *, 2> decls; mod->lookupQualified(ModuleType::get(mod), C.getIdentifier(typeName), NL_QualifiedDefault | NL_KnownNonCascadingDependency, /*typeResolver=*/nullptr, decls); if (decls.size() != 1) return CanType(); const auto *typeDecl = dyn_cast<TypeDecl>(decls.front()); if (!typeDecl) return CanType(); assert(typeDecl->hasInterfaceType() && "bridged type must be type-checked"); return typeDecl->getDeclaredInterfaceType()->getCanonicalType(); })(); } CanType t = *cacheSlot; // It is possible that we won't find a bridging type (e.g. String) when we're // parsing the stdlib itself. if (t) { DEBUG(llvm::dbgs() << "Bridging type " << moduleName << '.' << typeName << " mapped to "; if (t) t->print(llvm::dbgs()); else llvm::dbgs() << "<null>"; llvm::dbgs() << '\n'); } return t; } #define BRIDGING_KNOWN_TYPE(BridgedModule,BridgedType) \ CanType TypeConverter::get##BridgedType##Type() { \ return getKnownType(BridgedType##Ty, M.getASTContext(), \ #BridgedModule, #BridgedType); \ } #include "swift/SIL/BridgedTypes.def" /// Adjust a function type to have a slightly different type. CanAnyFunctionType Lowering::adjustFunctionType(CanAnyFunctionType t, AnyFunctionType::ExtInfo extInfo) { if (t->getExtInfo() == extInfo) return t; return CanAnyFunctionType(t->withExtInfo(extInfo)); } /// Adjust a function type to have a slightly different type. CanSILFunctionType Lowering::adjustFunctionType( CanSILFunctionType type, SILFunctionType::ExtInfo extInfo, ParameterConvention callee, Optional<ProtocolConformanceRef> witnessMethodConformance) { if (type->getExtInfo() == extInfo && type->getCalleeConvention() == callee && type->getWitnessMethodConformanceOrNone() == witnessMethodConformance) return type; return SILFunctionType::get(type->getGenericSignature(), extInfo, type->getCoroutineKind(), callee, type->getParameters(), type->getYields(), type->getResults(), type->getOptionalErrorResult(), type->getASTContext(), witnessMethodConformance); } CanSILFunctionType SILFunctionType::getWithRepresentation(Representation repr) { return getWithExtInfo(getExtInfo().withRepresentation(repr)); } CanSILFunctionType SILFunctionType::getWithExtInfo(ExtInfo newExt) { auto oldExt = getExtInfo(); if (newExt == oldExt) return CanSILFunctionType(this); auto calleeConvention = (newExt.hasContext() ? (oldExt.hasContext() ? getCalleeConvention() : Lowering::DefaultThickCalleeConvention) : ParameterConvention::Direct_Unowned); return get(getGenericSignature(), newExt, getCoroutineKind(), calleeConvention, getParameters(), getYields(), getResults(), getOptionalErrorResult(), getASTContext(), getWitnessMethodConformanceOrNone()); } namespace { enum class ConventionsKind : uint8_t { Default = 0, DefaultBlock = 1, ObjCMethod = 2, CFunctionType = 3, CFunction = 4, SelectorFamily = 5, Deallocator = 6, Capture = 7, }; class Conventions { ConventionsKind kind; protected: virtual ~Conventions() = default; public: Conventions(ConventionsKind k) : kind(k) {} ConventionsKind getKind() const { return kind; } virtual ParameterConvention getIndirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const = 0; virtual ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const = 0; virtual ParameterConvention getCallee() const = 0; virtual ResultConvention getResult(const TypeLowering &resultTL) const = 0; virtual ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const = 0; virtual ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const = 0; // Helpers that branch based on a value ownership. ParameterConvention getIndirect(ValueOwnership ownership, bool forSelf, unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const { switch (ownership) { case ValueOwnership::Default: if (forSelf) return getIndirectSelfParameter(type); return getIndirectParameter(index, type, substTL); case ValueOwnership::InOut: return ParameterConvention::Indirect_Inout; case ValueOwnership::Shared: return ParameterConvention::Indirect_In_Guaranteed; case ValueOwnership::Owned: return ParameterConvention::Indirect_In; } } ParameterConvention getDirect(ValueOwnership ownership, bool forSelf, unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const { switch (ownership) { case ValueOwnership::Default: if (forSelf) return getDirectSelfParameter(type); return getDirectParameter(index, type, substTL); case ValueOwnership::InOut: return ParameterConvention::Indirect_Inout; case ValueOwnership::Shared: return ParameterConvention::Direct_Guaranteed; case ValueOwnership::Owned: return ParameterConvention::Direct_Owned; } } }; /// A visitor for breaking down formal result types into a SILResultInfo /// and possibly some number of indirect-out SILParameterInfos, /// matching the abstraction patterns of the original type. class DestructureResults { SILModule &M; const Conventions &Convs; SmallVectorImpl<SILResultInfo> &Results; public: DestructureResults(SILModule &M, const Conventions &conventions, SmallVectorImpl<SILResultInfo> &results) : M(M), Convs(conventions), Results(results) {} void destructure(AbstractionPattern origType, CanType substType) { // Recurse into tuples. if (origType.isTuple()) { auto substTupleType = cast<TupleType>(substType); for (auto eltIndex : indices(substTupleType.getElementTypes())) { AbstractionPattern origEltType = origType.getTupleElementType(eltIndex); CanType substEltType = substTupleType.getElementType(eltIndex); destructure(origEltType, substEltType); } return; } auto &substResultTL = M.Types.getTypeLowering(origType, substType); // Determine the result convention. ResultConvention convention; if (isFormallyReturnedIndirectly(origType, substType, substResultTL)) { convention = ResultConvention::Indirect; } else { convention = Convs.getResult(substResultTL); // Reduce conventions for trivial types to an unowned convention. if (substResultTL.isTrivial()) { switch (convention) { case ResultConvention::Indirect: case ResultConvention::Unowned: case ResultConvention::UnownedInnerPointer: // Leave these as-is. break; case ResultConvention::Autoreleased: case ResultConvention::Owned: // These aren't distinguishable from unowned for trivial types. convention = ResultConvention::Unowned; break; } } } SILResultInfo result(substResultTL.getLoweredType().getASTType(), convention); Results.push_back(result); } /// Query whether the original type is returned indirectly for the purpose /// of reabstraction given complete lowering information about its /// substitution. bool isFormallyReturnedIndirectly(AbstractionPattern origType, CanType substType, const TypeLowering &substTL) { // If the substituted type is returned indirectly, so must the // unsubstituted type. if ((origType.isTypeParameter() && !origType.isConcreteType() && !origType.requiresClass()) || substTL.isAddressOnly()) { return true; // If the substitution didn't change the type, then a negative // response to the above is determinative as well. } else if (origType.getType() == substType && !origType.getType()->hasTypeParameter()) { return false; // Otherwise, query specifically for the original type. } else { // FIXME: Get expansion from SILDeclRef return SILType::isFormallyReturnedIndirectly( origType.getType(), M, origType.getGenericSignature(), ResilienceExpansion::Minimal); } } }; /// A visitor for turning formal input types into SILParameterInfos, /// matching the abstraction patterns of the original type. /// /// If the original abstraction pattern is fully opaque, we must /// pass the function's inputs as if the original type were the most /// general function signature (expressed entirely in type /// variables) which can be substituted to equal the given /// signature. /// /// The goal of the most general type is to be (1) unambiguous to /// compute from the substituted type and (2) the same for every /// possible generalization of that type. For example, suppose we /// have a Vector<(Int,Int)->Bool>. Obviously, we would prefer to /// store optimal function pointers directly in this array; and if /// all uses of it are ungeneralized, we'd get away with that. But /// suppose the vector is passed to a function like this: /// func satisfiesAll<T>(v : Vector<(T,T)->Bool>, x : T, y : T) -> Bool /// That function will expect to be able to pull values out with the /// proper abstraction. The only type we can possibly expect to agree /// upon is the most general form. /// /// The precise way this works is that Vector's subscript operation /// (assuming that's how it's being accessed) has this signature: /// <X> Vector<X> -> Int -> X /// which 'satisfiesAll' is calling with this substitution: /// X := (T, T) -> Bool /// Since 'satisfiesAll' has a function type substituting for an /// unrestricted archetype, it expects the value returned to have the /// most general possible form 'A -> B', which it will need to /// de-generalize (by thunking) if it needs to pass it around as /// a '(T, T) -> Bool' value. /// /// It is only this sort of direct substitution in types that forces /// the most general possible type to be selected; declarations will /// generally provide a target generalization level. For example, /// in a Vector<IntPredicate>, where IntPredicate is a struct (not a /// tuple) with one field of type (Int, Int) -> Bool, all the /// function pointers will be stored ungeneralized. Of course, such /// a vector couldn't be passed to 'satisfiesAll'. /// /// For most types, the most general type is simply a fresh, /// unrestricted type variable. But unmaterializable types are not /// valid results of substitutions, so this does not apply. The /// most general form of an unmaterializable type preserves the /// basic structure of the unmaterializable components, replacing /// any materializable components with fresh type variables. /// /// That is, if we have a substituted function type: /// (UnicodeScalar, (Int, Float), Double) -> Bool /// then its most general form is /// A -> B /// /// because there is a valid substitution /// A := (UnicodeScalar, (Int, Float), Double) /// B := Bool /// /// But if we have a substituted function type: /// (UnicodeScalar, (Int, Float), inout Double) -> Bool /// then its most general form is /// (A, B, inout C) -> D /// because the substitution /// X := (UnicodeScalar, (Int, Float), inout Double) /// is invalid substitution, ultimately because 'inout Double' /// is not materializable. class DestructureInputs { SILModule &M; const Conventions &Convs; const ForeignInfo &Foreign; Optional<llvm::function_ref<void()>> HandleForeignSelf; SmallVectorImpl<SILParameterInfo> &Inputs; unsigned NextOrigParamIndex = 0; public: DestructureInputs(SILModule &M, const Conventions &conventions, const ForeignInfo &foreign, SmallVectorImpl<SILParameterInfo> &inputs) : M(M), Convs(conventions), Foreign(foreign), Inputs(inputs) {} void destructure(AbstractionPattern origType, CanAnyFunctionType::CanParamArrayRef params, AnyFunctionType::ExtInfo extInfo) { visitTopLevelParams(origType, params, extInfo); } private: bool isClangTypeMoreIndirectThanSubstType(const clang::Type *clangTy, CanType substTy) { // A const pointer argument might have been imported as // UnsafePointer, COpaquePointer, or a CF foreign class. // (An ObjC class type wouldn't be const-qualified.) if (clangTy->isPointerType() && clangTy->getPointeeType().isConstQualified()) { // Peek through optionals. if (auto substObjTy = substTy.getOptionalObjectType()) substTy = substObjTy; // Void pointers aren't usefully indirectable. if (clangTy->isVoidPointerType()) return false; if (auto eltTy = substTy->getAnyPointerElementType()) return isClangTypeMoreIndirectThanSubstType( clangTy->getPointeeType().getTypePtr(), CanType(eltTy)); if (substTy->getAnyNominal() == M.getASTContext().getOpaquePointerDecl()) // TODO: We could conceivably have an indirect opaque ** imported // as COpaquePointer. That shouldn't ever happen today, though, // since we only ever indirect the 'self' parameter of functions // imported as methods. return false; if (clangTy->getPointeeType()->getAs<clang::RecordType>()) { // CF type as foreign class if (substTy->getClassOrBoundGenericClass() && substTy->getClassOrBoundGenericClass()->getForeignClassKind() == ClassDecl::ForeignKind::CFType) { return false; } } // swift_newtypes are always passed directly if (auto typedefTy = clangTy->getAs<clang::TypedefType>()) { if (typedefTy->getDecl()->getAttr<clang::SwiftNewtypeAttr>()) return false; } return true; } return false; } /// Query whether the original type is address-only given complete /// lowering information about its substitution. bool isFormallyPassedIndirectly(AbstractionPattern origType, CanType substType, const TypeLowering &substTL) { // If the C type of the argument is a const pointer, but the Swift type // isn't, treat it as indirect. if (origType.isClangType() && isClangTypeMoreIndirectThanSubstType(origType.getClangType(), substType)) { return true; } // If the substituted type is passed indirectly, so must the // unsubstituted type. if ((origType.isTypeParameter() && !origType.isConcreteType() && !origType.requiresClass()) || substTL.isAddressOnly()) { return true; // If the substitution didn't change the type, then a negative // response to the above is determinative as well. } else if (origType.getType() == substType && !origType.getType()->hasTypeParameter()) { return false; // Otherwise, query specifically for the original type. } else { // FIXME: Get expansion from SILDeclRef return SILType::isFormallyPassedIndirectly( origType.getType(), M, origType.getGenericSignature(), ResilienceExpansion::Minimal); } } /// This is a special entry point that allows destructure inputs to handle /// self correctly. void visitTopLevelParams(AbstractionPattern origType, CanAnyFunctionType::CanParamArrayRef params, AnyFunctionType::ExtInfo extInfo) { unsigned numEltTypes = params.size(); unsigned numNonSelfParams = numEltTypes - 1; auto silRepresentation = extInfo.getSILRepresentation(); // We have to declare this out here so that the lambda scope lasts for // the duration of the loop below. auto handleForeignSelf = [&] { // This is a "self", but it's not a Swift self, we handle it differently. visit(ValueOwnership::Default, /*forSelf=*/false, origType.getTupleElementType(numNonSelfParams), params[numNonSelfParams].getType(), silRepresentation); }; // If we have a foreign-self, install handleSelf as the handler. if (Foreign.Self.isInstance()) { assert(numEltTypes > 0); // This is safe because function_ref just stores a pointer to the // existing lambda object. HandleForeignSelf = handleForeignSelf; } // Add any leading foreign parameters. maybeAddForeignParameters(); // If we have no parameters, even 'self' parameters, bail unless we need // to substitute. if (params.empty()) { if (origType.isTypeParameter()) visit(ValueOwnership::Default, /*forSelf=*/false, origType, M.getASTContext().TheEmptyTupleType, silRepresentation); return; } assert(numEltTypes > 0); auto handleParameter = [&](AbstractionPattern pattern, ParameterTypeFlags paramFlags, CanType ty) { CanTupleType tty = dyn_cast<TupleType>(ty); // If the abstraction pattern is opaque, and the tuple type is // materializable -- if it doesn't contain an l-value type -- then it's // a valid target for substitution and we should not expand it. if (!tty || (pattern.isTypeParameter() && !tty->hasInOutElement())) { visit(paramFlags.getValueOwnership(), /*forSelf=*/false, pattern, ty, silRepresentation); return; } for (auto i : indices(tty.getElementTypes())) { auto patternEltTy = pattern.getTupleElementType(i); auto trueEltTy = tty.getElementType(i); auto flags = tty->getElement(i).getParameterFlags(); visit(flags.getValueOwnership(), /*forSelf=*/false, patternEltTy, trueEltTy, silRepresentation); } }; // If we don't have 'self', we don't need to do anything special. if (!extInfo.hasSelfParam() && !Foreign.Self.isImportAsMember()) { CanType ty = AnyFunctionType::composeInput(M.getASTContext(), params, /*canonicalVararg*/true) ->getCanonicalType(); auto flags = (params.size() == 1) ? params.front().getParameterFlags() : ParameterTypeFlags(); handleParameter(origType, flags, ty); return; } // Okay, handle 'self'. // Process all the non-self parameters. for (unsigned i = 0; i != numNonSelfParams; ++i) { CanType ty = params[i].getType(); AbstractionPattern eltPattern = origType.getTupleElementType(i); auto flags = params[i].getParameterFlags(); handleParameter(eltPattern, flags, ty); } // Process the self parameter. Note that we implicitly drop self // if this is a static foreign-self import. if (!Foreign.Self.isImportAsMember()) { visit(ValueOwnership::Default, /*forSelf=*/true, origType.getTupleElementType(numNonSelfParams), params[numNonSelfParams].getType(), silRepresentation); } // Clear the foreign-self handler for safety. HandleForeignSelf.reset(); } void visit(ValueOwnership ownership, bool forSelf, AbstractionPattern origType, CanType substType, SILFunctionTypeRepresentation rep) { // Tuples get handled specially, in some cases: CanTupleType substTupleTy = dyn_cast<TupleType>(substType); if (substTupleTy && !origType.isTypeParameter()) { assert(origType.getNumTupleElements() == substTupleTy->getNumElements()); switch (ownership) { case ValueOwnership::Default: case ValueOwnership::Owned: // Expand the tuple. for (auto i : indices(substTupleTy.getElementTypes())) { visit(ownership, forSelf, origType.getTupleElementType(i), substTupleTy.getElementType(i), rep); } return; case ValueOwnership::Shared: // Do not lower tuples @guaranteed. This can create conflicts with // substitutions for witness thunks e.g. we take $*(T, T) // @in_guaranteed and try to substitute it for $*T. return visit(ValueOwnership::Default, forSelf, origType, substType, rep); case ValueOwnership::InOut: // handled below break; } } unsigned origParamIndex = NextOrigParamIndex++; bool isInout = false; if (auto inoutType = dyn_cast<InOutType>(substType)) { isInout = true; substType = inoutType.getObjectType(); origType = origType.getWithoutSpecifierType(); } auto &substTL = M.Types.getTypeLowering(origType, substType); ParameterConvention convention; if (isInout) { convention = ParameterConvention::Indirect_Inout; } else if (isFormallyPassedIndirectly(origType, substType, substTL)) { if (forSelf && rep == SILFunctionTypeRepresentation::WitnessMethod) convention = ParameterConvention::Indirect_In_Guaranteed; else convention = Convs.getIndirect(ownership, forSelf, origParamIndex, origType, substTL); assert(isIndirectFormalParameter(convention)); } else if (substTL.isTrivial()) { convention = ParameterConvention::Direct_Unowned; } else { convention = Convs.getDirect(ownership, forSelf, origParamIndex, origType, substTL); assert(!isIndirectFormalParameter(convention)); } auto loweredType = substTL.getLoweredType().getASTType(); Inputs.push_back(SILParameterInfo(loweredType, convention)); maybeAddForeignParameters(); } /// Given that we've just reached an argument index for the /// first time, add any foreign parameters. void maybeAddForeignParameters() { while (maybeAddForeignErrorParameter() || maybeAddForeignSelfParameter()) { // Continue to see, just in case there are more parameters to add. } } bool maybeAddForeignErrorParameter() { if (!Foreign.Error || NextOrigParamIndex != Foreign.Error->getErrorParameterIndex()) return false; auto foreignErrorTy = M.Types.getLoweredType(Foreign.Error->getErrorParameterType()); // Assume the error parameter doesn't have interesting lowering. Inputs.push_back(SILParameterInfo(foreignErrorTy.getASTType(), ParameterConvention::Direct_Unowned)); NextOrigParamIndex++; return true; } bool maybeAddForeignSelfParameter() { if (!Foreign.Self.isInstance() || NextOrigParamIndex != Foreign.Self.getSelfIndex()) return false; (*HandleForeignSelf)(); return true; } }; } // end anonymous namespace static bool isPseudogeneric(SILDeclRef c) { // FIXME: should this be integrated in with the Sema check that prevents // illegal use of type arguments in pseudo-generic method bodies? // The implicitly-generated native initializer thunks for imported // initializers are never pseudo-generic, because they may need // to use their type arguments to bridge their value arguments. if (!c.isForeign && (c.kind == SILDeclRef::Kind::Allocator || c.kind == SILDeclRef::Kind::Initializer) && c.getDecl()->hasClangNode()) return false; // Otherwise, we have to look at the entity's context. DeclContext *dc; if (c.hasDecl()) { dc = c.getDecl()->getDeclContext(); } else if (auto closure = c.getAbstractClosureExpr()) { dc = closure->getParent(); } else { return false; } dc = dc->getInnermostTypeContext(); if (!dc) return false; auto classDecl = dc->getAsClassOrClassExtensionContext(); return (classDecl && classDecl->usesObjCGenericsModel()); } /// Update the result type given the foreign error convention that we will be /// using. static std::pair<AbstractionPattern, CanType> updateResultTypeForForeignError( ForeignErrorConvention convention, CanGenericSignature genericSig, AbstractionPattern origResultType, CanType substFormalResultType) { switch (convention.getKind()) { // These conventions replace the result type. case ForeignErrorConvention::ZeroResult: case ForeignErrorConvention::NonZeroResult: assert(substFormalResultType->isVoid()); substFormalResultType = convention.getResultType(); origResultType = AbstractionPattern(genericSig, substFormalResultType); return {origResultType, substFormalResultType}; // These conventions wrap the result type in a level of optionality. case ForeignErrorConvention::NilResult: assert(!substFormalResultType->getOptionalObjectType()); substFormalResultType = OptionalType::get(substFormalResultType)->getCanonicalType(); origResultType = AbstractionPattern::getOptional(origResultType); return {origResultType, substFormalResultType}; // These conventions don't require changes to the formal error type. case ForeignErrorConvention::ZeroPreservedResult: case ForeignErrorConvention::NonNilError: return {origResultType, substFormalResultType}; } } /// Lower any/all capture context parameters. /// /// *NOTE* Currently default arg generators can not capture anything. /// If we ever add that ability, it will be a different capture list /// from the function to which the argument is attached. static void lowerCaptureContextParameters(SILModule &M, AnyFunctionRef function, CanGenericSignature genericSig, SmallVectorImpl<SILParameterInfo> &inputs) { // NB: The generic signature may be elided from the lowered function type // if the function is in a fully-specialized context, but we still need to // canonicalize references to the generic parameters that may appear in // non-canonical types in that context. We need the original generic // signature from the AST for that. auto origGenericSig = function.getGenericSignature(); auto &Types = M.Types; auto loweredCaptures = Types.getLoweredLocalCaptures(function); for (auto capture : loweredCaptures.getCaptures()) { if (capture.isDynamicSelfMetadata()) { ParameterConvention convention = ParameterConvention::Direct_Unowned; auto dynamicSelfInterfaceType = loweredCaptures.getDynamicSelfType()->mapTypeOutOfContext(); auto selfMetatype = MetatypeType::get(dynamicSelfInterfaceType, MetatypeRepresentation::Thick); auto canSelfMetatype = selfMetatype->getCanonicalType(origGenericSig); SILParameterInfo param(canSelfMetatype, convention); inputs.push_back(param); continue; } auto *VD = capture.getDecl(); auto type = VD->getInterfaceType(); auto canType = type->getCanonicalType(origGenericSig); auto &loweredTL = Types.getTypeLowering(AbstractionPattern(genericSig, canType), canType); auto loweredTy = loweredTL.getLoweredType(); switch (Types.getDeclCaptureKind(capture)) { case CaptureKind::None: break; case CaptureKind::Constant: { // Constants are captured by value. ParameterConvention convention; if (loweredTL.isAddressOnly()) { convention = ParameterConvention::Indirect_In_Guaranteed; } else if (loweredTL.isTrivial()) { convention = ParameterConvention::Direct_Unowned; } else { convention = ParameterConvention::Direct_Guaranteed; } SILParameterInfo param(loweredTy.getASTType(), convention); inputs.push_back(param); break; } case CaptureKind::Box: { // Lvalues are captured as a box that owns the captured value. auto boxTy = Types.getInterfaceBoxTypeForCapture( VD, loweredTy.getASTType(), /*mutable*/ true); auto convention = ParameterConvention::Direct_Guaranteed; auto param = SILParameterInfo(boxTy, convention); inputs.push_back(param); break; } case CaptureKind::StorageAddress: { // Non-escaping lvalues are captured as the address of the value. SILType ty = loweredTy.getAddressType(); auto param = SILParameterInfo(ty.getASTType(), ParameterConvention::Indirect_InoutAliasable); inputs.push_back(param); break; } } } } /// Create the appropriate SIL function type for the given formal type /// and conventions. /// /// The lowering of function types is generally sensitive to the /// declared abstraction pattern. We want to be able to take /// advantage of declared type information in order to, say, pass /// arguments separately and directly; but we also want to be able to /// call functions from generic code without completely embarrassing /// performance. Therefore, different abstraction patterns induce /// different argument-passing conventions, and we must introduce /// implicit reabstracting conversions where necessary to map one /// convention to another. /// /// However, we actually can't reabstract arbitrary thin function /// values while still leaving them thin, at least without costly /// page-mapping tricks. Therefore, the representation must remain /// consistent across all abstraction patterns. /// /// We could reabstract block functions in theory, but (1) we don't /// really need to and (2) doing so would be problematic because /// stuffing something in an Optional currently forces it to be /// reabstracted to the most general type, which means that we'd /// expect the wrong abstraction conventions on bridged block function /// types. /// /// Therefore, we only honor abstraction patterns on thick or /// polymorphic functions. /// /// FIXME: we shouldn't just drop the original abstraction pattern /// when we can't reabstract. Instead, we should introduce /// dynamic-indirect argument-passing conventions and map opaque /// archetypes to that, then respect those conventions in IRGen by /// using runtime call construction. /// /// \param conventions - conventions as expressed for the original type static CanSILFunctionType getSILFunctionType( SILModule &M, AbstractionPattern origType, CanAnyFunctionType substFnInterfaceType, AnyFunctionType::ExtInfo extInfo, const Conventions &conventions, const ForeignInfo &foreignInfo, Optional<SILDeclRef> constant, Optional<ProtocolConformanceRef> witnessMethodConformance) { // Per above, only fully honor opaqueness in the abstraction pattern // for thick or polymorphic functions. We don't need to worry about // non-opaque patterns because the type-checker forbids non-thick // function types from having generic parameters or results. if (origType.isTypeParameter() && substFnInterfaceType->getExtInfo().getSILRepresentation() != SILFunctionType::Representation::Thick && isa<FunctionType>(substFnInterfaceType)) { origType = AbstractionPattern(M.Types.getCurGenericContext(), substFnInterfaceType); } // Find the generic parameters. CanGenericSignature genericSig = substFnInterfaceType.getOptGenericSignature(); // Lower the interface type in a generic context. GenericContextScope scope(M.Types, genericSig); // Map 'throws' to the appropriate error convention. Optional<SILResultInfo> errorResult; assert((!foreignInfo.Error || substFnInterfaceType->getExtInfo().throws()) && "foreignError was set but function type does not throw?"); if (substFnInterfaceType->getExtInfo().throws() && !foreignInfo.Error) { assert(!origType.isForeign() && "using native Swift error convention for foreign type!"); SILType exnType = SILType::getExceptionType(M.getASTContext()); assert(exnType.isObject()); errorResult = SILResultInfo(exnType.getASTType(), ResultConvention::Owned); } // Lower the result type. AbstractionPattern origResultType = origType.getFunctionResultType(); CanType substFormalResultType = substFnInterfaceType.getResult(); // If we have a foreign error convention, restore the original result type. if (auto convention = foreignInfo.Error) { std::tie(origResultType, substFormalResultType) = updateResultTypeForForeignError(*convention, genericSig, origResultType, substFormalResultType); } // Destructure the result tuple type. SmallVector<SILResultInfo, 8> results; { DestructureResults destructurer(M, conventions, results); destructurer.destructure(origResultType, substFormalResultType); } // Destructure the input tuple type. SmallVector<SILParameterInfo, 8> inputs; { DestructureInputs destructurer(M, conventions, foreignInfo, inputs); destructurer.destructure(origType.getFunctionInputType(), substFnInterfaceType.getParams(), extInfo); } // Lower the capture context parameters, if any. // // *NOTE* Currently default arg generators can not capture anything. // If we ever add that ability, it will be a different capture list // from the function to which the argument is attached. if (constant && !constant->isDefaultArgGenerator()) { if (auto function = constant->getAnyFunctionRef()) { lowerCaptureContextParameters(M, *function, genericSig, inputs); } } auto calleeConvention = ParameterConvention::Direct_Unowned; if (extInfo.hasContext()) calleeConvention = conventions.getCallee(); bool pseudogeneric = (constant ? isPseudogeneric(*constant) : false); // NOTE: SILFunctionType::ExtInfo doesn't track everything that // AnyFunctionType::ExtInfo tracks. For example: 'throws' or 'auto-closure' auto silExtInfo = SILFunctionType::ExtInfo() .withRepresentation(extInfo.getSILRepresentation()) .withIsPseudogeneric(pseudogeneric) .withNoEscape(extInfo.isNoEscape()); return SILFunctionType::get(genericSig, silExtInfo, SILCoroutineKind::None, calleeConvention, inputs, /*yields*/ {}, results, errorResult, M.getASTContext(), witnessMethodConformance); } //===----------------------------------------------------------------------===// // Deallocator SILFunctionTypes //===----------------------------------------------------------------------===// namespace { // The convention for general deallocators. struct DeallocatorConventions : Conventions { DeallocatorConventions() : Conventions(ConventionsKind::Deallocator) {} ParameterConvention getIndirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { llvm_unreachable("Deallocators do not have indirect parameters"); } ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { llvm_unreachable("Deallocators do not have non-self direct parameters"); } ParameterConvention getCallee() const override { llvm_unreachable("Deallocators do not have callees"); } ResultConvention getResult(const TypeLowering &tl) const override { // TODO: Put an unreachable here? return ResultConvention::Owned; } ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { // TODO: Investigate whether or not it is return ParameterConvention::Direct_Owned; } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("Deallocators do not have indirect self parameters"); } static bool classof(const Conventions *C) { return C->getKind() == ConventionsKind::Deallocator; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Default Convention FunctionTypes //===----------------------------------------------------------------------===// namespace { enum class NormalParameterConvention { Owned, Guaranteed }; /// The default Swift conventions. class DefaultConventions : public Conventions { NormalParameterConvention normalParameterConvention; public: DefaultConventions(NormalParameterConvention normalParameterConvention) : Conventions(ConventionsKind::Default), normalParameterConvention(normalParameterConvention) {} bool isNormalParameterConventionGuaranteed() const { return normalParameterConvention == NormalParameterConvention::Guaranteed; } ParameterConvention getIndirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { if (isNormalParameterConventionGuaranteed()) { return ParameterConvention::Indirect_In_Guaranteed; } return ParameterConvention::Indirect_In; } ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { if (isNormalParameterConventionGuaranteed()) return ParameterConvention::Direct_Guaranteed; return ParameterConvention::Direct_Owned; } ParameterConvention getCallee() const override { return DefaultThickCalleeConvention; } ResultConvention getResult(const TypeLowering &tl) const override { return ResultConvention::Owned; } ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { return ParameterConvention::Direct_Guaranteed; } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { return ParameterConvention::Indirect_In_Guaranteed; } static bool classof(const Conventions *C) { return C->getKind() == ConventionsKind::Default; } }; /// The default conventions for Swift initializing constructors. /// /// Initializing constructors take all parameters (including) self at +1. This /// is because: /// /// 1. We are likely to be initializing fields of self implying that the /// parameters are likely to be forwarded into memory without further /// copies. /// 2. Initializers must take 'self' at +1, since they will return it back /// at +1, and may chain onto Objective-C initializers that replace the /// instance. struct DefaultInitializerConventions : DefaultConventions { DefaultInitializerConventions() : DefaultConventions(NormalParameterConvention::Owned) {} /// Initializers must take 'self' at +1, since they will return it back at +1, /// and may chain onto Objective-C initializers that replace the instance. ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { return ParameterConvention::Direct_Owned; } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { return ParameterConvention::Indirect_In; } }; /// The convention used for allocating inits. Allocating inits take their normal /// parameters at +1 and do not have a self parameter. struct DefaultAllocatorConventions : DefaultConventions { DefaultAllocatorConventions() : DefaultConventions(NormalParameterConvention::Owned) {} ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("Allocating inits do not have self parameters"); } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("Allocating inits do not have self parameters"); } }; /// The default conventions for Swift setter acccessors. /// /// These take self at +0, but all other parameters at +1. This is because we /// assume that setter parameters are likely to be values to be forwarded into /// memory. Thus by passing in the +1 value, we avoid a potential copy in that /// case. struct DefaultSetterConventions : DefaultConventions { DefaultSetterConventions() : DefaultConventions(NormalParameterConvention::Owned) {} }; /// The default conventions for ObjC blocks. struct DefaultBlockConventions : Conventions { DefaultBlockConventions() : Conventions(ConventionsKind::DefaultBlock) {} ParameterConvention getIndirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { llvm_unreachable("indirect block parameters unsupported"); } ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { return ParameterConvention::Direct_Unowned; } ParameterConvention getCallee() const override { return ParameterConvention::Direct_Unowned; } ResultConvention getResult(const TypeLowering &substTL) const override { return ResultConvention::Autoreleased; } ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("objc blocks do not have a self parameter"); } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("objc blocks do not have a self parameter"); } static bool classof(const Conventions *C) { return C->getKind() == ConventionsKind::DefaultBlock; } }; } // end anonymous namespace static CanSILFunctionType getSILFunctionTypeForAbstractCFunction(SILModule &M, AbstractionPattern origType, CanAnyFunctionType substType, AnyFunctionType::ExtInfo extInfo, Optional<SILDeclRef> constant); /// If EnableGuaranteedNormalArguments is set, return a default convention that /// uses guaranteed. static DefaultConventions getNormalArgumentConvention(SILModule &M) { if (M.getOptions().EnableGuaranteedNormalArguments) return DefaultConventions(NormalParameterConvention::Guaranteed); return DefaultConventions(NormalParameterConvention::Owned); } static CanSILFunctionType getNativeSILFunctionType( SILModule &M, AbstractionPattern origType, CanAnyFunctionType substInterfaceType, AnyFunctionType::ExtInfo extInfo, Optional<SILDeclRef> constant, Optional<ProtocolConformanceRef> witnessMethodConformance) { switch (extInfo.getSILRepresentation()) { case SILFunctionType::Representation::Block: case SILFunctionType::Representation::CFunctionPointer: return getSILFunctionTypeForAbstractCFunction(M, origType, substInterfaceType, extInfo, constant); case SILFunctionType::Representation::Thin: case SILFunctionType::Representation::ObjCMethod: case SILFunctionType::Representation::Thick: case SILFunctionType::Representation::Method: case SILFunctionType::Representation::Closure: case SILFunctionType::Representation::WitnessMethod: { switch (constant ? constant->kind : SILDeclRef::Kind::Func) { case SILDeclRef::Kind::Initializer: case SILDeclRef::Kind::EnumElement: return getSILFunctionType(M, origType, substInterfaceType, extInfo, DefaultInitializerConventions(), ForeignInfo(), constant, witnessMethodConformance); case SILDeclRef::Kind::Allocator: return getSILFunctionType(M, origType, substInterfaceType, extInfo, DefaultAllocatorConventions(), ForeignInfo(), constant, witnessMethodConformance); case SILDeclRef::Kind::Func: // If we have a setter, use the special setter convention. This ensures // that we take normal parameters at +1. if (constant && constant->isSetter()) { return getSILFunctionType(M, origType, substInterfaceType, extInfo, DefaultSetterConventions(), ForeignInfo(), constant, witnessMethodConformance); } LLVM_FALLTHROUGH; case SILDeclRef::Kind::Destroyer: case SILDeclRef::Kind::GlobalAccessor: case SILDeclRef::Kind::DefaultArgGenerator: case SILDeclRef::Kind::StoredPropertyInitializer: case SILDeclRef::Kind::IVarInitializer: case SILDeclRef::Kind::IVarDestroyer: return getSILFunctionType(M, origType, substInterfaceType, extInfo, getNormalArgumentConvention(M), ForeignInfo(), constant, witnessMethodConformance); case SILDeclRef::Kind::Deallocator: return getSILFunctionType(M, origType, substInterfaceType, extInfo, DeallocatorConventions(), ForeignInfo(), constant, witnessMethodConformance); } } } llvm_unreachable("Unhandled SILDeclRefKind in switch."); } CanSILFunctionType swift::getNativeSILFunctionType( SILModule &M, AbstractionPattern origType, CanAnyFunctionType substType, Optional<SILDeclRef> constant, Optional<ProtocolConformanceRef> witnessMethodConformance) { AnyFunctionType::ExtInfo extInfo; // Preserve type information from the original type if possible. if (auto origFnType = origType.getAs<AnyFunctionType>()) { extInfo = origFnType->getExtInfo(); // Otherwise, preserve function type attributes from the substituted type. } else { extInfo = substType->getExtInfo(); } return ::getNativeSILFunctionType(M, origType, substType, extInfo, constant, witnessMethodConformance); } //===----------------------------------------------------------------------===// // Foreign SILFunctionTypes //===----------------------------------------------------------------------===// static bool isCFTypedef(const TypeLowering &tl, clang::QualType type) { // If we imported a C pointer type as a non-trivial type, it was // a foreign class type. return !tl.isTrivial() && type->isPointerType(); } /// Given nothing but a formal C parameter type that's passed /// indirectly, deduce the convention for it. /// /// Generally, whether the parameter is +1 is handled before this. static ParameterConvention getIndirectCParameterConvention(clang::QualType type) { // Non-trivial C++ types would be Indirect_Inout (at least in Itanium). // A trivial const * parameter in C should be considered @in. return ParameterConvention::Indirect_In; } /// Given a C parameter declaration whose type is passed indirectly, /// deduce the convention for it. /// /// Generally, whether the parameter is +1 is handled before this. static ParameterConvention getIndirectCParameterConvention(const clang::ParmVarDecl *param) { return getIndirectCParameterConvention(param->getType()); } /// Given nothing but a formal C parameter type that's passed /// directly, deduce the convention for it. /// /// Generally, whether the parameter is +1 is handled before this. static ParameterConvention getDirectCParameterConvention(clang::QualType type) { return ParameterConvention::Direct_Unowned; } /// Given a C parameter declaration whose type is passed directly, /// deduce the convention for it. static ParameterConvention getDirectCParameterConvention(const clang::ParmVarDecl *param) { if (param->hasAttr<clang::NSConsumedAttr>() || param->hasAttr<clang::CFConsumedAttr>()) return ParameterConvention::Direct_Owned; return getDirectCParameterConvention(param->getType()); } // FIXME: that should be Direct_Guaranteed const auto ObjCSelfConvention = ParameterConvention::Direct_Unowned; namespace { class ObjCMethodConventions : public Conventions { const clang::ObjCMethodDecl *Method; public: const clang::ObjCMethodDecl *getMethod() const { return Method; } ObjCMethodConventions(const clang::ObjCMethodDecl *method) : Conventions(ConventionsKind::ObjCMethod), Method(method) {} ParameterConvention getIndirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { return getIndirectCParameterConvention(Method->param_begin()[index]); } ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { return getDirectCParameterConvention(Method->param_begin()[index]); } ParameterConvention getCallee() const override { // Always thin. return ParameterConvention::Direct_Unowned; } /// Given that a method returns a CF type, infer its method /// family. Unfortunately, Clang's getMethodFamily() never /// considers a method to be in a special family if its result /// doesn't satisfy isObjCRetainable(). clang::ObjCMethodFamily getMethodFamilyForCFResult() const { // Trust an explicit attribute. if (auto attr = Method->getAttr<clang::ObjCMethodFamilyAttr>()) { switch (attr->getFamily()) { case clang::ObjCMethodFamilyAttr::OMF_None: return clang::OMF_None; case clang::ObjCMethodFamilyAttr::OMF_alloc: return clang::OMF_alloc; case clang::ObjCMethodFamilyAttr::OMF_copy: return clang::OMF_copy; case clang::ObjCMethodFamilyAttr::OMF_init: return clang::OMF_init; case clang::ObjCMethodFamilyAttr::OMF_mutableCopy: return clang::OMF_mutableCopy; case clang::ObjCMethodFamilyAttr::OMF_new: return clang::OMF_new; } llvm_unreachable("bad attribute value"); } return Method->getSelector().getMethodFamily(); } bool isImplicitPlusOneCFResult() const { switch (getMethodFamilyForCFResult()) { case clang::OMF_None: case clang::OMF_dealloc: case clang::OMF_finalize: case clang::OMF_retain: case clang::OMF_release: case clang::OMF_autorelease: case clang::OMF_retainCount: case clang::OMF_self: case clang::OMF_initialize: case clang::OMF_performSelector: return false; case clang::OMF_alloc: case clang::OMF_new: case clang::OMF_mutableCopy: case clang::OMF_copy: return true; case clang::OMF_init: return Method->isInstanceMethod(); } llvm_unreachable("bad method family"); } ResultConvention getResult(const TypeLowering &tl) const override { // If we imported the result as something trivial, we need to // use one of the unowned conventions. if (tl.isTrivial()) { if (Method->hasAttr<clang::ObjCReturnsInnerPointerAttr>()) return ResultConvention::UnownedInnerPointer; auto type = tl.getLoweredType(); if (type.unwrapOptionalType().getStructOrBoundGenericStruct() == type.getASTContext().getUnmanagedDecl()) return ResultConvention::UnownedInnerPointer; return ResultConvention::Unowned; } // Otherwise, the return type had better be a retainable object pointer. auto resultType = Method->getReturnType(); assert(resultType->isObjCRetainableType() || isCFTypedef(tl, resultType)); // If it's retainable for the purposes of ObjC ARC, we can trust // the presence of ns_returns_retained, because Clang will add // that implicitly based on the method family. if (resultType->isObjCRetainableType()) { if (Method->hasAttr<clang::NSReturnsRetainedAttr>()) return ResultConvention::Owned; return ResultConvention::Autoreleased; } // Otherwise, it's a CF return type, which unfortunately means // we can't just trust getMethodFamily(). We should really just // change that, but that's an annoying change to make to Clang // right now. assert(isCFTypedef(tl, resultType)); // Trust the explicit attributes. if (Method->hasAttr<clang::CFReturnsRetainedAttr>()) return ResultConvention::Owned; if (Method->hasAttr<clang::CFReturnsNotRetainedAttr>()) return ResultConvention::Autoreleased; // Otherwise, infer based on the method family. if (isImplicitPlusOneCFResult()) return ResultConvention::Owned; return ResultConvention::Autoreleased; } ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { if (Method->hasAttr<clang::NSConsumesSelfAttr>()) return ParameterConvention::Direct_Owned; // The caller is supposed to take responsibility for ensuring // that 'self' survives a method call. return ObjCSelfConvention; } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("objc methods do not support indirect self parameters"); } static bool classof(const Conventions *C) { return C->getKind() == ConventionsKind::ObjCMethod; } }; /// Conventions based on a C function type. class CFunctionTypeConventions : public Conventions { const clang::FunctionType *FnType; clang::QualType getParamType(unsigned i) const { return FnType->castAs<clang::FunctionProtoType>()->getParamType(i); } protected: /// Protected constructor for subclasses to override the kind passed to the /// super class. CFunctionTypeConventions(ConventionsKind kind, const clang::FunctionType *type) : Conventions(kind), FnType(type) {} public: CFunctionTypeConventions(const clang::FunctionType *type) : Conventions(ConventionsKind::CFunctionType), FnType(type) {} ParameterConvention getIndirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { return getIndirectCParameterConvention(getParamType(index)); } ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { if (cast<clang::FunctionProtoType>(FnType)->isParamConsumed(index)) return ParameterConvention::Direct_Owned; return getDirectCParameterConvention(getParamType(index)); } ParameterConvention getCallee() const override { // FIXME: blocks should be Direct_Guaranteed. return ParameterConvention::Direct_Unowned; } ResultConvention getResult(const TypeLowering &tl) const override { if (tl.isTrivial()) return ResultConvention::Unowned; if (FnType->getExtInfo().getProducesResult()) return ResultConvention::Owned; return ResultConvention::Autoreleased; } ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("c function types do not have a self parameter"); } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("c function types do not have a self parameter"); } static bool classof(const Conventions *C) { return C->getKind() == ConventionsKind::CFunctionType; } }; /// Conventions based on C function declarations. class CFunctionConventions : public CFunctionTypeConventions { using super = CFunctionTypeConventions; const clang::FunctionDecl *TheDecl; public: CFunctionConventions(const clang::FunctionDecl *decl) : CFunctionTypeConventions(ConventionsKind::CFunction, decl->getType()->castAs<clang::FunctionType>()), TheDecl(decl) {} ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { if (auto param = TheDecl->getParamDecl(index)) if (param->hasAttr<clang::CFConsumedAttr>()) return ParameterConvention::Direct_Owned; return super::getDirectParameter(index, type, substTL); } ResultConvention getResult(const TypeLowering &tl) const override { if (isCFTypedef(tl, TheDecl->getReturnType())) { // The CF attributes aren't represented in the type, so we need // to check them here. if (TheDecl->hasAttr<clang::CFReturnsRetainedAttr>()) { return ResultConvention::Owned; } else if (TheDecl->hasAttr<clang::CFReturnsNotRetainedAttr>()) { // Probably not actually autoreleased. return ResultConvention::Autoreleased; // The CF Create/Copy rule only applies to functions that return // a CF-runtime type; it does not apply to methods, and it does // not apply to functions returning ObjC types. } else if (clang::ento::coreFoundation::followsCreateRule(TheDecl)) { return ResultConvention::Owned; } else { return ResultConvention::Autoreleased; } } // Otherwise, fall back on the ARC annotations, which are part // of the type. return super::getResult(tl); } static bool classof(const Conventions *C) { return C->getKind() == ConventionsKind::CFunction; } }; } // end anonymous namespace /// Given that we have an imported Clang declaration, deduce the /// ownership conventions for calling it and build the SILFunctionType. static CanSILFunctionType getSILFunctionTypeForClangDecl(SILModule &M, const clang::Decl *clangDecl, CanAnyFunctionType origType, CanAnyFunctionType substInterfaceType, AnyFunctionType::ExtInfo extInfo, const ForeignInfo &foreignInfo, Optional<SILDeclRef> constant) { if (auto method = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) { auto origPattern = AbstractionPattern::getObjCMethod(origType, method, foreignInfo.Error); return getSILFunctionType(M, origPattern, substInterfaceType, extInfo, ObjCMethodConventions(method), foreignInfo, constant, /*witnessMethodConformance=*/None); } if (auto func = dyn_cast<clang::FunctionDecl>(clangDecl)) { auto clangType = func->getType().getTypePtr(); AbstractionPattern origPattern = foreignInfo.Self.isImportAsMember() ? AbstractionPattern::getCFunctionAsMethod(origType, clangType, foreignInfo.Self) : AbstractionPattern(origType, clangType); return getSILFunctionType(M, origPattern, substInterfaceType, extInfo, CFunctionConventions(func), foreignInfo, constant, /*witnessMethodConformance=*/None); } llvm_unreachable("call to unknown kind of C function"); } static CanSILFunctionType getSILFunctionTypeForAbstractCFunction(SILModule &M, AbstractionPattern origType, CanAnyFunctionType substType, AnyFunctionType::ExtInfo extInfo, Optional<SILDeclRef> constant) { if (origType.isClangType()) { auto clangType = origType.getClangType(); const clang::FunctionType *fnType; if (auto blockPtr = clangType->getAs<clang::BlockPointerType>()) { fnType = blockPtr->getPointeeType()->castAs<clang::FunctionType>(); } else if (auto ptr = clangType->getAs<clang::PointerType>()) { fnType = ptr->getPointeeType()->getAs<clang::FunctionType>(); } else if (auto ref = clangType->getAs<clang::ReferenceType>()) { fnType = ref->getPointeeType()->getAs<clang::FunctionType>(); } else if (auto fn = clangType->getAs<clang::FunctionType>()) { fnType = fn; } else { llvm_unreachable("unexpected type imported as a function type"); } if (fnType) { return getSILFunctionType(M, origType, substType, extInfo, CFunctionTypeConventions(fnType), ForeignInfo(), constant, /*witnessMethodConformance=*/None); } } // TODO: Ought to support captures in block funcs. return getSILFunctionType(M, origType, substType, extInfo, DefaultBlockConventions(), ForeignInfo(), constant, /*witnessMethodConformance=*/None); } /// Try to find a clang method declaration for the given function. static const clang::Decl *findClangMethod(ValueDecl *method) { if (auto *methodFn = dyn_cast<FuncDecl>(method)) { if (auto *decl = methodFn->getClangDecl()) return decl; if (auto overridden = methodFn->getOverriddenDecl()) return findClangMethod(overridden); } if (auto *constructor = dyn_cast<ConstructorDecl>(method)) { if (auto *decl = constructor->getClangDecl()) return decl; } return nullptr; } //===----------------------------------------------------------------------===// // Selector Family SILFunctionTypes //===----------------------------------------------------------------------===// /// Apply a macro FAMILY(Name, Prefix) to all ObjC selector families. #define FOREACH_FAMILY(FAMILY) \ FAMILY(Alloc, "alloc") \ FAMILY(Copy, "copy") \ FAMILY(Init, "init") \ FAMILY(MutableCopy, "mutableCopy") \ FAMILY(New, "new") namespace { enum class SelectorFamily : unsigned { None, #define GET_LABEL(LABEL, PREFIX) LABEL, FOREACH_FAMILY(GET_LABEL) #undef GET_LABEL }; } // end anonymous namespace /// Derive the ObjC selector family from an identifier. /// /// Note that this will never derive the Init family, which is too dangerous /// to leave to chance. Swift functions starting with "init" are always /// emitted as if they are part of the "none" family. static SelectorFamily getSelectorFamily(Identifier name) { StringRef text = name.get(); while (!text.empty() && text[0] == '_') text = text.substr(1); // Does the given selector start with the given string as a prefix, in the // sense of the selector naming conventions? // This implementation matches the one used by // clang::Selector::getMethodFamily, to make sure we behave the same as Clang // ARC. We're not just calling that method here because it means allocating a // clang::IdentifierInfo, which requires a Clang ASTContext. auto hasPrefix = [](StringRef text, StringRef prefix) { if (!text.startswith(prefix)) return false; if (text.size() == prefix.size()) return true; assert(text.size() > prefix.size()); return !clang::isLowercase(text[prefix.size()]); }; auto result = SelectorFamily::None; if (false) /*for #define purposes*/; #define CHECK_PREFIX(LABEL, PREFIX) \ else if (hasPrefix(text, PREFIX)) result = SelectorFamily::LABEL; FOREACH_FAMILY(CHECK_PREFIX) #undef CHECK_PREFIX if (result == SelectorFamily::Init) return SelectorFamily::None; return result; } /// Get the ObjC selector family a foreign SILDeclRef belongs to. static SelectorFamily getSelectorFamily(SILDeclRef c) { assert(c.isForeign); switch (c.kind) { case SILDeclRef::Kind::Func: { if (!c.hasDecl()) return SelectorFamily::None; auto *FD = cast<FuncDecl>(c.getDecl()); if (auto accessor = dyn_cast<AccessorDecl>(FD)) { switch (accessor->getAccessorKind()) { case AccessorKind::Get: case AccessorKind::Set: break; case AccessorKind::WillSet: case AccessorKind::DidSet: case AccessorKind::Address: case AccessorKind::MutableAddress: case AccessorKind::MaterializeForSet: llvm_unreachable("Unexpected AccessorKind of foreign FuncDecl"); } } return getSelectorFamily(FD->getObjCSelector().getSelectorPieces().front()); } case SILDeclRef::Kind::Initializer: case SILDeclRef::Kind::IVarInitializer: return SelectorFamily::Init; /// Currently IRGen wraps alloc/init methods into Swift constructors /// with Swift conventions. case SILDeclRef::Kind::Allocator: /// These constants don't correspond to method families we care about yet. case SILDeclRef::Kind::Destroyer: case SILDeclRef::Kind::Deallocator: case SILDeclRef::Kind::IVarDestroyer: return SelectorFamily::None; case SILDeclRef::Kind::EnumElement: case SILDeclRef::Kind::GlobalAccessor: case SILDeclRef::Kind::DefaultArgGenerator: case SILDeclRef::Kind::StoredPropertyInitializer: llvm_unreachable("Unexpected Kind of foreign SILDeclRef"); } llvm_unreachable("Unhandled SILDeclRefKind in switch."); } namespace { class SelectorFamilyConventions : public Conventions { SelectorFamily Family; public: SelectorFamilyConventions(SelectorFamily family) : Conventions(ConventionsKind::SelectorFamily), Family(family) {} ParameterConvention getIndirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { return ParameterConvention::Indirect_In; } ParameterConvention getDirectParameter(unsigned index, const AbstractionPattern &type, const TypeLowering &substTL) const override { return ParameterConvention::Direct_Unowned; } ParameterConvention getCallee() const override { // Always thin. return ParameterConvention::Direct_Unowned; } ResultConvention getResult(const TypeLowering &tl) const override { switch (Family) { case SelectorFamily::Alloc: case SelectorFamily::Copy: case SelectorFamily::Init: case SelectorFamily::MutableCopy: case SelectorFamily::New: return ResultConvention::Owned; case SelectorFamily::None: // Defaults below. break; } auto type = tl.getLoweredType().getASTType(); if (type->hasRetainablePointerRepresentation() || (type->getSwiftNewtypeUnderlyingType() && !tl.isTrivial())) return ResultConvention::Autoreleased; return ResultConvention::Unowned; } ParameterConvention getDirectSelfParameter(const AbstractionPattern &type) const override { if (Family == SelectorFamily::Init) return ParameterConvention::Direct_Owned; return ObjCSelfConvention; } ParameterConvention getIndirectSelfParameter(const AbstractionPattern &type) const override { llvm_unreachable("selector family objc function types do not support " "indirect self parameters"); } static bool classof(const Conventions *C) { return C->getKind() == ConventionsKind::SelectorFamily; } }; } // end anonymous namespace static CanSILFunctionType getSILFunctionTypeForSelectorFamily(SILModule &M, SelectorFamily family, CanAnyFunctionType origType, CanAnyFunctionType substInterfaceType, AnyFunctionType::ExtInfo extInfo, const ForeignInfo &foreignInfo, Optional<SILDeclRef> constant) { return getSILFunctionType(M, AbstractionPattern(origType), substInterfaceType, extInfo, SelectorFamilyConventions(family), foreignInfo, constant, /*witnessMethodConformance=*/None); } static bool isImporterGeneratedAccessor(const clang::Decl *clangDecl, SILDeclRef constant) { // Must be an accessor. auto accessor = dyn_cast<AccessorDecl>(constant.getDecl()); if (!accessor) return false; // Must be a type member. if (constant.getParameterListCount() != 2) return false; // Must be imported from a function. if (!isa<clang::FunctionDecl>(clangDecl)) return false; return true; } static CanSILFunctionType getUncachedSILFunctionTypeForConstant(SILModule &M, SILDeclRef constant, CanAnyFunctionType origLoweredInterfaceType) { assert(origLoweredInterfaceType->getExtInfo().getSILRepresentation() != SILFunctionTypeRepresentation::Thick && origLoweredInterfaceType->getExtInfo().getSILRepresentation() != SILFunctionTypeRepresentation::Block); auto extInfo = origLoweredInterfaceType->getExtInfo(); if (!constant.isForeign) { Optional<ProtocolConformanceRef> witnessMethodConformance; if (extInfo.getSILRepresentation() == SILFunctionTypeRepresentation::WitnessMethod) { auto proto = constant.getDecl() ->getDeclContext() ->getAsProtocolOrProtocolExtensionContext(); witnessMethodConformance = ProtocolConformanceRef(proto); } return ::getNativeSILFunctionType( M, AbstractionPattern(origLoweredInterfaceType), origLoweredInterfaceType, extInfo, constant, witnessMethodConformance); } ForeignInfo foreignInfo; // If we have a clang decl associated with the Swift decl, derive its // ownership conventions. if (constant.hasDecl()) { auto decl = constant.getDecl(); if (auto funcDecl = dyn_cast<AbstractFunctionDecl>(decl)) { foreignInfo.Error = funcDecl->getForeignErrorConvention(); foreignInfo.Self = funcDecl->getImportAsMemberStatus(); } if (auto clangDecl = findClangMethod(decl)) { // The importer generates accessors that are not actually // import-as-member but do involve the same gymnastics with the // formal type. That's all that SILFunctionType cares about, so // pretend that it's import-as-member. if (!foreignInfo.Self.isImportAsMember() && isImporterGeneratedAccessor(clangDecl, constant)) { assert(origLoweredInterfaceType->getNumParams() == 2); // The 'self' parameter is still the second argument. unsigned selfIndex = cast<AccessorDecl>(decl)->isSetter() ? 1 : 0; assert(selfIndex == 1 || origLoweredInterfaceType.getParams()[0].getType()->isVoid()); foreignInfo.Self.setSelfIndex(selfIndex); } return getSILFunctionTypeForClangDecl(M, clangDecl, origLoweredInterfaceType, origLoweredInterfaceType, extInfo, foreignInfo, constant); } } // If the decl belongs to an ObjC method family, use that family's // ownership conventions. return getSILFunctionTypeForSelectorFamily(M, getSelectorFamily(constant), origLoweredInterfaceType, origLoweredInterfaceType, extInfo, foreignInfo, constant); } CanSILFunctionType TypeConverter:: getUncachedSILFunctionTypeForConstant(SILDeclRef constant, CanAnyFunctionType origInterfaceType) { auto origLoweredInterfaceType = getLoweredFormalTypes(constant, origInterfaceType).Uncurried; return ::getUncachedSILFunctionTypeForConstant(M, constant, origLoweredInterfaceType); } static bool isClassOrProtocolMethod(ValueDecl *vd) { if (!vd->getDeclContext()) return false; Type contextType = vd->getDeclContext()->getDeclaredInterfaceType(); if (!contextType) return false; return contextType->getClassOrBoundGenericClass() || contextType->isClassExistentialType(); } SILFunctionTypeRepresentation TypeConverter::getDeclRefRepresentation(SILDeclRef c) { // Currying thunks always have freestanding CC. if (c.isCurried) return SILFunctionTypeRepresentation::Thin; // If this is a foreign thunk, it always has the foreign calling convention. if (c.isForeign) { if (!c.hasDecl() || c.getDecl()->isImportAsMember()) return SILFunctionTypeRepresentation::CFunctionPointer; if (isClassOrProtocolMethod(c.getDecl()) || c.kind == SILDeclRef::Kind::IVarInitializer || c.kind == SILDeclRef::Kind::IVarDestroyer) return SILFunctionTypeRepresentation::ObjCMethod; return SILFunctionTypeRepresentation::CFunctionPointer; } // Anonymous functions currently always have Freestanding CC. if (!c.hasDecl()) return SILFunctionTypeRepresentation::Thin; // FIXME: Assert that there is a native entry point // available. There's no great way to do this. // Protocol witnesses are called using the witness calling convention. if (auto proto = dyn_cast<ProtocolDecl>(c.getDecl()->getDeclContext())) { // Use the regular method convention for foreign-to-native thunks. if (c.isForeignToNativeThunk()) return SILFunctionTypeRepresentation::Method; assert(!c.isNativeToForeignThunk() && "shouldn't be possible"); return getProtocolWitnessRepresentation(proto); } switch (c.kind) { case SILDeclRef::Kind::GlobalAccessor: case SILDeclRef::Kind::DefaultArgGenerator: case SILDeclRef::Kind::StoredPropertyInitializer: return SILFunctionTypeRepresentation::Thin; case SILDeclRef::Kind::Func: if (c.getDecl()->getDeclContext()->isTypeContext()) return SILFunctionTypeRepresentation::Method; return SILFunctionTypeRepresentation::Thin; case SILDeclRef::Kind::Destroyer: case SILDeclRef::Kind::Deallocator: case SILDeclRef::Kind::Allocator: case SILDeclRef::Kind::Initializer: case SILDeclRef::Kind::EnumElement: case SILDeclRef::Kind::IVarInitializer: case SILDeclRef::Kind::IVarDestroyer: return SILFunctionTypeRepresentation::Method; } llvm_unreachable("Unhandled SILDeclRefKind in switch."); } // Provide the ability to turn off the type converter cache to ease debugging. static llvm::cl::opt<bool> DisableConstantInfoCache("sil-disable-typelowering-constantinfo-cache", llvm::cl::init(false)); const SILConstantInfo &TypeConverter::getConstantInfo(SILDeclRef constant) { if (!DisableConstantInfoCache) { auto found = ConstantTypes.find(constant); if (found != ConstantTypes.end()) return *found->second; } // First, get a function type for the constant. This creates the // right type for a getter or setter. auto formalInterfaceType = makeConstantInterfaceType(constant); auto *genericEnv = getConstantGenericEnvironment(constant); // The formal type is just that with the right representation. auto rep = getDeclRefRepresentation(constant); formalInterfaceType = adjustFunctionType(formalInterfaceType, rep); // The lowered type is the formal type, but uncurried and with // parameters automatically turned into their bridged equivalents. auto bridgedTypes = getLoweredFormalTypes(constant, formalInterfaceType); CanAnyFunctionType loweredInterfaceType = bridgedTypes.Uncurried; // The SIL type encodes conventions according to the original type. CanSILFunctionType silFnType = ::getUncachedSILFunctionTypeForConstant(M, constant, loweredInterfaceType); DEBUG(llvm::dbgs() << "lowering type for constant "; constant.print(llvm::dbgs()); llvm::dbgs() << "\n formal type: "; formalInterfaceType.print(llvm::dbgs()); llvm::dbgs() << "\n lowered AST type: "; loweredInterfaceType.print(llvm::dbgs()); llvm::dbgs() << "\n SIL type: "; silFnType.print(llvm::dbgs()); llvm::dbgs() << "\n"); auto resultBuf = M.allocate(sizeof(SILConstantInfo), alignof(SILConstantInfo)); auto result = ::new (resultBuf) SILConstantInfo{formalInterfaceType, bridgedTypes.Pattern, loweredInterfaceType, silFnType, genericEnv}; if (DisableConstantInfoCache) return *result; auto inserted = ConstantTypes.insert({constant, result}); assert(inserted.second); return *result; } /// Returns the SILParameterInfo for the given declaration's `self` parameter. /// `constant` must refer to a method. SILParameterInfo TypeConverter::getConstantSelfParameter(SILDeclRef constant) { auto ty = getConstantFunctionType(constant); // In most cases the "self" parameter is lowered as the back parameter. // The exception is C functions imported as methods. if (!constant.isForeign) return ty->getParameters().back(); if (!constant.hasDecl()) return ty->getParameters().back(); auto fn = dyn_cast<AbstractFunctionDecl>(constant.getDecl()); if (!fn) return ty->getParameters().back(); if (fn->isImportAsStaticMember()) return SILParameterInfo(); if (fn->isImportAsInstanceMember()) return ty->getParameters()[fn->getSelfIndex()]; return ty->getParameters().back(); } // This check duplicates TypeConverter::checkForABIDifferences(), // but on AST types. The issue is we only want to introduce a new // vtable thunk if the AST type changes, but an abstraction change // is OK; we don't want a new entry if an @in parameter became // @guaranteed or whatever. static bool checkASTTypeForABIDifferences(CanType type1, CanType type2) { return !type1->matches(type2, TypeMatchFlags::AllowABICompatible); } // FIXME: This makes me very upset. Can we do without this? static CanType copyOptionalityFromDerivedToBase(TypeConverter &tc, CanType derived, CanType base) { // Unwrap optionals, but remember that we did. bool derivedWasOptional = false; if (auto object = derived.getOptionalObjectType()) { derivedWasOptional = true; derived = object; } if (auto object = base.getOptionalObjectType()) { base = object; } // T? +> S = (T +> S)? // T? +> S? = (T +> S)? if (derivedWasOptional) { base = copyOptionalityFromDerivedToBase(tc, derived, base); auto optDecl = tc.Context.getOptionalDecl(); return CanType(BoundGenericEnumType::get(optDecl, Type(), base)); } // (T1, T2, ...) +> (S1, S2, ...) = (T1 +> S1, T2 +> S2, ...) if (auto derivedTuple = dyn_cast<TupleType>(derived)) { if (auto baseTuple = dyn_cast<TupleType>(base)) { assert(derivedTuple->getNumElements() == baseTuple->getNumElements()); SmallVector<TupleTypeElt, 4> elements; for (unsigned i = 0, e = derivedTuple->getNumElements(); i < e; i++) { elements.push_back( baseTuple->getElement(i).getWithType( copyOptionalityFromDerivedToBase( tc, derivedTuple.getElementType(i), baseTuple.getElementType(i)))); } return CanType(TupleType::get(elements, tc.Context)); } } // (T1 -> T2) +> (S1 -> S2) = (T1 +> S1) -> (T2 +> S2) if (auto derivedFunc = dyn_cast<AnyFunctionType>(derived)) { if (auto baseFunc = dyn_cast<AnyFunctionType>(base)) { return CanAnyFunctionType::get( baseFunc.getOptGenericSignature(), copyOptionalityFromDerivedToBase(tc, derivedFunc.getInput(), baseFunc.getInput()), copyOptionalityFromDerivedToBase(tc, derivedFunc.getResult(), baseFunc.getResult()), baseFunc->getExtInfo()); } } return base; } /// Returns the ConstantInfo corresponding to the VTable thunk for overriding. /// Will be the same as getConstantInfo if the declaration does not override. const SILConstantInfo & TypeConverter::getConstantOverrideInfo(SILDeclRef derived, SILDeclRef base) { // Foreign overrides currently don't need reabstraction. if (derived.isForeign) return getConstantInfo(derived); auto found = ConstantOverrideTypes.find({derived, base}); if (found != ConstantOverrideTypes.end()) return *found->second; assert(base.requiresNewVTableEntry() && "base must not be an override"); auto baseInfo = getConstantInfo(base); auto derivedInfo = getConstantInfo(derived); // If the derived method is ABI-compatible with the base method, give the // vtable thunk the same signature as the derived method. auto basePattern = AbstractionPattern(baseInfo.LoweredType); auto baseInterfaceTy = baseInfo.FormalType; auto derivedInterfaceTy = derivedInfo.FormalType; auto selfInterfaceTy = derivedInterfaceTy.getInput()->getRValueInstanceType(); auto overrideInterfaceTy = selfInterfaceTy->adjustSuperclassMemberDeclType( base.getDecl(), derived.getDecl(), baseInterfaceTy); // Copy generic signature from derived to the override type, to handle // the case where the base member is not generic (because the base class // is concrete) but the derived member is generic (because the derived // class is generic). if (auto derivedInterfaceFnTy = derivedInterfaceTy->getAs<GenericFunctionType>()) { auto overrideInterfaceFnTy = overrideInterfaceTy->castTo<FunctionType>(); overrideInterfaceTy = GenericFunctionType::get(derivedInterfaceFnTy->getGenericSignature(), overrideInterfaceFnTy->getInput(), overrideInterfaceFnTy->getResult(), overrideInterfaceFnTy->getExtInfo()); } // Lower the formal AST type. auto bridgedTypes = getLoweredFormalTypes(derived, cast<AnyFunctionType>(overrideInterfaceTy->getCanonicalType())); auto overrideLoweredInterfaceTy = bridgedTypes.Uncurried; if (!checkASTTypeForABIDifferences(derivedInfo.LoweredType, overrideLoweredInterfaceTy)) { basePattern = AbstractionPattern( copyOptionalityFromDerivedToBase( *this, derivedInfo.LoweredType, baseInfo.LoweredType)); overrideLoweredInterfaceTy = derivedInfo.LoweredType; } // Build the SILFunctionType for the vtable thunk. CanSILFunctionType fnTy = getNativeSILFunctionType( M, basePattern, overrideLoweredInterfaceTy, derived, /*witnessMethodConformance=*/None); // Build the SILConstantInfo and cache it. auto resultBuf = M.allocate(sizeof(SILConstantInfo), alignof(SILConstantInfo)); auto result = ::new (resultBuf) SILConstantInfo{ derivedInterfaceTy, bridgedTypes.Pattern, overrideLoweredInterfaceTy, fnTy, derivedInfo.GenericEnv}; auto inserted = ConstantOverrideTypes.insert({{derived, base}, result}); assert(inserted.second); return *result; } namespace { /// Given a lowered SIL type, apply a substitution to it to produce another /// lowered SIL type which uses the same abstraction conventions. class SILTypeSubstituter : public CanTypeVisitor<SILTypeSubstituter, CanType> { SILModule &TheSILModule; TypeSubstitutionFn Subst; LookupConformanceFn Conformances; // The signature for the original type. // // Replacement types are lowered with respect to the current // context signature. CanGenericSignature Sig; ASTContext &getASTContext() { return TheSILModule.getASTContext(); } public: SILTypeSubstituter(SILModule &silModule, TypeSubstitutionFn Subst, LookupConformanceFn Conformances, CanGenericSignature Sig) : TheSILModule(silModule), Subst(Subst), Conformances(Conformances), Sig(Sig) {} // SIL type lowering only does special things to tuples and functions. // When a function appears inside of another type, we only perform // substitutions if it does not have a generic signature. CanSILFunctionType visitSILFunctionType(CanSILFunctionType origType) { if (origType->getGenericSignature()) return origType; return substSILFunctionType(origType); } // Entry point for use by SILType::substGenericArgs(). CanSILFunctionType substSILFunctionType(CanSILFunctionType origType) { SmallVector<SILResultInfo, 8> substResults; substResults.reserve(origType->getNumResults()); for (auto origResult : origType->getResults()) { substResults.push_back(subst(origResult)); } auto substErrorResult = origType->getOptionalErrorResult(); assert(!substErrorResult || (!substErrorResult->getType()->hasTypeParameter() && !substErrorResult->getType()->hasArchetype())); SmallVector<SILParameterInfo, 8> substParams; substParams.reserve(origType->getParameters().size()); for (auto &origParam : origType->getParameters()) { substParams.push_back(subst(origParam)); } SmallVector<SILYieldInfo, 8> substYields; substYields.reserve(origType->getYields().size()); for (auto &origYield : origType->getYields()) { substYields.push_back(subst(origYield)); } Optional<ProtocolConformanceRef> witnessMethodConformance; if (auto conformance = origType->getWitnessMethodConformanceOrNone()) { assert(origType->getExtInfo().hasSelfParam()); auto selfType = origType->getSelfParameter().getType(); // The Self type can be nested in a few layers of metatypes (etc.), e.g. // for a mutable static variable the materializeForSet currently has its // last argument as a Self.Type.Type metatype. while (1) { auto next = selfType->getRValueInstanceType()->getCanonicalType(); if (next == selfType) break; selfType = next; } witnessMethodConformance = conformance->subst(selfType, Subst, Conformances); } return SILFunctionType::get(nullptr, origType->getExtInfo(), origType->getCoroutineKind(), origType->getCalleeConvention(), substParams, substYields, substResults, substErrorResult, getASTContext(), witnessMethodConformance); } SILType subst(SILType type) { return SILType::getPrimitiveType(visit(type.getASTType()), type.getCategory()); } SILResultInfo subst(SILResultInfo orig) { return SILResultInfo(visit(orig.getType()), orig.getConvention()); } SILYieldInfo subst(SILYieldInfo orig) { return SILYieldInfo(visit(orig.getType()), orig.getConvention()); } SILParameterInfo subst(SILParameterInfo orig) { return SILParameterInfo(visit(orig.getType()), orig.getConvention()); } /// Tuples need to have their component types substituted by these /// same rules. CanType visitTupleType(CanTupleType origType) { // Fast-path the empty tuple. if (origType->getNumElements() == 0) return origType; SmallVector<TupleTypeElt, 8> substElts; substElts.reserve(origType->getNumElements()); for (auto &origElt : origType->getElements()) { auto substEltType = visit(CanType(origElt.getType())); substElts.push_back(origElt.getWithType(substEltType)); } return CanType(TupleType::get(substElts, getASTContext())); } // Block storage types need to substitute their capture type by these same // rules. CanType visitSILBlockStorageType(CanSILBlockStorageType origType) { auto substCaptureType = visit(origType->getCaptureType()); return SILBlockStorageType::get(substCaptureType); } /// Optionals need to have their object types substituted by these rules. CanType visitBoundGenericEnumType(CanBoundGenericEnumType origType) { // Only use a special rule if it's Optional. if (!origType->getDecl()->isOptionalDecl()) { return visitType(origType); } CanType origObjectType = origType.getGenericArgs()[0]; CanType substObjectType = visit(origObjectType); return CanType(BoundGenericType::get(origType->getDecl(), Type(), substObjectType)); } /// Any other type is would be a valid type in the AST. Just /// apply the substitution on the AST level and then lower that. CanType visitType(CanType origType) { assert(!isa<AnyFunctionType>(origType)); assert(!isa<LValueType>(origType) && !isa<InOutType>(origType)); auto substType = origType.subst(Subst, Conformances)->getCanonicalType(); // If the substitution didn't change anything, we know that the // original type was a lowered type, so we're good. if (origType == substType) { return origType; } AbstractionPattern abstraction(Sig, origType); return TheSILModule.Types.getLoweredType(abstraction, substType) .getASTType(); } }; } // end anonymous namespace SILType SILType::subst(SILModule &silModule, TypeSubstitutionFn subs, LookupConformanceFn conformances, CanGenericSignature genericSig) const { if (!hasArchetype() && !hasTypeParameter()) return *this; if (!genericSig) genericSig = silModule.Types.getCurGenericContext(); SILTypeSubstituter STST(silModule, subs, conformances, genericSig); return STST.subst(*this); } SILType SILType::subst(SILModule &silModule, SubstitutionMap subs) const{ return subst(silModule, QuerySubstitutionMap{subs}, LookUpConformanceInSubstitutionMap(subs)); } /// Apply a substitution to this polymorphic SILFunctionType so that /// it has the form of the normal SILFunctionType for the substituted /// type, except using the original conventions. CanSILFunctionType SILFunctionType::substGenericArgs(SILModule &silModule, SubstitutionMap subs) { if (!isPolymorphic()) { return CanSILFunctionType(this); } if (subs.empty()) { return CanSILFunctionType(this); } return substGenericArgs(silModule, QuerySubstitutionMap{subs}, LookUpConformanceInSubstitutionMap(subs)); } CanSILFunctionType SILFunctionType::substGenericArgs(SILModule &silModule, TypeSubstitutionFn subs, LookupConformanceFn conformances) { if (!isPolymorphic()) return CanSILFunctionType(this); SILTypeSubstituter substituter(silModule, subs, conformances, getGenericSignature()); return substituter.substSILFunctionType(CanSILFunctionType(this)); } /// Fast path for bridging types in a function type without uncurrying. CanAnyFunctionType TypeConverter::getBridgedFunctionType(AbstractionPattern pattern, CanAnyFunctionType t, AnyFunctionType::ExtInfo extInfo) { // Pull out the generic signature. CanGenericSignature genericSig = t.getOptGenericSignature(); auto rebuild = [&](CanType input, CanType result) -> CanAnyFunctionType { return CanAnyFunctionType::get(genericSig, input, result, extInfo); }; switch (auto rep = t->getExtInfo().getSILRepresentation()) { case SILFunctionTypeRepresentation::Thick: case SILFunctionTypeRepresentation::Thin: case SILFunctionTypeRepresentation::Method: case SILFunctionTypeRepresentation::Closure: case SILFunctionTypeRepresentation::WitnessMethod: // No bridging needed for native functions. if (t->getExtInfo() == extInfo) return t; return rebuild(t.getInput(), t.getResult()); case SILFunctionTypeRepresentation::CFunctionPointer: case SILFunctionTypeRepresentation::Block: case SILFunctionTypeRepresentation::ObjCMethod: return rebuild(getBridgedInputType(rep, pattern.getFunctionInputType(), t.getInput()), getBridgedResultType(rep, pattern.getFunctionResultType(), t.getResult(), pattern.hasForeignErrorStrippingResultOptionality())); } llvm_unreachable("bad calling convention"); } static AbstractFunctionDecl *getBridgedFunction(SILDeclRef declRef) { switch (declRef.kind) { case SILDeclRef::Kind::Func: case SILDeclRef::Kind::Allocator: case SILDeclRef::Kind::Initializer: return (declRef.hasDecl() ? cast<AbstractFunctionDecl>(declRef.getDecl()) : nullptr); case SILDeclRef::Kind::EnumElement: case SILDeclRef::Kind::Destroyer: case SILDeclRef::Kind::Deallocator: case SILDeclRef::Kind::GlobalAccessor: case SILDeclRef::Kind::DefaultArgGenerator: case SILDeclRef::Kind::StoredPropertyInitializer: case SILDeclRef::Kind::IVarInitializer: case SILDeclRef::Kind::IVarDestroyer: return nullptr; } llvm_unreachable("bad SILDeclRef kind"); } static AbstractionPattern getAbstractionPatternForConstant(ASTContext &ctx, SILDeclRef constant, CanAnyFunctionType fnType, unsigned uncurryLevel) { if (!constant.isForeign) return AbstractionPattern(fnType); auto bridgedFn = getBridgedFunction(constant); if (!bridgedFn) return AbstractionPattern(fnType); const clang::Decl *clangDecl = bridgedFn->getClangDecl(); if (!clangDecl) return AbstractionPattern(fnType); // Don't implicitly turn non-optional results to optional if // we're going to apply a foreign error convention that checks // for nil results. if (auto method = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) { assert(uncurryLevel == 1 && "getting curried ObjC method type?"); auto foreignError = bridgedFn->getForeignErrorConvention(); return AbstractionPattern::getCurriedObjCMethod(fnType, method, foreignError); } else if (auto value = dyn_cast<clang::ValueDecl>(clangDecl)) { if (uncurryLevel == 0) { // C function imported as a function. return AbstractionPattern(fnType, value->getType().getTypePtr()); } else { // C function imported as a method. assert(uncurryLevel == 1); return AbstractionPattern::getCurriedCFunctionAsMethod(fnType, bridgedFn); } } return AbstractionPattern(fnType); } TypeConverter::LoweredFormalTypes TypeConverter::getLoweredFormalTypes(SILDeclRef constant, CanAnyFunctionType fnType) { unsigned uncurryLevel = constant.getParameterListCount() - 1; auto extInfo = fnType->getExtInfo(); // Form an abstraction pattern for bridging purposes. // Foreign functions are only available at very specific uncurry levels. AbstractionPattern bridgingFnPattern = getAbstractionPatternForConstant(Context, constant, fnType, uncurryLevel); // Fast path: no uncurrying required. if (uncurryLevel == 0) { auto bridgedFnType = getBridgedFunctionType(bridgingFnPattern, fnType, extInfo); bridgingFnPattern.rewriteType(bridgingFnPattern.getGenericSignature(), bridgedFnType); return { bridgingFnPattern, bridgedFnType }; } SILFunctionTypeRepresentation rep = extInfo.getSILRepresentation(); assert(!extInfo.isAutoClosure() && "autoclosures cannot be curried"); assert(rep != SILFunctionType::Representation::Block && "objc blocks cannot be curried"); // The dependent generic signature. CanGenericSignature genericSig = fnType.getOptGenericSignature(); // The uncurried input types. SmallVector<TupleTypeElt, 4> inputs; // Merge inputs and generic parameters from the uncurry levels. for (;;) { auto canInput = fnType->getInput()->getCanonicalType(); auto inputFlags = ParameterTypeFlags().withInOut(isa<InOutType>(canInput)); inputs.push_back(TupleTypeElt(canInput->getInOutObjectType(), Identifier(), inputFlags)); // The uncurried function calls all of the intermediate function // levels and so throws if any of them do. if (fnType->getExtInfo().throws()) extInfo = extInfo.withThrows(); if (uncurryLevel-- == 0) break; fnType = cast<AnyFunctionType>(fnType.getResult()); } CanType resultType = fnType.getResult(); bool suppressOptionalResult = bridgingFnPattern.hasForeignErrorStrippingResultOptionality(); // Bridge input and result types. switch (rep) { case SILFunctionTypeRepresentation::Thin: case SILFunctionTypeRepresentation::Thick: case SILFunctionTypeRepresentation::Method: case SILFunctionTypeRepresentation::Closure: case SILFunctionTypeRepresentation::WitnessMethod: // Native functions don't need bridging. break; case SILFunctionTypeRepresentation::ObjCMethod: { assert(inputs.size() == 2); // The "self" parameter should not get bridged unless it's a metatype. if (inputs.front().getType()->is<AnyMetatypeType>()) { auto inputPattern = bridgingFnPattern.getFunctionInputType(); inputs[0] = inputs[0].getWithType( getBridgedInputType(rep, inputPattern, CanType(inputs[0].getType()))); } auto partialFnPattern = bridgingFnPattern.getFunctionResultType(); inputs[1] = inputs[1].getWithType( getBridgedInputType(rep, partialFnPattern.getFunctionInputType(), CanType(inputs[1].getType()))); resultType = getBridgedResultType(rep, partialFnPattern.getFunctionResultType(), resultType, suppressOptionalResult); break; } case SILFunctionTypeRepresentation::CFunctionPointer: { // A C function imported as a method. assert(inputs.size() == 2); // Bridge the parameters. auto partialFnPattern = bridgingFnPattern.getFunctionResultType(); inputs[1] = inputs[1].getWithType( getBridgedInputType(rep, partialFnPattern.getFunctionInputType(), CanType(inputs[1].getType()))); resultType = getBridgedResultType(rep, partialFnPattern.getFunctionResultType(), resultType, suppressOptionalResult); break; } case SILFunctionTypeRepresentation::Block: llvm_unreachable("Cannot uncurry native representation"); } // Put the inputs in the order expected by the calling convention. std::reverse(inputs.begin(), inputs.end()); auto buildFinalFunctionType = [&](CanType inputType, CanType resultType) -> CanAnyFunctionType { return CanAnyFunctionType::get(genericSig, inputType, resultType, extInfo); }; // Build the curried function type. CanType curriedResultType = resultType; for (auto input : llvm::makeArrayRef(inputs).drop_back()) { curriedResultType = CanFunctionType::get(CanType(input.getType()), curriedResultType); } auto curried = buildFinalFunctionType(CanType(inputs.back().getType()), curriedResultType); // Replace the type in the abstraction pattern with the type we just built. bridgingFnPattern.rewriteType(genericSig, curried); // Build the uncurried function type. CanType uncurriedInputType = TupleType::get(inputs, Context)->getCanonicalType(); auto uncurried = buildFinalFunctionType(uncurriedInputType, resultType); return { bridgingFnPattern, uncurried }; } // TODO: We should compare generic signatures. Class and witness methods // allow variance in "self"-fulfilled parameters; other functions must // match exactly. // TODO: More sophisticated param and return ABI compatibility rules could // diverge. static bool areABICompatibleParamsOrReturns(SILType a, SILType b) { // Address parameters are all ABI-compatible, though the referenced // values may not be. Assume whoever's doing this knows what they're // doing. if (a.isAddress() && b.isAddress()) return true; // Addresses aren't compatible with values. // TODO: An exception for pointerish types? if (a.isAddress() || b.isAddress()) return false; // Tuples are ABI compatible if their elements are. // TODO: Should destructure recursively. SmallVector<CanType, 1> aElements, bElements; if (auto tup = a.getAs<TupleType>()) { auto types = tup.getElementTypes(); aElements.append(types.begin(), types.end()); } else { aElements.push_back(a.getASTType()); } if (auto tup = b.getAs<TupleType>()) { auto types = tup.getElementTypes(); bElements.append(types.begin(), types.end()); } else { bElements.push_back(b.getASTType()); } if (aElements.size() != bElements.size()) return false; for (unsigned i : indices(aElements)) { auto aa = SILType::getPrimitiveObjectType(aElements[i]); auto bb = SILType::getPrimitiveObjectType(bElements[i]); // Equivalent types are always ABI-compatible. if (aa == bb) continue; // FIXME: If one or both types are dependent, we can't accurately assess // whether they're ABI-compatible without a generic context. We can // do a better job here when dependent types are related to their // generic signatures. if (aa.hasTypeParameter() || bb.hasTypeParameter()) continue; // Bridgeable object types are interchangeable. if (aa.isBridgeableObjectType() && bb.isBridgeableObjectType()) continue; // Optional and IUO are interchangeable if their elements are. auto aObject = aa.getOptionalObjectType(); auto bObject = bb.getOptionalObjectType(); if (aObject && bObject && areABICompatibleParamsOrReturns(aObject, bObject)) continue; // Optional objects are ABI-interchangeable with non-optionals; // None is represented by a null pointer. if (aObject && aObject.isBridgeableObjectType() && bb.isBridgeableObjectType()) continue; if (bObject && bObject.isBridgeableObjectType() && aa.isBridgeableObjectType()) continue; // Optional thick metatypes are ABI-interchangeable with non-optionals // too. if (aObject) if (auto aObjMeta = aObject.getAs<MetatypeType>()) if (auto bMeta = bb.getAs<MetatypeType>()) if (aObjMeta->getRepresentation() == bMeta->getRepresentation() && bMeta->getRepresentation() != MetatypeRepresentation::Thin) continue; if (bObject) if (auto aMeta = aa.getAs<MetatypeType>()) if (auto bObjMeta = bObject.getAs<MetatypeType>()) if (aMeta->getRepresentation() == bObjMeta->getRepresentation() && aMeta->getRepresentation() != MetatypeRepresentation::Thin) continue; // Function types are interchangeable if they're also ABI-compatible. if (auto aFunc = aa.getAs<SILFunctionType>()) { if (auto bFunc = bb.getAs<SILFunctionType>()) { // *NOTE* We swallow the specific error here for now. We will still get // that the function types are incompatible though, just not more // specific information. return aFunc->isABICompatibleWith(bFunc).isCompatible(); } } // Metatypes are interchangeable with metatypes with the same // representation. if (auto aMeta = aa.getAs<MetatypeType>()) { if (auto bMeta = bb.getAs<MetatypeType>()) { if (aMeta->getRepresentation() == bMeta->getRepresentation()) continue; } } // Other types must match exactly. return false; } return true; } namespace { using ABICompatibilityCheckResult = SILFunctionType::ABICompatibilityCheckResult; } // end anonymous namespace ABICompatibilityCheckResult SILFunctionType::isABICompatibleWith(CanSILFunctionType other) const { // The calling convention and function representation can't be changed. if (getRepresentation() != other->getRepresentation()) return ABICompatibilityCheckResult::DifferentFunctionRepresentations; // Check the results. if (getNumResults() != other->getNumResults()) return ABICompatibilityCheckResult::DifferentNumberOfResults; for (unsigned i : indices(getResults())) { auto result1 = getResults()[i]; auto result2 = other->getResults()[i]; if (result1.getConvention() != result2.getConvention()) return ABICompatibilityCheckResult::DifferentReturnValueConventions; if (!areABICompatibleParamsOrReturns(result1.getSILStorageType(), result2.getSILStorageType())) { return ABICompatibilityCheckResult::ABIIncompatibleReturnValues; } } // Our error result conventions are designed to be ABI compatible // with functions lacking error results. Just make sure that the // actual conventions match up. if (hasErrorResult() && other->hasErrorResult()) { auto error1 = getErrorResult(); auto error2 = other->getErrorResult(); if (error1.getConvention() != error2.getConvention()) return ABICompatibilityCheckResult::DifferentErrorResultConventions; if (!areABICompatibleParamsOrReturns(error1.getSILStorageType(), error2.getSILStorageType())) return ABICompatibilityCheckResult::ABIIncompatibleErrorResults; } // Check the parameters. // TODO: Could allow known-empty types to be inserted or removed, but SIL // doesn't know what empty types are yet. if (getParameters().size() != other->getParameters().size()) return ABICompatibilityCheckResult::DifferentNumberOfParameters; for (unsigned i : indices(getParameters())) { auto param1 = getParameters()[i]; auto param2 = other->getParameters()[i]; if (param1.getConvention() != param2.getConvention()) return {ABICompatibilityCheckResult::DifferingParameterConvention, i}; if (!areABICompatibleParamsOrReturns(param1.getSILStorageType(), param2.getSILStorageType())) return {ABICompatibilityCheckResult::ABIIncompatibleParameterType, i}; } // This needs to be checked last because the result implies everying else has // already been checked and this is the only difference. if (isNoEscape() != other->isNoEscape() && (getRepresentation() == SILFunctionType::Representation::Thick)) return ABICompatibilityCheckResult::ABIEscapeToNoEscapeConversion; return ABICompatibilityCheckResult::None; } StringRef SILFunctionType::ABICompatibilityCheckResult::getMessage() const { switch (kind) { case innerty::None: return "None"; case innerty::DifferentFunctionRepresentations: return "Different function representations"; case innerty::DifferentNumberOfResults: return "Different number of results"; case innerty::DifferentReturnValueConventions: return "Different return value conventions"; case innerty::ABIIncompatibleReturnValues: return "ABI incompatible return values"; case innerty::DifferentErrorResultConventions: return "Different error result conventions"; case innerty::ABIIncompatibleErrorResults: return "ABI incompatible error results"; case innerty::DifferentNumberOfParameters: return "Different number of parameters"; // These two have to do with specific parameters, so keep the error message // non-plural. case innerty::DifferingParameterConvention: return "Differing parameter convention"; case innerty::ABIIncompatibleParameterType: return "ABI incompatible parameter type."; case innerty::ABIEscapeToNoEscapeConversion: return "Escape to no escape conversion"; } llvm_unreachable("Covered switch isn't completely covered?!"); }
// SoundFactory.cpp: implementation of the SoundFactory class. // ////////////////////////////////////////////////////////////////////// #include "SoundFactory.h" #include "drivers/null/NullSoundEngine.h" #include "drivers/sfml/SFMLSoundEngine.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// SoundEngine* SoundFactory::singletonInstance=0; SoundFactory::SoundFactory() { } SoundFactory::~SoundFactory() { } /** * Returns the single instance of Null Sample Engine class. */ SoundEngine* SoundFactory::getInstance(int driverID) { // check if we have an instance if (singletonInstance==0) { // create new instance depending on capabilities switch (driverID) { case 3: singletonInstance = new SFMLSoundEngine(); break; default: singletonInstance = new NullSoundEngine(); break; } } singletonInstance->init(); return singletonInstance; }
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "jit/x86/Assembler-x86.h" #include "gc/Marking.h" using namespace js; using namespace js::jit; ABIArgGenerator::ABIArgGenerator() : stackOffset_(0), current_() {} ABIArg ABIArgGenerator::next(MIRType type) { switch (type) { case MIRType_Int32: case MIRType_Pointer: current_ = ABIArg(stackOffset_); stackOffset_ += sizeof(uint32_t); break; case MIRType_Float32: // Float32 moves are actually double moves case MIRType_Double: current_ = ABIArg(stackOffset_); stackOffset_ += sizeof(uint64_t); break; case MIRType_Int32x4: case MIRType_Float32x4: // SIMD values aren't passed in or out of C++, so we can make up // whatever internal ABI we like. visitAsmJSPassArg assumes // SimdMemoryAlignment. stackOffset_ = AlignBytes(stackOffset_, SimdMemoryAlignment); current_ = ABIArg(stackOffset_); stackOffset_ += Simd128DataSize; break; default: MOZ_CRASH("Unexpected argument type"); } return current_; } const Register ABIArgGenerator::NonArgReturnReg0 = ecx; const Register ABIArgGenerator::NonArgReturnReg1 = edx; const Register ABIArgGenerator::NonVolatileReg = ebx; const Register ABIArgGenerator::NonArg_VolatileReg = eax; const Register ABIArgGenerator::NonReturn_VolatileReg0 = ecx; void Assembler::executableCopy(uint8_t* buffer) { AssemblerX86Shared::executableCopy(buffer); for (size_t i = 0; i < jumps_.length(); i++) { RelativePatch& rp = jumps_[i]; X86Encoding::SetRel32(buffer + rp.offset, rp.target); } } class RelocationIterator { CompactBufferReader reader_; uint32_t offset_; public: RelocationIterator(CompactBufferReader& reader) : reader_(reader) { } bool read() { if (!reader_.more()) return false; offset_ = reader_.readUnsigned(); return true; } uint32_t offset() const { return offset_; } }; static inline JitCode* CodeFromJump(uint8_t* jump) { uint8_t* target = (uint8_t*)X86Encoding::GetRel32Target(jump); return JitCode::FromExecutable(target); } void Assembler::TraceJumpRelocations(JSTracer* trc, JitCode* code, CompactBufferReader& reader) { RelocationIterator iter(reader); while (iter.read()) { JitCode* child = CodeFromJump(code->raw() + iter.offset()); MarkJitCodeUnbarriered(trc, &child, "rel32"); MOZ_ASSERT(child == CodeFromJump(code->raw() + iter.offset())); } } uint32_t FloatRegister::GetSizeInBytes(const FloatRegisterSet& s) { uint32_t ret = s.size() * sizeof(double); return ret; } FloatRegisterSet FloatRegister::ReduceSetForPush(const FloatRegisterSet& s) { return s; } uint32_t FloatRegister::GetPushSizeInBytes(const FloatRegisterSet& s) { return s.size() * sizeof(double); } uint32_t FloatRegister::getRegisterDumpOffsetInBytes() { return code() * sizeof(double); }
// nanorange/iterator/istream_iterator.hpp // // Copyright (c) 2018 Tristan Brindle (tcbrindle at gmail 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 NANORANGE_ITERATOR_ISTREAM_ITERATOR_HPP_INCLUDED #define NANORANGE_ITERATOR_ISTREAM_ITERATOR_HPP_INCLUDED #include <nanorange/iterator/default_sentinel.hpp> #include <nanorange/detail/iterator/traits.hpp> #include <iosfwd> NANO_BEGIN_NAMESPACE template <typename T, typename CharT = char, typename Traits = std::char_traits<CharT>, typename Distance = std::ptrdiff_t> class istream_iterator { public: using iterator_category = input_iterator_tag; using difference_type = Distance; using value_type = T; using reference = const T&; using pointer = const T*; using char_type = CharT; using traits_type = Traits; using istream_type = std::basic_istream<CharT, Traits>; constexpr istream_iterator() = default; constexpr istream_iterator(default_sentinel) {} istream_iterator(istream_type& s) : in_stream_(std::addressof(s)) { s >> value_; } istream_iterator(const istream_iterator& x) = default; ~istream_iterator() = default; const T& operator*() const { return value_; } const T* operator->() const { return std::addressof(value_); } istream_iterator& operator++() { *in_stream_ >> value_; if (in_stream_->fail()) { in_stream_ = nullptr; } return *this; } istream_iterator operator++(int) { istream_iterator tmp = *this; this->operator++(); return tmp; } friend bool operator==(const istream_iterator& x, const istream_iterator& y) { return x.in_stream_ == y.in_stream_; } friend bool operator==(default_sentinel, const istream_iterator y) { return nullptr == y.in_stream_; } friend bool operator==(const istream_iterator& x, default_sentinel) { return x.in_stream_ == nullptr; } friend bool operator!=(const istream_iterator& x, const istream_iterator& y) { return !(x == y); } friend bool operator!=(default_sentinel x, const istream_iterator y) { return !(x == y); } friend bool operator!=(const istream_iterator& x, default_sentinel y) { return !(x == y); } private: istream_type* in_stream_ = nullptr; T value_{}; }; NANO_END_NAMESPACE #endif
#include <iostream> using namespace std; double divide(double x, double y) throw(int) { if (y == 0) throw 0; return x / y; } int main() { try { cout << divide(10, 2) << endl; cout << divide(10, 0) << endl; cout << divide(10, 5) << endl; } catch (int i) { cout << "divide by zero" << endl; } cout << "Hello World" << endl; return 0; }
#pragma once #ifdef PLATE_WEBGL #include "webgl/shaders/object_instanced/shader.hpp" #endif #ifdef PLATE_LINUX_GL #include "gl/shaders/object_instanced/shader.hpp" #endif #ifdef PLATE_LINUX_VULKAN #include "vulkan/shaders/object_instanced/shader.hpp" #endif
/** Copyright 2009-2020 National Technology and Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government retains certain rights in this software. Sandia National Laboratories is a multimission laboratory managed and operated by National Technology and Engineering Solutions of Sandia, LLC., a wholly owned subsidiary of Honeywell International, Inc., for the U.S. Department of Energy's National Nuclear Security Administration under contract DE-NA0003525. Copyright (c) 2009-2020, NTESS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. Questions? Contact sst-macro-help@sandia.gov */ #include "testglobals.cc"
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "network/message.hpp" #include "fetch_pybind.hpp"
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #include <iostream> #include <sstream> #include <vector> #include <cstring> #include <unistd.h> #include <mpi.h> #include "galois/Timer.h" volatile int cont = 0; int main(int argc, char** argv) { int trials = 1000000; if (argc > 1) trials = atoi(argv[1]); int provided; MPI_Init_thread(NULL, NULL, MPI_THREAD_FUNNELED, &provided); int numTasks, taskRank; MPI_Comm_size(MPI_COMM_WORLD, &numTasks); MPI_Comm_rank(MPI_COMM_WORLD, &taskRank); if (numTasks != 2) { std::cerr << "Just run with 2 hosts\n"; return 1; } // while (!cont) {} for (int s = 10; s < trials; s *= 1.1) { std::vector<char> vec(s); galois::Timer T1, T2, T3; MPI_Barrier(MPI_COMM_WORLD); T3.start(); T1.start(); T1.stop(); MPI_Barrier(MPI_COMM_WORLD); T2.start(); MPI_Status status; if (taskRank == 0) { MPI_Request cur; MPI_Isend(vec.data(), vec.size(), MPI_BYTE, 1, 0, MPI_COMM_WORLD, &cur); int flag; do { MPI_Test(&cur, &flag, &status); } while (!flag); } else { int nbytes, flag; do { MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status); } while (!flag); MPI_Get_count(&status, MPI_CHAR, &nbytes); MPI_Recv(vec.data(), nbytes, MPI_BYTE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, &status); } T2.stop(); MPI_Barrier(MPI_COMM_WORLD); T3.stop(); MPI_Barrier(MPI_COMM_WORLD); std::cerr << "H" << taskRank << " size " << s << " T1 " << T1.get() << " T2 " << T2.get() << " T3 " << T3.get() << " B " << (T3.get() ? (s / (T3.get() - T1.get())) : 0.0) << "\n"; MPI_Barrier(MPI_COMM_WORLD); } return 0; }
#ifndef CLICK_PROTOCOLTRANSLATOR64_HH #define CLICK_PROTOCOLTRANSLATOR64_HH #include <click/ip6address.hh> #include <click/ipaddress.hh> #include <click/vector.hh> #include <click/element.hh> CLICK_DECLS /* * =c * ProtocolTranslator64() * * * =s ip6 * translate IP/ICMP, TCP, and UDP packets from the IPv6 to the IPv4 protocol * * =d * * * Has one input and one output. Input packets are valid IPv6 packets. IPv6 * packets will be translated to IPv4 packets. Output packets are valid * IPv4 packets; for instance, translated packets have their IP, ICMP, * TCP and/or UDP checksums updated. * * * =a AddressTranslator ProtocolTranslator46*/ class ProtocolTranslator64 : public Element { public: ProtocolTranslator64(); ~ProtocolTranslator64(); const char *class_name() const { return "ProtocolTranslator64"; } const char *port_count() const { return PORTS_1_1; } void push(int port, Packet *p); void handle_ip6(Packet *); private: Packet * make_icmp_translate64(unsigned char *a, unsigned char payload_length); Packet * make_translate64(IPAddress src, IPAddress dst, click_ip6 * ip6, unsigned char *a); }; CLICK_ENDDECLS #endif
// Copyright (c) 2013-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. // Unit tests for alert system #include "alert.h" #include "chain.h" #include "chainparams.h" #include "clientversion.h" #include "data/alertTests.raw.h" #include "main.h" // For PartitionCheck #include "serialize.h" #include "streams.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_neodash.h" #include <fstream> #include <boost/filesystem/operations.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #if 0 // // alertTests contains 7 alerts, generated with this code: // (SignAndSave code not shown, alert signing key is secret) // { CAlert alert; alert.nRelayUntil = 60; alert.nExpiration = 24 * 60 * 60; alert.nID = 1; alert.nCancel = 0; // cancels previous messages up to this ID number alert.nMinVer = 0; // These versions are protocol versions alert.nMaxVer = 999001; alert.nPriority = 1; alert.strComment = "Alert comment"; alert.strStatusBar = "Alert 1"; SignAndSave(alert, "test/alertTests"); alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0"; SignAndSave(alert, "test/alertTests"); alert.setSubVer.insert(std::string("/Satoshi:0.2.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0"; SignAndSave(alert, "test/alertTests"); alert.setSubVer.clear(); ++alert.nID; alert.nCancel = 1; alert.nPriority = 100; alert.strStatusBar = "Alert 2, cancels 1"; SignAndSave(alert, "test/alertTests"); alert.nExpiration += 60; ++alert.nID; SignAndSave(alert, "test/alertTests"); ++alert.nID; alert.nMinVer = 11; alert.nMaxVer = 22; SignAndSave(alert, "test/alertTests"); ++alert.nID; alert.strStatusBar = "Alert 2 for Satoshi 0.1.0"; alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); SignAndSave(alert, "test/alertTests"); ++alert.nID; alert.nMinVer = 0; alert.nMaxVer = 999999; alert.strStatusBar = "Evil Alert'; /bin/ls; echo '"; alert.setSubVer.clear(); SignAndSave(alert, "test/alertTests"); } #endif struct ReadAlerts : public TestingSetup { ReadAlerts() { std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests)); CDataStream stream(vch, SER_DISK, CLIENT_VERSION); try { while (!stream.eof()) { CAlert alert; stream >> alert; alerts.push_back(alert); } } catch (const std::exception&) { } } ~ReadAlerts() { } static std::vector<std::string> read_lines(boost::filesystem::path filepath) { std::vector<std::string> result; std::ifstream f(filepath.string().c_str()); std::string line; while (std::getline(f,line)) result.push_back(line); return result; } std::vector<CAlert> alerts; }; BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts) BOOST_AUTO_TEST_CASE(AlertApplies) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); BOOST_FOREACH(const CAlert& alert, alerts) { BOOST_CHECK(alert.CheckSignature(alertKey)); } BOOST_CHECK(alerts.size() >= 3); // Matches: BOOST_CHECK(alerts[0].AppliesTo(1, "")); BOOST_CHECK(alerts[0].AppliesTo(999001, "")); BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/")); BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/")); // Don't match: BOOST_CHECK(!alerts[0].AppliesTo(-1, "")); BOOST_CHECK(!alerts[0].AppliesTo(999002, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/")); BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/")); SetMockTime(0); } BOOST_AUTO_TEST_CASE(AlertNotify) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); boost::filesystem::path temp = GetTempPath() / boost::filesystem::unique_path("alertnotify-%%%%.txt"); mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string(); BOOST_FOREACH(CAlert alert, alerts) alert.ProcessAlert(alertKey, false); std::vector<std::string> r = read_lines(temp); BOOST_CHECK_EQUAL(r.size(), 4u); // Windows built-in echo semantics are different than posixy shells. Quotes and // whitespace are printed literally. #ifndef WIN32 BOOST_CHECK_EQUAL(r[0], "Alert 1"); BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed #else BOOST_CHECK_EQUAL(r[0], "'Alert 1' "); BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' "); #endif boost::filesystem::remove(temp); SetMockTime(0); } static bool falseFunc() { return false; } BOOST_AUTO_TEST_CASE(PartitionAlert) { // Test PartitionCheck CCriticalSection csDummy; CBlockIndex indexDummy[100]; CChainParams& params = Params(CBaseChainParams::MAIN); int64_t nPowTargetSpacing = params.GetConsensus().nPowTargetSpacing; // Generate fake blockchain timestamps relative to // an arbitrary time: int64_t now = 1427379054; SetMockTime(now); for (int i = 0; i < 100; i++) { indexDummy[i].phashBlock = NULL; if (i == 0) indexDummy[i].pprev = NULL; else indexDummy[i].pprev = &indexDummy[i-1]; indexDummy[i].nHeight = i; indexDummy[i].nTime = now - (100-i)*nPowTargetSpacing; // Other members don't matter, the partition check code doesn't // use them } strMiscWarning = ""; // Test 1: chain with blocks every nPowTargetSpacing seconds, // as normal, no worries: PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK_MESSAGE(strMiscWarning.empty(), strMiscWarning); // Test 2: go 52.5 minutes without a block, expect a warning: now += (3*60*60+30*60)/4; // we have 4x faster blocks SetMockTime(now); PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK(!strMiscWarning.empty()); BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning); strMiscWarning = ""; // Test 3: test the "partition alerts only go off once per day" // code: now += 60*10; SetMockTime(now); PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK(strMiscWarning.empty()); // Test 4: get 2.5 times as many blocks as expected: now += 60*60*24; // Pretend it is a day later SetMockTime(now); int64_t quickSpacing = nPowTargetSpacing*2/5; for (int i = 0; i < 100; i++) // Tweak chain timestamps: indexDummy[i].nTime = now - (100-i)*quickSpacing; PartitionCheck(falseFunc, csDummy, &indexDummy[99], nPowTargetSpacing); BOOST_CHECK(!strMiscWarning.empty()); BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning); strMiscWarning = ""; SetMockTime(0); } BOOST_AUTO_TEST_SUITE_END()
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include<iostream> #include "Huobi/HuobiClient.h" using namespace Huobi; using namespace std; int main(int argc, char** argv) { /** * Get exchangeInfo : include huobi supports currencies and symbols */ // RequestOptions options; // options.url = "https://api-cloud.huobi.co.kr"; options RequestClient* client = createRequestClient(); ExchangeInfo exchangeInfo = client->getExchangeInfo(); cout << "---- Supported symbols ----" << endl; for (Symbols symbols : exchangeInfo.symbolsList) { cout << symbols.symbol << endl; } cout << "---- Supported currencies ----" << endl; for (std::string currency : exchangeInfo.currencies) { cout << currency << endl; } /** * Get symbols. */ vector<Symbols> symbolVec = client->getSymbols(); cout << "---- Supported symbols ----" << endl; for (Symbols symbols : symbolVec) { cout << symbols.symbol << endl; } /** * Get currencies. */ vector<string> currencies = client->getCurrencies(); cout << "---- Supported currencies ----" << endl; for (std::string currency : currencies) { cout << currency << endl; } }
#include <iostream> //std::cout #include <array> //std::array int solve_wk(int num) { std::array<int,8> slice{{1, 1, 1, 1, 1, 1, 1, 1}}; std::array<int,8> offsets{{1, 2, 3, 4, 5, 6, 7, 8}}; for (int disp = 1; true; ++disp) { for (int i = 0; i < 8; ++i) { slice[i] += offsets[i]; if (slice[i] >= num) return (disp + (num - slice[(i + 7) & 0x7])); offsets[i] += 8; } } } int main(int argc, char ** argv) { int num = 361527; std::cout<<solve_wk(num)<<std::endl; return 0; }
// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/betchip-config.h> #endif #include <qt/splashscreen.h> #include <qt/networkstyle.h> #include <clientversion.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <interfaces/wallet.h> #include <util.h> #include <ui_interface.h> #include <version.h> #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> #include <QRadialGradient> SplashScreen::SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0), m_node(node) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; float devicePixelRatio = 1.0; #if QT_VERSION > 0x050100 devicePixelRatio = static_cast<QGuiApplication*>(QCoreApplication::instance())->devicePixelRatio(); #endif // define text to place QString titleText = tr(PACKAGE_NAME); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QString::fromUtf8(CopyrightHolders(strprintf("\xc2\xA9 %u-%u ", 2009, COPYRIGHT_YEAR)).c_str()); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // create a bitmap according to device pixelratio QSize splashSize(480*devicePixelRatio,320*devicePixelRatio); pixmap = QPixmap(splashSize); #if QT_VERSION > 0x050100 // change to HiDPI if it makes sense pixmap.setDevicePixelRatio(devicePixelRatio); #endif QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // draw a slightly radial gradient QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, QColor(247,247,247)); QRect rGradient(QPoint(0,0), splashSize); pixPaint.fillRect(rGradient, gradient); // draw the betchip icon, expected size of PNG: 1024x1024 QRect rectIcon(QPoint(-150,-122), QSize(430,430)); const QSize requiredSize(1024,1024); QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize)); pixPaint.drawPixmap(rectIcon, icon); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 176) { fontFactor = fontFactor * 176 / titleTextWidth; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is too long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff { pixPaint.setFont(QFont(font, 10*fontFactor)); const int x = pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight; const int y = paddingTop+titleCopyrightVSpace; QRect copyrightRect(x, y, pixmap.width() - x - paddingRight, pixmap.height() - y); pixPaint.drawText(copyrightRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, copyrightText); } // 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()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio)); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); installEventFilter(this); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } bool SplashScreen::eventFilter(QObject * obj, QEvent * ev) { if (ev->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev); if(keyEvent->text()[0] == 'q') { m_node.startShutdown(); } } return QObject::eventFilter(obj, ev); } 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, bool resume_possible) { InitMessage(splash, title + std::string("\n") + (resume_possible ? _("(press q to shutdown and continue later)") : _("press q to shutdown")) + strprintf("\n%d", nProgress) + "%"); } #ifdef ENABLE_WALLET void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet) { m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(boost::bind(ShowProgress, this, _1, _2, false))); m_connected_wallets.emplace_back(std::move(wallet)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client m_handler_init_message = m_node.handleInitMessage(boost::bind(InitMessage, this, _1)); m_handler_show_progress = m_node.handleShowProgress(boost::bind(ShowProgress, this, _1, _2, _3)); #ifdef ENABLE_WALLET m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { ConnectWallet(std::move(wallet)); }); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client m_handler_init_message->disconnect(); m_handler_show_progress->disconnect(); for (auto& handler : m_connected_wallet_handlers) { handler->disconnect(); } m_connected_wallet_handlers.clear(); m_connected_wallets.clear(); } 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) { m_node.startShutdown(); // allows an "emergency" shutdown during startup event->ignore(); }
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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 <Pegasus/Common/Config.h> #include <Pegasus/Common/String.h> #include <Pegasus/Common/PegasusVersion.h> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; #include "UNIX_NotaryProvider.h" extern "C" PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName) { if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL; else if (String::equalNoCase(providerName, "UNIX_NotaryProvider")) return new UNIX_NotaryProvider(); return NULL; }
#ifndef ACPL_I18N_CHARSETS_CHARSET_ISO_8859_1_1998_INC_CPP #define ACPL_I18N_CHARSETS_CHARSET_ISO_8859_1_1998_INC_CPP // WARNING: Do not modify this file because it was generated using i18nproc #include "../../Charsets.h" #include "../../_cp/Memory.inc.cpp" namespace acpl { namespace i18n { class Charset_ISO_8859_1_1998 { public: static inline bool IsCompatible(const char *nMimeName, acpl::Charsets::ByteOrderMask nBom, acpl::Charsets::Fpc &nFpc) { if (nMimeName != NULL && acpl::pi::_string_ascii_strcasecmp(nMimeName, "ISO-8859-1") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "ISO_8859-1") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "latin1") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "l1") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "IBM819") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "CP819") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "iso-ir-100") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "csISOLatin1") != 0) return false; if (nBom != acpl::Charsets::bomNone) return false; nFpc.Set( IsCompatible, GetMimeName, IsBomSuggested, CreateBom, MinSeqSize, MaxSeqSize, Decode, Encode ); return true; } static inline const char *GetMimeName() { return "ISO-8859-1"; } static inline bool IsBomSuggested() { return false; } static inline acpl::SizeT CreateBom(acpl::UInt8 *, acpl::SizeT) { return 0; } static inline acpl::SizeT MinSeqSize() { return 1; } static inline acpl::SizeT MaxSeqSize() { return 1; } static inline acpl::SizeT Decode(const acpl::UInt8 *nBfr, acpl::SizeT nBfrSize, acpl::Unichar &nUnicodeChar) { if (nBfrSize >= 1) { nUnicodeChar = static_cast<acpl::Unichar>(*nBfr); return 1; } return 0; } static inline acpl::SizeT Encode(acpl::Unichar nUnicodeChar, acpl::UInt8 *nBfr, acpl::SizeT nBfrSize) { if (nBfrSize >= 1) { if (nUnicodeChar <= 0xFF) { *nBfr = static_cast<acpl::UInt8>(nUnicodeChar); return 1; } } return 0; } }; } } #endif // ACPL_I18N_CHARSETS_CHARSET_ISO_8859_1_1998_INC_CPP
// Copyright (C) 2010 James Turner - zakalawe@mac.com // // 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 General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifdef HAVE_CONFIG_H # include "simgear_config.h" #endif #include "propertyObject.hxx" // #include <simgear/structure/exception.hxx> namespace simgear { SGPropertyNode* static_defaultRoot = NULL; void PropertyObjectBase::setDefaultRoot(SGPropertyNode* aRoot) { static_defaultRoot = aRoot; } PropertyObjectBase::PropertyObjectBase() : _path(NULL), _prop(NULL) { } PropertyObjectBase::PropertyObjectBase(const PropertyObjectBase& aOther) : _path(aOther._path), _prop(aOther._prop) { } PropertyObjectBase::PropertyObjectBase(const char* aChild) : _path(aChild), _prop(NULL) { } PropertyObjectBase::PropertyObjectBase(SGPropertyNode* aNode, const char* aChild) : _path(aChild), _prop(aNode) { } SGPropertyNode* PropertyObjectBase::node(bool aCreate) const { if (_path == NULL) { // already resolved return _prop; } SGPropertyNode *r = _prop ? _prop : static_defaultRoot, *prop = r->getNode(_path, aCreate); if( prop ) { // resolve worked, we will cache from now on, so clear _path and cache prop _path = NULL; _prop = prop; } return prop; } SGPropertyNode* PropertyObjectBase::getOrThrow() const { SGPropertyNode* n = node(false); if (!n) { std::string path; if (_prop) { path = _prop->getPath(); if (_path) { path += '/'; } } if (_path) { path += _path; } throw("Unknown property:" + path); } return n; } } // of namespace simgear
#include "FEM_interface.h" #include "GL/glut.h" using namespace FEM; void GUI:: DrawWorld(const std::shared_ptr<World>& world) { const Eigen::VectorXd& X = world->GetPositions(); const auto& cs = world->GetConstraints(); for(const auto& c : cs) DrawConstraint(c, X); } void GUI:: DrawConstraint(const std::shared_ptr<Cst>& c,const Eigen::VectorXd& x) { glDisable(GL_LIGHTING); if(dynamic_cast<AttachmentCst*>(c.get()) != nullptr) { AttachmentCst* ac = dynamic_cast<AttachmentCst*>(c.get()); int i0 = ac->GetI0(); const Eigen::Vector3d& p = ac->GetP(); glLineWidth(3.0); GUI::DrawLine(x.block<3,1>(i0*3,0),p,Eigen::Vector3d(0.8,0,0)); glLineWidth(1.0); } else if(dynamic_cast<CorotateFEMCst*>(c.get()) != nullptr) { CorotateFEMCst* cc = dynamic_cast<CorotateFEMCst*>(c.get()); int i0 = cc->GetI0(); int i1 = cc->GetI1(); int i2 = cc->GetI2(); int i3 = cc->GetI3(); const Eigen::Vector3d& p0 = x.block<3,1>(i0*3,0); const Eigen::Vector3d& p1 = x.block<3,1>(i1*3,0); const Eigen::Vector3d& p2 = x.block<3,1>(i2*3,0); const Eigen::Vector3d& p3 = x.block<3,1>(i3*3,0); GUI::DrawTetrahedron(p0,p1,p2,p3); glLineWidth(2.0); GUI::DrawLine(p0,p1,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p0,p2,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p0,p3,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p1,p2,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p1,p3,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p2,p3,Eigen::Vector3d(0,0,0)); glLineWidth(1.0); } else if(dynamic_cast<LinearMuscleCst*>(c.get()) != nullptr) { LinearMuscleCst* cc = dynamic_cast<LinearMuscleCst*>(c.get()); int i0 = cc->GetI0(); int i1 = cc->GetI1(); int i2 = cc->GetI2(); int i3 = cc->GetI3(); double a = cc->GetActivationLevel(); const Eigen::Vector3d& p0 = x.block<3,1>(i0*3,0); const Eigen::Vector3d& p1 = x.block<3,1>(i1*3,0); const Eigen::Vector3d& p2 = x.block<3,1>(i2*3,0); const Eigen::Vector3d& p3 = x.block<3,1>(i3*3,0); GUI::DrawTetrahedron(p0,p1,p2,p3,Eigen::Vector3d(0.8,0.8-0.3*a,0.8-0.3*a)); glLineWidth(2.0); GUI::DrawLine(p0,p1,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p0,p2,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p0,p3,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p1,p2,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p1,p3,Eigen::Vector3d(0,0,0)); GUI::DrawLine(p2,p3,Eigen::Vector3d(0,0,0)); glLineWidth(1.0); } glEnable(GL_LIGHTING); }
#include "StdAfx.h" #include "LevelsManager.h" CLevelsManager::CLevelsManager() { m_cFileName[ 0 ] = 0; m_pShipsManager = new CShipsManager(); if( m_pShipsManager ) m_pShipsManager->LoadUniqueShips( NULL ); } CLevelsManager::~CLevelsManager() { ClearLevels(); delete m_pShipsManager; } void CLevelsManager::ConvertStruct() { //funkcja podmieniajaca pliki ze starej struktury na nowa //odczytanie starej struktury //przepisanie starej struktury na nowa //zapisanie nowej struktury std::vector< SLevelOld > aOldLevels; FILE *hFile = NULL; SLevelOld sOldLevels; ::wcscpy_s( m_cFileName, 255, FILE_NAME_LEVEL_EDIT2 ); errno_t error = _wfopen_s( &hFile, m_cFileName, _T("rb") ); if( error != 0 ) { wxString strMsg; strMsg.Printf( _T("ConvertStruct: open file error: %d"), error ); wxMessageBox( strMsg, _T("Error"), wxOK | wxICON_ERROR ); return; } while( fread( &sOldLevels, sizeof( SLevelOld ), 1, hFile ) != NULL ) { aOldLevels.push_back( sOldLevels ); int iIndex = static_cast<int>( aOldLevels.size() ) - 1; if( aOldLevels[ iIndex ].iNumberGroups > 0 ) { aOldLevels[ iIndex ].psShipsGroups = new SShipsGroups[ aOldLevels[ iIndex ].iNumberGroups ]; for( int i = 0; i < aOldLevels[ iIndex ].iNumberGroups; ++i ) { fread( &aOldLevels[ iIndex ].psShipsGroups[ i ], sizeof( SShipsGroups ), 1, hFile ); } } else aOldLevels[ iIndex ].psShipsGroups = NULL; } fclose( hFile ); ClearLevels(); //przepisanie tablic - stara na nowa SLevel sLevel; for( int i = 0; i < static_cast<int>( aOldLevels.size() ); ++i ) { ////////////////////////////////////////////////////////////////////////// ///////nowe wartosci inicjalizujemy, a nie przypisujemy ze starej///////// ////////////////////////////////////////////////////////////////////////// sLevel.iIndexBoss = -1; //nowe sLevel.iBossReserve1 = 0; //nowe sLevel.iBossReserve2 = 0; //nowe sLevel.iBossReserve3 = 0; //nowe ////////////////////////////////////////////////////////////////////////// sLevel.iLevel = aOldLevels[ i ].iLevel; sLevel.iMaxShipsOnScreen = aOldLevels[ i ].iMaxShipsOnScreen; sLevel.iFrequencyShoot = aOldLevels[ i ].iFrequencyShoot; sLevel.iPercentChanceToShoot = aOldLevels[ i ].iPercentChanceToShoot; sLevel.iNumberGroups = aOldLevels[ i ].iNumberGroups; m_aLevels.push_back( sLevel ); if( aOldLevels[ i ].iNumberGroups <= 0 ) { m_aLevels[ i ].iNumberGroups = 0; m_aLevels[ i ].psShipsGroups = NULL; } else { m_aLevels[ i ].psShipsGroups = new SShipsGroups[ m_aLevels[ i ].iNumberGroups ]; for( int j = 0; j < aOldLevels[ i ].iNumberGroups; ++j ) { m_aLevels[ i ].psShipsGroups[ j ].iIndexShip = aOldLevels[ i ].psShipsGroups[ j ].iIndexShip; m_aLevels[ i ].psShipsGroups[ j ].iNumberShips = aOldLevels[ i ].psShipsGroups[ j ].iNumberShips; m_aLevels[ i ].psShipsGroups[ j ].iFormation = aOldLevels[ i ].psShipsGroups[ j ].iFormation; m_aLevels[ i ].psShipsGroups[ j ].iPosXForRand = aOldLevels[ i ].psShipsGroups[ j ].iPosXForRand; m_aLevels[ i ].psShipsGroups[ j ].fSpeed = aOldLevels[ i ].psShipsGroups[ j ].fSpeed; m_aLevels[ i ].psShipsGroups[ j ].bCosFly = aOldLevels[ i ].psShipsGroups[ j ].bCosFly; m_aLevels[ i ].psShipsGroups[ j ].bSlantFly = aOldLevels[ i ].psShipsGroups[ j ].bSlantFly; m_aLevels[ i ].psShipsGroups[ j ].fOffsetXPosForSlantFly = aOldLevels[ i ].psShipsGroups[ j ].fOffsetXPosForSlantFly; } } } //zapisanie SaveAllLevels(); } bool CLevelsManager::LoadLevels( LPCTSTR lpFileName ) { ClearLevels(); FILE *hFile; if( lpFileName == NULL ) wcscpy_s( m_cFileName, 255, FILE_NAME_LEVEL_EDIT2 ); else wcscpy_s( m_cFileName, 255, lpFileName ); errno_t error = _wfopen_s( &hFile, m_cFileName, _T("rb") ); if( error != 0 ) { wxString str; str.Printf( _T("LoadLevels - Open file: %s failed"), m_cFileName ); wxMessageBox( str, _T("Error"), wxOK | wxICON_ERROR ); return false; } SLevel sLevel; while( fread( &sLevel, sizeof( SLevel ), 1, hFile ) != NULL ) { m_aLevels.push_back( sLevel ); int iIndex = GetLevelsSize() - 1; if( m_aLevels[ iIndex ].iNumberGroups > 0 ) { m_aLevels[ iIndex ].psShipsGroups = new SShipsGroups[ m_aLevels[ iIndex ].iNumberGroups ]; for( int i = 0; i < m_aLevels[ iIndex ].iNumberGroups; ++i ) { fread( &m_aLevels[ iIndex ].psShipsGroups[ i ], sizeof( SShipsGroups ), 1, hFile ); } } else m_aLevels[ iIndex ].psShipsGroups = NULL; } fclose( hFile ); return true; } void CLevelsManager::ClearLevels() { for( int i = GetLevelsSize() - 1; i >= 0; --i ) { if( m_aLevels[ i ].psShipsGroups ) delete [] m_aLevels[ i ].psShipsGroups; } m_aLevels.clear(); } bool CLevelsManager::SaveLevel( const SLevel &sLevel ) { FILE *hFile; errno_t error = _wfopen_s( &hFile, m_cFileName, _T("ab") ); if( error != 0 ) { wxString str; str.Printf( _T("SaveLevel - Open file: %s failed"), m_cFileName ); wxMessageBox( str, _T("Error"), wxOK | wxICON_ERROR ); return false; } fwrite( &sLevel, sizeof( SLevel ), 1, hFile ); for( int i = 0; i < sLevel.iNumberGroups; ++i ) fwrite( &sLevel.psShipsGroups[ i ], sizeof( SShipsGroups ), 1, hFile ); fclose( hFile ); return true; } bool CLevelsManager::SaveAllLevels() { FILE *hFile; errno_t error = _wfopen_s( &hFile, m_cFileName, _T("wb") ); if( error != 0 ) { wxString str; str.Printf( _T("SaveAllLevels - Open file: %s failed"), m_cFileName ); wxMessageBox( str, _T("Error"), wxOK | wxICON_ERROR ); return false; } for( int i = 0; i < GetLevelsSize(); ++i ) { fwrite( &m_aLevels[ i ], sizeof( SLevel ), 1, hFile ); for( int j = 0; j < m_aLevels[ i ].iNumberGroups; ++j ) { fwrite( &m_aLevels[ i ].psShipsGroups[ j ], sizeof( SShipsGroups ), 1, hFile ); } } fclose( hFile ); return true; } bool CLevelsManager::MoveUpIndex( int iIndex ) { if( iIndex < 0 || iIndex >= GetLevelsSize() ) { wxMessageBox( _T("MoveDownIndex: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } //strwadz czy aktualna pozycja nie jest pierwsza if( iIndex == 0 ) { wxMessageBox( _T("This index is first"), _T("Exclamation"), wxOK | wxICON_EXCLAMATION ); return false; } SLevel sTempLevel; memset( &sTempLevel, 0, sizeof( SLevel ) ); CopyLevel( sTempLevel, m_aLevels[ iIndex ] ); CopyLevel( m_aLevels[ iIndex ], m_aLevels[ iIndex - 1 ] ); CopyLevel( m_aLevels[ iIndex - 1 ], sTempLevel ); SaveAllLevels(); return true; } bool CLevelsManager::MoveDownIndex( int iIndex ) { if( iIndex < 0 || iIndex >= GetLevelsSize() ) { wxMessageBox( _T("MoveDownIndex: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } //strwadz czy aktualna pozycja nie jest ostatnia if( iIndex == GetLevelsSize() - 1 ) { wxMessageBox( _T("This index is last"), _T("Exclamation"), wxOK | wxICON_EXCLAMATION ); return false; } SLevel sTempLevel; memset( &sTempLevel, 0, sizeof( SLevel ) ); CopyLevel( sTempLevel, m_aLevels[ iIndex ] ); CopyLevel( m_aLevels[ iIndex ], m_aLevels[ iIndex + 1 ] ); CopyLevel( m_aLevels[ iIndex + 1 ], sTempLevel ); SaveAllLevels(); return true; } void CLevelsManager::CopyLevel( SLevel &dest, SLevel &src ) { if( dest.psShipsGroups ) delete [] dest.psShipsGroups; dest.iLevel = src.iLevel; dest.iIndexBoss = src.iIndexBoss; dest.iBossReserve1 = src.iBossReserve1; dest.iBossReserve2 = src.iBossReserve2; dest.iBossReserve3 = src.iBossReserve3; dest.iMaxShipsOnScreen = src.iMaxShipsOnScreen; dest.iFrequencyShoot = src.iFrequencyShoot; dest.iPercentChanceToShoot = src.iPercentChanceToShoot; dest.iNumberGroups = src.iNumberGroups; if( dest.iNumberGroups == 0 ) dest.psShipsGroups = NULL; else { dest.psShipsGroups = new SShipsGroups[ dest.iNumberGroups ]; for( int i = 0; i < dest.iNumberGroups; ++i ) { dest.psShipsGroups[ i ].iIndexShip = src.psShipsGroups[ i ].iIndexShip; dest.psShipsGroups[ i ].iNumberShips = src.psShipsGroups[ i ].iNumberShips; dest.psShipsGroups[ i ].iFormation = src.psShipsGroups[ i ].iFormation; dest.psShipsGroups[ i ].iPosXForRand = src.psShipsGroups[ i ].iPosXForRand; dest.psShipsGroups[ i ].fSpeed = src.psShipsGroups[ i ].fSpeed; dest.psShipsGroups[ i ].bCosFly = src.psShipsGroups[ i ].bCosFly; dest.psShipsGroups[ i ].bSlantFly = src.psShipsGroups[ i ].bSlantFly; dest.psShipsGroups[ i ].fOffsetXPosForSlantFly = src.psShipsGroups[ i ].fOffsetXPosForSlantFly; } } } bool CLevelsManager::AddNewLevel( const SLevel &sLevel ) { return SaveLevel( sLevel ); } bool CLevelsManager::DeleteLevel( int iIndexLevel ) { if( iIndexLevel < 0 || iIndexLevel >= GetLevelsSize() ) { wxMessageBox( _T("Error: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } if( m_aLevels[ iIndexLevel ].psShipsGroups ) delete [] m_aLevels[ iIndexLevel ].psShipsGroups; m_aLevels.erase( m_aLevels.begin() + iIndexLevel ); SaveAllLevels(); return true; } bool CLevelsManager::SaveModifyLevel( int iIndexLevel, SLevel &sLevel ) { if( iIndexLevel < 0 || iIndexLevel >= GetLevelsSize() ) { wxMessageBox( _T("Error: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } //ustaw dane emittera takie jak ma oryginal bo ich nie zmnieniamy tutaj sLevel.iNumberGroups = m_aLevels[ iIndexLevel ].iNumberGroups; sLevel.psShipsGroups = m_aLevels[ iIndexLevel ].psShipsGroups; memcpy_s( &m_aLevels[ iIndexLevel ], sizeof( SLevel ), &sLevel, sizeof( SLevel ) ); SaveAllLevels(); return true; } bool CLevelsManager::AddNewGroup( int iIndexLevel, const SShipsGroups &sNewGroup ) { if( iIndexLevel < 0 || iIndexLevel >= GetLevelsSize() ) { wxMessageBox( _T("Error: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } //stworz kobie aktualnych grup std::vector<SShipsGroups> aCopyOfGroup; for( int i = 0; i < m_aLevels[ iIndexLevel ].iNumberGroups; ++i ) { aCopyOfGroup.push_back( m_aLevels[ iIndexLevel ].psShipsGroups[ i ] ); } //usun aktualne emitery i stworz nowe if( m_aLevels[ iIndexLevel ].iNumberGroups > 0 && m_aLevels[ iIndexLevel ].psShipsGroups ) delete [] m_aLevels[ iIndexLevel ].psShipsGroups; //zwieksz liczbe emiterow ++m_aLevels[ iIndexLevel ].iNumberGroups; //utworz tablice na nowo z nowym emiterem m_aLevels[ iIndexLevel ].psShipsGroups = new SShipsGroups[ m_aLevels[ iIndexLevel ].iNumberGroups ]; for( int i = 0; i < m_aLevels[ iIndexLevel ].iNumberGroups; ++i ) { if( i < static_cast<int>( aCopyOfGroup.size() ) ) memcpy_s( &m_aLevels[ iIndexLevel ].psShipsGroups[ i ], sizeof( SShipsGroups ), &aCopyOfGroup[ i ], sizeof( SShipsGroups ) ); else //dopisz nowy memcpy_s( &m_aLevels[ iIndexLevel ].psShipsGroups[ i ], sizeof( SShipsGroups ), &sNewGroup, sizeof( SShipsGroups ) ); } aCopyOfGroup.clear(); SaveAllLevels(); return true; } bool CLevelsManager::DeleteGroup( int iIndexLevel, int iIndexGroup ) { if( iIndexLevel < 0 || iIndexLevel >= GetLevelsSize() ) { wxMessageBox( _T("Error: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } if( iIndexGroup < 0 || iIndexGroup >= m_aLevels[ iIndexLevel ].iNumberGroups ) { wxMessageBox( _T("Error: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } //stworz kobie aktualnych emiterow ale bez usuwanego std::vector<SShipsGroups> aCopyOfGroup; for( int i = 0; i < m_aLevels[ iIndexLevel ].iNumberGroups; ++i ) { if( i == iIndexGroup ) continue; aCopyOfGroup.push_back( m_aLevels[ iIndexLevel ].psShipsGroups[ i ] ); } //usun aktualne emitery if( m_aLevels[ iIndexLevel ].iNumberGroups > 0 && m_aLevels[ iIndexLevel ].psShipsGroups ) delete [] m_aLevels[ iIndexLevel ].psShipsGroups; //zmniejsz liczbe emiterow --m_aLevels[ iIndexLevel ].iNumberGroups; //utworz tablice na nowo m_aLevels[ iIndexLevel ].psShipsGroups = new SShipsGroups[ m_aLevels[ iIndexLevel ].iNumberGroups ]; for( int i = 0; i < m_aLevels[ iIndexLevel ].iNumberGroups; ++i ) { memcpy_s( &m_aLevels[ iIndexLevel ].psShipsGroups[ i ], sizeof( SShipsGroups ), &aCopyOfGroup[ i ], sizeof( SShipsGroups ) ); } aCopyOfGroup.clear(); SaveAllLevels(); return true; } bool CLevelsManager::SaveModifyGroup( int iIndexLevel, int iIndexGroup, const SShipsGroups &sModGroup ) { if( iIndexLevel < 0 || iIndexLevel >= GetLevelsSize() ) { wxMessageBox( _T("Error: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } if( iIndexGroup < 0 || iIndexGroup >= m_aLevels[ iIndexLevel ].iNumberGroups ) { wxMessageBox( _T("Error: incorrect index array"), _T("Error"), wxOK | wxICON_ERROR ); return false; } memcpy_s( &m_aLevels[ iIndexLevel ].psShipsGroups[ iIndexGroup], sizeof( SShipsGroups ), &sModGroup, sizeof( SShipsGroups ) ); SaveAllLevels(); return true; } /////////////////////////////////////////////////////////////////// int CLevelsManager::GetShipsNumber() { return m_pShipsManager->GetUniqueShipSize(); } TCHAR* CLevelsManager::GetShipName( int iIndex ) { return m_pShipsManager->GetUniqueShip( iIndex ).cShipName; }
/* Maximum of Minima of all windows of size k For a list of numbers, Find the maximum of minima of all windows of size k For example if array = [1,2,3,4,5,6] and window size, k = 3 then windows | minimum [1,2,3] | 1 [2,3,4] | 2 [3,4,5] | 3 [4,5,6] | 4 Then maximum of minima = 4 Approach: Hash the first window using ordered map, and store the first element of hash as answer then hash subsequent windows and for each window decrease one instance first element of previous window and if that number is not present in new window remove it. Add the new element and again take the first element of map and maximise it. */ #include <bits/stdc++.h> using namespace std; int main() { int n = 6; // size of array int nums[n] = {1, 2, 3, 4, 5, 6}; int k = 3; // window size int maxx = INT_MIN; map<int,int>hash; for(int i=0;i<k;i++) hash[nums[i]]++; // hashing first k numbers auto it=hash.begin(); maxx = it->first; // first element of map is smallest for(int i=k;i<n;i++) { hash[nums[i-k]]--; // excluding first value of last window // if the first value of last window is not in new / current window if( hash[nums[i-k]] ==0) hash.erase(nums[i-k]); // removing the value hash[nums[i]]++; // adding current element to new window auto it = hash.begin(); // taking the first value maxx = max(maxx,it->first); // maximising the minima } cout<<maxx; // answer return 0; }
#include "midgard/constants.h" #include "midgard/logging.h" #include "midgard/util.h" #include "sif/autocost.h" #include "sif/bicyclecost.h" #include "sif/pedestriancost.h" #include "thor/costmatrix.h" #include "thor/optimizer.h" #include "thor/worker.h" using namespace valhalla; using namespace valhalla::midgard; using namespace valhalla::baldr; using namespace valhalla::sif; using namespace valhalla::thor; namespace valhalla { namespace thor { void thor_worker_t::optimized_route(Api& request) { // time this whole method and save that statistic auto _ = measure_scope_time(request); parse_locations(request); auto costing = parse_costing(request); auto& options = *request.mutable_options(); controller = AttributesController(options); // Use CostMatrix to find costs from each location to every other location CostMatrix costmatrix; std::vector<thor::TimeDistance> td = costmatrix.SourceToTarget(options.sources(), options.targets(), *reader, mode_costing, mode, max_matrix_distance.find(costing)->second); // Return an error if any locations are totally unreachable const auto& correlated = (options.sources_size() > options.targets_size() ? options.sources() : options.targets()); // Set time costs to send to Optimizer. std::vector<float> time_costs; bool reachable = true; for (size_t i = 0; i < td.size(); ++i) { // If any location is completely unreachable then we cant have a connected path if (i % correlated.size() == 0) { if (!reachable) { throw valhalla_exception_t{441, " at index " + std::to_string(i / correlated.size())}; }; reachable = false; } reachable = reachable || td[i].time != kMaxCost; // Keep the times for the reordering time_costs.emplace_back(static_cast<float>(td[i].time)); } Optimizer optimizer; // returns the optimal order of the path_locations auto optimal_order = optimizer.Solve(correlated.size(), time_costs); // put the optimal order into the locations array options.mutable_locations()->Clear(); for (size_t i = 0; i < optimal_order.size(); i++) { options.mutable_locations()->Add()->CopyFrom(correlated.Get(optimal_order[i])); } // run the route path_depart_at(request, costing); } } // namespace thor } // namespace valhalla
// // Created by Ciaran on 06/02/2021. // #include <utility> #include <vector> #include <iostream> #include "Optimizer.h" namespace opt { Optimizer::Optimizer( opt::CostFunction cost, const std::vector<double> &startingValues, const std::vector<double> &lb, const std::vector<double> &ub, bool logspace, bool verbose) : cost_(cost), optItems_(OptItems(startingValues, lb, ub, logspace)), numberOfParameters_(startingValues.size()), verbose_(verbose){ } Optimizer::Optimizer(opt::CostFunction cost, OptItems optItems) : cost_(cost), optItems_(std::move(optItems)), numberOfParameters_(optItems.size()) {} CostFunction Optimizer::getCost() const { return cost_; } void Optimizer::setCost(CostFunction cost) { cost_ = cost; } const OptItems &Optimizer::getOptItems() const { return optItems_; } void Optimizer::setOptItems(const OptItems &optItems) { optItems_ = optItems; } void Optimizer::setSeed(unsigned long long int seed) { RandomNumberGenerator::getInstance().setSeed(seed); } bool Optimizer::setSolution(const double &value, const std::vector<double> &variables) { bestFitnessValue_ = value; hallOfFame_.push_back(bestFitnessValue_); // The initialization call from Optimizer and GASR have NULL as variables if (!variables.empty()) solutionValues_ = variables; bool Continue = true; if (value == -std::numeric_limits<double>::infinity()) Continue = false; // if (mpCallBack) // Continue &= mpCallBack->progressItem(mhSolutionValue); return Continue; } const std::vector<double> &Optimizer::getSolutionValues() const { return solutionValues_; } void Optimizer::setSolutionValues(const std::vector<double> &solutionValues) { solutionValues_ = solutionValues; } double Optimizer::getBestFitnessValue() const { return bestFitnessValue_; } void Optimizer::setBestValue(double bestValue) { bestFitnessValue_ = bestValue; } std::vector<double> Optimizer::getHallOfFame() { return hallOfFame_; } int Optimizer::getNumberOfParameters() const { return numberOfParameters_; } void Optimizer::setNumberOfParameters(int numberOfParameters) { numberOfParameters_ = numberOfParameters; } }
#include "stdafx.h" //----------------------------------------------------------------------------- // Name: WndProc() // Desc: Static msg handler which passes messages to the application class. //----------------------------------------------------------------------------- LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch(uMsg) { case WM_ACTIVATE: { Device.OnWM_Activate (wParam, lParam); /* u16 fActive = LOWORD(wParam); BOOL fMinimized = (BOOL) HIWORD(wParam); BOOL bActive = ((fActive!=WA_INACTIVE) && (!fMinimized))?TRUE:FALSE; if (bActive!=Device.bActive) { Device.bActive = bActive; if (Device.b_is_Active) { Device.seqAppActivate.Process(rp_AppActivate); #ifndef DEDICATED_SERVER ShowCursor (FALSE); #endif }else { Device.seqAppDeactivate.Process(rp_AppDeactivate); ShowCursor (TRUE); } } */ } break; case WM_SETCURSOR: return 1; case WM_SYSCOMMAND: // Prevent moving/sizing and power loss in fullscreen mode switch( wParam ) { case SC_MOVE: case SC_SIZE: case SC_MAXIMIZE: case SC_MONITORPOWER: return 1; break; } break; case WM_CLOSE: return 0; case WM_KEYDOWN: break; default: break; } return DefWindowProc(hWnd,uMsg,wParam,lParam); }
#include "signalFirstInternal.h" #include <vector> #include "config.h" #include "sgcu/sgcu.hpp" int main(int argc, char** argv) { sgcu::argumentParser<char> myP; // Declare the supported options. myP.desc_.add_options() ("help", "produce help message") ("input", boost::program_options::value<std::string>(), "set input file") ; myP.defaultParse(argc, argv); std::string inputFile = myP.parseVariable("input", std::string(".")); std::vector<SG::candidate_t> allCandidates; readCandidatesFromFile(inputFile, allCandidates); // set up an object to handle all computations with a simple interface to this module SG::signalFirstInternal intern; intern.init(SG::fine); // Evaluate the clustering/density of the found candidates here intern.performEvaluate(allCandidates, SG::fine); return 0; }
// Copyright (c) 2015-2016 The Alphapay Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "scheduler.h" #include "reverselock.h" #include <assert.h> #include <boost/bind.hpp> #include <utility> CScheduler::CScheduler() : nThreadsServicingQueue(0), stopRequested(false), stopWhenEmpty(false) { } CScheduler::~CScheduler() { assert(nThreadsServicingQueue == 0); } #if BOOST_VERSION < 105000 static boost::system_time toPosixTime(const boost::chrono::system_clock::time_point& t) { return boost::posix_time::from_time_t(boost::chrono::system_clock::to_time_t(t)); } #endif void CScheduler::serviceQueue() { boost::unique_lock<boost::mutex> lock(newTaskMutex); ++nThreadsServicingQueue; // newTaskMutex is locked throughout this loop EXCEPT // when the thread is waiting or when the user's function // is called. while (!shouldStop()) { try { while (!shouldStop() && taskQueue.empty()) { // Wait until there is something to do. newTaskScheduled.wait(lock); } // Wait until either there is a new task, or until // the time of the first item on the queue: // wait_until needs boost 1.50 or later; older versions have timed_wait: #if BOOST_VERSION < 105000 while (!shouldStop() && !taskQueue.empty() && newTaskScheduled.timed_wait(lock, toPosixTime(taskQueue.begin()->first))) { // Keep waiting until timeout } #else // Some boost versions have a conflicting overload of wait_until that returns void. // Explicitly use a template here to avoid hitting that overload. while (!shouldStop() && !taskQueue.empty()) { boost::chrono::system_clock::time_point timeToWaitFor = taskQueue.begin()->first; if (newTaskScheduled.wait_until<>(lock, timeToWaitFor) == boost::cv_status::timeout) break; // Exit loop after timeout, it means we reached the time of the event } #endif // If there are multiple threads, the queue can empty while we're waiting (another // thread may service the task we were waiting on). if (shouldStop() || taskQueue.empty()) continue; Function f = taskQueue.begin()->second; taskQueue.erase(taskQueue.begin()); { // Unlock before calling f, so it can reschedule itself or another task // without deadlocking: reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock); f(); } } catch (...) { --nThreadsServicingQueue; throw; } } --nThreadsServicingQueue; newTaskScheduled.notify_one(); } void CScheduler::stop(bool drain) { { boost::unique_lock<boost::mutex> lock(newTaskMutex); if (drain) stopWhenEmpty = true; else stopRequested = true; } newTaskScheduled.notify_all(); } void CScheduler::schedule(CScheduler::Function f, boost::chrono::system_clock::time_point t) { { boost::unique_lock<boost::mutex> lock(newTaskMutex); taskQueue.insert(std::make_pair(t, f)); } newTaskScheduled.notify_one(); } void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaSeconds) { schedule(f, boost::chrono::system_clock::now() + boost::chrono::seconds(deltaSeconds)); } static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaSeconds) { f(); s->scheduleFromNow(boost::bind(&Repeat, s, f, deltaSeconds), deltaSeconds); } void CScheduler::scheduleEvery(CScheduler::Function f, int64_t deltaSeconds) { scheduleFromNow(boost::bind(&Repeat, this, f, deltaSeconds), deltaSeconds); } size_t CScheduler::getQueueInfo(boost::chrono::system_clock::time_point &first, boost::chrono::system_clock::time_point &last) const { boost::unique_lock<boost::mutex> lock(newTaskMutex); size_t result = taskQueue.size(); if (!taskQueue.empty()) { first = taskQueue.begin()->first; last = taskQueue.rbegin()->first; } return result; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Gtacoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "cleanse.h" #include <openssl/crypto.h> void memory_cleanse(void *ptr, size_t len) { OPENSSL_cleanse(ptr, len); }
#include "MainWindow.h" #include "TestEntity.h" #include "ChildWindow.h" MainWindow::MainWindow(Oculum::WindowManager* manager) : Oculum::Window(L"MainWindow", 400, 400, nullptr, manager) { SubscribeEvent<Oculum::ChildCloseEvent>([&](Oculum::ChildCloseEvent* e) { OC_INFO("Child closed with exit code %i", e->GetExitCode()); return true; }); new ChildWindow(this, GetManager()); new ChildWindow(this, GetManager()); new ChildWindow(this, GetManager()); } MainWindow::~MainWindow() { } void MainWindow::OnUpdateClient(float) { } void MainWindow::OnClose() { if (MessageBox(GetHwnd(), L"Are you sure you want to exit?", L"Quit", MB_YESNO) == IDYES) { CloseWindow(Oculum::Window::ExitCode::Normal); } }
#include<iostream> #include<cstdio> #include<cctype> #include<stack> #pragma GCC optimize(2) using namespace std; //stack<char> OPTR; //stack<double> OPND; typedef struct node { char data; node *next; }Qnode,Snode; typedef struct Cnode { int data; Cnode *next; }SnodeC; typedef struct{ Qnode *rear,*front; }Qlink; typedef struct{ SnodeC *base,*top; }SlinkC; typedef struct { Snode *base, *top; }Slink; template<class T> void InitStack(T &s){ s.top = s.base = NULL; } //void InitStack(Slink &s){ // s.top = s.base = NULL; //} // //void InitStack(SlinkC &s){ // s.top = s.base = NULL; //} void push(Slink &s,int n){ Snode *p; p = new (Snode); p->data = n; p->next = NULL; if (s.base == NULL){ s.top = s.base = p; } else{ s.top->next = p; s.top = p; } } void push(SlinkC &s,char n){ SnodeC *p; p = new (SnodeC); p->data = n; p->next = NULL; if (s.base == NULL){ s.top = s.base = p; } else{ s.top->next = p; s.top = p; } } void pop(Slink &s){ Snode *p; p = s.base; if ((s.base == s.top)&&(s.base != NULL)){ free(s.base); s.base = s.top = NULL; return; } while (p->next != s.top) p = p->next; s.top = p; free(p->next); p->next =NULL; } void pop(SlinkC &s){ SnodeC *p; p = s.base; if ((s.base == s.top)&&(s.base != NULL)){ free(s.base); s.base = s.top = NULL; return; } while (p->next != s.top) p = p->next; s.top = p; free(p->next); p->next =NULL; } int top(Slink s){ return s.top->data; } char top(SlinkC s){ return s.top->data; } template<class T> int empty(T s){ if (s.base == NULL) return 1; else return 0; } int getIndex(char theta) //中文"("与")"不可用 { int index = 0; switch (theta) { case '+': index = 0; break; case '-': index = 1; break; case '*': index = 2; break; case '/': index = 3; break; case '(': index = 4; break; case ')': index = 5; break; case '#': index = 6; default:break; } return index; } char Precede(char theta1, char theta2) { const char priority[][7] = //优先度 { { '>','>','<','<','<','>','>' }, { '>','>','<','<','<','>','>' }, { '>','>','>','>','<','>','>' }, { '>','>','>','>','<','>','>' }, { '<','<','<','<','<','=','0' }, { '>','>','>','>','0','>','>' }, { '<','<','<','<','<','0','=' }, }; int index1 = getIndex(theta1); int index2 = getIndex(theta2); return priority[index1][index2]; } double calculate(double b, char theta, double a) { switch (theta) { case '+': return b + a; case '-': return b - a; case '*': return b * a; case '/': return b / a; default: break; } } double getAnswer(SlinkC &OPTR,Slink &OPND) { push(OPTR,'#'); int counter = 0; //用来记录数字的位数 char c = getchar(); while (c != '#' || top(OPTR) != '#') { if (isdigit(c)) //判断是否是数字 { if (counter == 1) { double t = top(OPND); //保留栈顶 pop(OPND); push(OPND,t * 10 + (c - '0')); counter = 1; } else { push(OPND,c - '0'); counter++; //第二位也是数字,则counter变为1,弹出原有数字并压入新的数字 } c = getchar(); } else { counter = 0; //数字结束 switch (Precede(top(OPTR), c)) { case '<': push(OPTR,c); c = getchar(); break; case '=': pop(OPTR); c = getchar(); break; case '>': char theta = top(OPTR); pop(OPTR); double a = top(OPND); pop(OPND); double b = top(OPND); pop(OPND); push(OPND,calculate(b, theta, a)); } } } return top(OPND); } template<class T> void clearstack(T s) //清空栈 { while (!empty(s)) pop(s); } int main() { Slink OPND; SlinkC OPTR; InitStack(OPND); InitStack(OPTR); int t; cin >> t; getchar(); while (t--) { clearstack(OPND); clearstack(OPTR); double ans = getAnswer(OPTR,OPND); cout << ans << endl<< endl; getchar(); } return 0; }
#include <iostream> #include <string> #include <list> using namespace std; void spacer(); void test1(); void aufgabe1(); int main() { int test; aufgabe1(); cin >> test; return 0; } void test1() { cout << "Hello world!" << endl; int x; x = 5; while (x > 0) { spacer(); cout << "\n" << x << endl; x--; } spacer(); } void spacer() { cout << "\n\n- - - - - - - - - - - - - - -\n\n"; } void aufgabe1() { /* Hallo Welt mit einer while Schleife */ int i; int j; while (i < 10) { cout << i << ". Hello World" << endl; } do { cout << i << ". Hello World" << endl; } while (j < 10); for (int k; k < 10; k++) { cout << j << ". Hello World" << endl; } } /* void excercise1() { int number1; int number2; cout << "You'll enter two numbers and the programm will print all numbers inbetween.\n"; cout << "Enter number 1:\n> "; cin >> number1; cout << "Enter number 2:\n> "; cin >> number2; if (number2 > number1) { while (true) { cout << number2 << endl; if (number2 == number1) { break; } else { number2 = number2 - 1; } } } else { while (true) { cout << number1 << endl; if (number1 == number2) { break; } else { number1 = number1 - 1; } } } } void excercise2() { string password; password == "IFIS1"; string user; while (user != password) { cout << "Please enter the password:\n> " << endl; cin >> user; } cout << "Access granted!" << endl; } void excercise3() { float number; cout << "Enter a number you want to divide until it's smaller than or equal 1:\n> "; cin >> number; cout << number << endl; while (number > 1) { number = number / 2; cout << number << endl; } } void excercise4() { int n, t1 = 0, t2 = 1, nextTerm = 0; cout << "Enter the number of terms: "; cin >> n; cout << "Fibonacci Series: "; for (int i = 1; i <= n; ++i) { if (i == 1) { cout << " " << t1; continue; } if (i == 2) { cout << t2 << " "; continue; } nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; cout << nextTerm << " "; } } void excercise5() { cout << "Hi" << endl; } void presentation() { int i = 1; while (i <= 5) { cout << "Hello world!\n"; i++; } } */
/* Copyright 2020 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 <poplar/DebugContext.hpp> #include "tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/poplar_ops.h" #include "tensorflow/compiler/plugin/poplar/driver/tensor.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/conv_poplar_util.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/weights_transpose_chans_flip_xy.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/debug_info.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "absl/strings/str_cat.h" namespace xla { namespace poplarplugin { namespace { StatusOr<poplar::Tensor> AddConvWeightsTransposeChansFlipXY( poplar::Graph& graph, const poplar::DebugNameAndId& debug_name_and_id, const HloInstruction* inst, CompilerResources& resources) { const HloWeightsTransposeChansFlipXYInstruction* weights_transpose_inst = Cast<HloWeightsTransposeChansFlipXYInstruction>(inst); const ConvolutionDimensionNumbers& conv_dimension_numbers = weights_transpose_inst->convolution_dimension_numbers(); const std::vector<size_t>& conv_input_shape = weights_transpose_inst->ConvInputShape(); const std::vector<size_t>& conv_output_shape = weights_transpose_inst->ConvOutputShape(); TF_ASSIGN_OR_RETURN( poplin::ConvParams conv_params, GetConvolutionParametersForWeightsTranspose( weights_transpose_inst, conv_input_shape, conv_output_shape)); TF_ASSIGN_OR_RETURN(poplar::OptionFlags opts, GetConvolutionOptionsForInst(inst, resources)); poplar::Tensor out_weights = poplin::createWeights( graph, conv_params, {debug_name_and_id, "createWeights_TransposeChansFlipXY"}, opts, &resources.convolution_cache); out_weights = RemoveGroupsDimensionFromWeights(conv_params, out_weights); out_weights = ShuffleConvolutionWeightsToTensorflow(conv_dimension_numbers, out_weights); return out_weights; } class WeightsTransposeChansFlipXYOp : public PoplarOpDef { StatusOr<poplar::program::Sequence> Creator( poplar::Graph& graph, CompilerResources& res, const HloInstruction* inst, const xla::Shape& output_shape, TensorMap& tensor_map, const poplar::DebugContext& debug_context) override { PoplarOpDefDebugInfo debug_info(debug_context, "WeightsTransposeChansFlipXYOp"); poplar::program::Sequence seq({}, debug_info); TF_ASSIGN_OR_RETURN( poplar::Tensor in_weights, FindInstructionInput(tensor_map, res, inst, 0, seq, debug_info, false)); const HloWeightsTransposeChansFlipXYInstruction* weights_transpose_inst = Cast<HloWeightsTransposeChansFlipXYInstruction>(inst); const ConvolutionDimensionNumbers& conv_dimension_numbers = weights_transpose_inst->convolution_dimension_numbers(); in_weights = ShuffleConvolutionWeightsToPoplar( conv_dimension_numbers, in_weights, /* swap_features= */ true); const std::vector<size_t>& conv_input_shape = weights_transpose_inst->ConvInputShape(); const std::vector<size_t>& conv_output_shape = weights_transpose_inst->ConvOutputShape(); TF_ASSIGN_OR_RETURN( poplin::ConvParams conv_params, GetConvolutionParametersForWeightsTranspose( weights_transpose_inst, conv_input_shape, conv_output_shape)); TF_ASSIGN_OR_RETURN(poplar::OptionFlags opts, GetConvolutionOptionsForInst(inst, res)); in_weights = AddGroupsDimensionToWeights(conv_params, in_weights, /* swap_features= */ true); poplar::Tensor out_weights = poplin::createWeights(graph, conv_params, {debug_info, "CreateWeights"}, opts, &res.convolution_cache); poplar::DebugNameAndId debug_name_and_id(debug_info); auto func = [&graph, &res, inst, debug_name_and_id]( std::vector<poplar::Tensor>& args, poplar::program::Sequence& prog) { poplar::Tensor in_weights_f = args[0]; poplar::Tensor out_weights_f = args[1]; poplin::weightsTransposeChansFlipXY( graph, in_weights_f, out_weights_f, prog, {debug_name_and_id, "WeightsTransposeChansFlipXY"}); }; std::vector<poplar::Tensor> args = {in_weights, out_weights}; poputil::graphfn::Signature signature = { poputil::graphfn::input(in_weights, "in_weights"), poputil::graphfn::output(out_weights, "out_weights")}; TF_RETURN_IF_ERROR(res.graph_cache.ExecuteCached( inst, graph, res, seq, func, signature, args, weights_transpose_inst->AllocatingIndices(), weights_transpose_inst->LayoutDependencies())); out_weights = RemoveGroupsDimensionFromWeights(conv_params, out_weights); out_weights = ShuffleConvolutionWeightsToTensorflow( conv_dimension_numbers, out_weights, /* swap_features = */ true); TF_CHECK_OK(AddOutputTensor(tensor_map, inst, 0, out_weights)); return seq; } StatusOr<poplar::Tensor> Allocator( poplar::Graph& graph, CompilerResources& res, const std::string& name, const TensorTarget& tensor_target, const TensorMap& tensor_map, const poplar::DebugContext& debug_context) override { PoplarOpDefDebugInfo debug_info(debug_context, "WeightsTransposeChansFlipXYOp"); const int64 input_index = tensor_target.input_index; const HloInstruction* inst = tensor_target.tgt; poplar::Tensor out; switch (input_index) { case 0: { TF_ASSIGN_OR_RETURN(out, AddConvWeightsTransposeChansFlipXY( graph, {debug_info}, inst, res)); break; } default: return xla::FailedPrecondition( "Input index %d of weights transpose chans flipxy op shouldn't be " "allocating", input_index); } return out; } }; REGISTER_POPLAR_OP(WeightsTransposeChansFlipXY, WeightsTransposeChansFlipXYOp); } // namespace } // namespace poplarplugin } // namespace xla
/* * Copyright (c) 2012, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3) Neither the name of the FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CXXLAPACK_INTERFACE_GEESX_TCC #define CXXLAPACK_INTERFACE_GEESX_TCC 1 #include <cxxstd/iostream.h> #include <cxxlapack/interface/interface.h> #include <cxxlapack/netlib/netlib.h> namespace cxxlapack { template <typename IndexType> IndexType geesx(char jobVS, char sort, IndexType (*select)(const float *, const float *), char sense, IndexType n, float *A, IndexType ldA, IndexType &sDim, float *wr, float *wi, float *VS, IndexType ldVS, float &rCondE, float &rCondV, float *work, IndexType lWork, IndexType *iWork, IndexType liWork, IndexType *bWork) { IndexType info; CXXLAPACK_DEBUG_OUT("sgeesx"); LAPACK_IMPL(sgeesx)(&jobVS, &sort, select, &sense, &n, A, &ldA, &sDim, wr, wi, VS, &ldVS, &rCondE, &rCondV, work, &lWork, iWork, &liWork, bWork, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } template <typename IndexType> IndexType geesx(char jobVS, char sort, IndexType (*select)(const double *, const double *), char sense, IndexType n, double *A, IndexType ldA, IndexType &sDim, double *wr, double *wi, double *VS, IndexType ldVS, double &rCondE, double &rCondV, double *work, IndexType lWork, IndexType *iWork, IndexType liWork, IndexType *bWork) { IndexType info; CXXLAPACK_DEBUG_OUT("dgeesx"); LAPACK_IMPL(dgeesx)(&jobVS, &sort, select, &sense, &n, A, &ldA, &sDim, wr, wi, VS, &ldVS, &rCondE, &rCondV, work, &lWork, iWork, &liWork, bWork, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } template <typename IndexType> IndexType geesx(char jobVS, char sort, IndexType (*select)(const std::complex<float > *), char sense, IndexType n, std::complex<float > *A, IndexType ldA, IndexType &sDim, std::complex<float > *w, std::complex<float > *VS, IndexType ldVS, float &rCondE, float &rCondV, std::complex<float > *work, IndexType lWork, float *rWork, IndexType *bWork) { typedef IndexType (*LapackSelect)(const float *); IndexType info; CXXLAPACK_DEBUG_OUT("cgeesx"); LAPACK_IMPL(cgeesx)(&jobVS, &sort, reinterpret_cast<LapackSelect>(select), &sense, &n, reinterpret_cast<float *>(A), &ldA, &sDim, reinterpret_cast<float *>(w), reinterpret_cast<float *>(VS), &ldVS, &rCondE, &rCondV, reinterpret_cast<float *>(work), &lWork, rWork, bWork, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } template <typename IndexType> IndexType geesx(char jobVS, char sort, IndexType (*select)(const std::complex<double> *), char sense, IndexType n, std::complex<double> *A, IndexType ldA, IndexType &sDim, std::complex<double> *w, std::complex<double> *VS, IndexType ldVS, double &rCondE, double &rCondV, std::complex<double> *work, IndexType lWork, double *rWork, IndexType *bWork) { typedef IndexType (*LapackSelect)(const double *); IndexType info; CXXLAPACK_DEBUG_OUT("zgeesx"); LAPACK_IMPL(zgeesx)(&jobVS, &sort, reinterpret_cast<LapackSelect>(select), &sense, &n, reinterpret_cast<double *>(A), &ldA, &sDim, reinterpret_cast<double *>(w), reinterpret_cast<double *>(VS), &ldVS, &rCondE, &rCondV, reinterpret_cast<double *>(work), &lWork, rWork, bWork, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } } // namespace cxxlapack #endif // CXXLAPACK_INTERFACE_GEESX_TCC
class Solution { public: int search(vector<int>& nums, int t) { int n = nums.size(); int l=0, r=n-1; if (n==0) return -1; while(l<=r) { int mid = (l+r)/2, k = nums[mid]; if (k == t) return mid; if (k <= nums[0] && k <= nums[n-1]) { // a[k...n-1] is increasing if (k > t) r=mid-1; else if (k<t && nums[n-1]<t) r=mid-1; else if (k<t && nums[n-1]>=t) l=mid+1; } else if (k >= nums[0] && k >= nums[n-1]) { // a[0...k] is increasing if (k > t && nums[0] > t) l=mid+1; else if (k > t && nums[0] <= t) r=mid-1; else if (k < t) l=mid+1; } else if (k < t) l=mid+1; else if (k>t) r=mid-1; } return -1; } };
//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// // // 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 // //===----------------------------------------------------------------------===// // // This file implements type-related semantic analysis. // //===----------------------------------------------------------------------===// #include "TypeLocBuilder.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/ASTStructuralEquivalence.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeLocVisitor.h" #include "clang/Basic/PartialDiagnostic.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/DelayedDiagnostic.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "clang/Sema/Template.h" #include "clang/Sema/TemplateInstCallback.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" using namespace clang; enum TypeDiagSelector { TDS_Function, TDS_Pointer, TDS_ObjCObjOrBlock }; /// isOmittedBlockReturnType - Return true if this declarator is missing a /// return type because this is a omitted return type on a block literal. static bool isOmittedBlockReturnType(const Declarator &D) { if (D.getContext() != DeclaratorContext::BlockLiteralContext || D.getDeclSpec().hasTypeSpecifier()) return false; if (D.getNumTypeObjects() == 0) return true; // ^{ ... } if (D.getNumTypeObjects() == 1 && D.getTypeObject(0).Kind == DeclaratorChunk::Function) return true; // ^(int X, float Y) { ... } return false; } /// diagnoseBadTypeAttribute - Diagnoses a type attribute which /// doesn't apply to the given type. static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, QualType type) { TypeDiagSelector WhichType; bool useExpansionLoc = true; switch (attr.getKind()) { case ParsedAttr::AT_ObjCGC: WhichType = TDS_Pointer; break; case ParsedAttr::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break; default: // Assume everything else was a function attribute. WhichType = TDS_Function; useExpansionLoc = false; break; } SourceLocation loc = attr.getLoc(); StringRef name = attr.getAttrName()->getName(); // The GC attributes are usually written with macros; special-case them. IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident : nullptr; if (useExpansionLoc && loc.isMacroID() && II) { if (II->isStr("strong")) { if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; } else if (II->isStr("weak")) { if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; } } S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType << type; } // objc_gc applies to Objective-C pointers or, otherwise, to the // smallest available pointer type (i.e. 'void*' in 'void**'). #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ case ParsedAttr::AT_ObjCGC: \ case ParsedAttr::AT_ObjCOwnership // Calling convention attributes. #define CALLING_CONV_ATTRS_CASELIST \ case ParsedAttr::AT_CDecl: \ case ParsedAttr::AT_FastCall: \ case ParsedAttr::AT_StdCall: \ case ParsedAttr::AT_ThisCall: \ case ParsedAttr::AT_RegCall: \ case ParsedAttr::AT_Pascal: \ case ParsedAttr::AT_SwiftCall: \ case ParsedAttr::AT_VectorCall: \ case ParsedAttr::AT_AArch64VectorPcs: \ case ParsedAttr::AT_MSABI: \ case ParsedAttr::AT_SysVABI: \ case ParsedAttr::AT_Pcs: \ case ParsedAttr::AT_IntelOclBicc: \ case ParsedAttr::AT_PreserveMost: \ case ParsedAttr::AT_PreserveAll // Function type attributes. #define FUNCTION_TYPE_ATTRS_CASELIST \ case ParsedAttr::AT_NSReturnsRetained: \ case ParsedAttr::AT_NoReturn: \ case ParsedAttr::AT_Regparm: \ case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ case ParsedAttr::AT_AnyX86NoCfCheck: \ CALLING_CONV_ATTRS_CASELIST // Microsoft-specific type qualifiers. #define MS_TYPE_ATTRS_CASELIST \ case ParsedAttr::AT_Ptr32: \ case ParsedAttr::AT_Ptr64: \ case ParsedAttr::AT_SPtr: \ case ParsedAttr::AT_UPtr // Nullability qualifiers. #define NULLABILITY_TYPE_ATTRS_CASELIST \ case ParsedAttr::AT_TypeNonNull: \ case ParsedAttr::AT_TypeNullable: \ case ParsedAttr::AT_TypeNullUnspecified namespace { /// An object which stores processing state for the entire /// GetTypeForDeclarator process. class TypeProcessingState { Sema &sema; /// The declarator being processed. Declarator &declarator; /// The index of the declarator chunk we're currently processing. /// May be the total number of valid chunks, indicating the /// DeclSpec. unsigned chunkIndex; /// Whether there are non-trivial modifications to the decl spec. bool trivial; /// Whether we saved the attributes in the decl spec. bool hasSavedAttrs; /// The original set of attributes on the DeclSpec. SmallVector<ParsedAttr *, 2> savedAttrs; /// A list of attributes to diagnose the uselessness of when the /// processing is complete. SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; /// Attributes corresponding to AttributedTypeLocs that we have not yet /// populated. // FIXME: The two-phase mechanism by which we construct Types and fill // their TypeLocs makes it hard to correctly assign these. We keep the // attributes in creation order as an attempt to make them line up // properly. using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; SmallVector<TypeAttrPair, 8> AttrsForTypes; bool AttrsForTypesSorted = true; /// MacroQualifiedTypes mapping to macro expansion locations that will be /// stored in a MacroQualifiedTypeLoc. llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; /// Flag to indicate we parsed a noderef attribute. This is used for /// validating that noderef was used on a pointer or array. bool parsedNoDeref; public: TypeProcessingState(Sema &sema, Declarator &declarator) : sema(sema), declarator(declarator), chunkIndex(declarator.getNumTypeObjects()), trivial(true), hasSavedAttrs(false), parsedNoDeref(false) {} Sema &getSema() const { return sema; } Declarator &getDeclarator() const { return declarator; } bool isProcessingDeclSpec() const { return chunkIndex == declarator.getNumTypeObjects(); } unsigned getCurrentChunkIndex() const { return chunkIndex; } void setCurrentChunkIndex(unsigned idx) { assert(idx <= declarator.getNumTypeObjects()); chunkIndex = idx; } ParsedAttributesView &getCurrentAttributes() const { if (isProcessingDeclSpec()) return getMutableDeclSpec().getAttributes(); return declarator.getTypeObject(chunkIndex).getAttrs(); } /// Save the current set of attributes on the DeclSpec. void saveDeclSpecAttrs() { // Don't try to save them multiple times. if (hasSavedAttrs) return; DeclSpec &spec = getMutableDeclSpec(); for (ParsedAttr &AL : spec.getAttributes()) savedAttrs.push_back(&AL); trivial &= savedAttrs.empty(); hasSavedAttrs = true; } /// Record that we had nowhere to put the given type attribute. /// We will diagnose such attributes later. void addIgnoredTypeAttr(ParsedAttr &attr) { ignoredTypeAttrs.push_back(&attr); } /// Diagnose all the ignored type attributes, given that the /// declarator worked out to the given type. void diagnoseIgnoredTypeAttrs(QualType type) const { for (auto *Attr : ignoredTypeAttrs) diagnoseBadTypeAttribute(getSema(), *Attr, type); } /// Get an attributed type for the given attribute, and remember the Attr /// object so that we can attach it to the AttributedTypeLoc. QualType getAttributedType(Attr *A, QualType ModifiedType, QualType EquivType) { QualType T = sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); AttrsForTypesSorted = false; return T; } /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if /// necessary. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { // Attributed type still should be an attributed type after replacement. auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); for (TypeAttrPair &A : AttrsForTypes) { if (A.first == AttrTy) A.first = NewAttrTy; } AttrsForTypesSorted = false; } return T; } /// Extract and remove the Attr* for a given attributed type. const Attr *takeAttrForAttributedType(const AttributedType *AT) { if (!AttrsForTypesSorted) { llvm::stable_sort(AttrsForTypes, llvm::less_first()); AttrsForTypesSorted = true; } // FIXME: This is quadratic if we have lots of reuses of the same // attributed type. for (auto It = std::partition_point( AttrsForTypes.begin(), AttrsForTypes.end(), [=](const TypeAttrPair &A) { return A.first < AT; }); It != AttrsForTypes.end() && It->first == AT; ++It) { if (It->second) { const Attr *Result = It->second; It->second = nullptr; return Result; } } llvm_unreachable("no Attr* for AttributedType*"); } SourceLocation getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { auto FoundLoc = LocsForMacros.find(MQT); assert(FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType"); return FoundLoc->second; } void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, SourceLocation Loc) { LocsForMacros[MQT] = Loc; } void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } bool didParseNoDeref() const { return parsedNoDeref; } ~TypeProcessingState() { if (trivial) return; restoreDeclSpecAttrs(); } private: DeclSpec &getMutableDeclSpec() const { return const_cast<DeclSpec&>(declarator.getDeclSpec()); } void restoreDeclSpecAttrs() { assert(hasSavedAttrs); getMutableDeclSpec().getAttributes().clearListOnly(); for (ParsedAttr *AL : savedAttrs) getMutableDeclSpec().getAttributes().addAtEnd(AL); } }; } // end anonymous namespace static void moveAttrFromListToList(ParsedAttr &attr, ParsedAttributesView &fromList, ParsedAttributesView &toList) { fromList.remove(&attr); toList.addAtEnd(&attr); } /// The location of a type attribute. enum TypeAttrLocation { /// The attribute is in the decl-specifier-seq. TAL_DeclSpec, /// The attribute is part of a DeclaratorChunk. TAL_DeclChunk, /// The attribute is immediately after the declaration's name. TAL_DeclName }; static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, ParsedAttributesView &attrs); static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type); static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type); static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type); static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type); static bool handleObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type) { if (attr.getKind() == ParsedAttr::AT_ObjCGC) return handleObjCGCTypeAttr(state, attr, type); assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership); return handleObjCOwnershipTypeAttr(state, attr, type); } /// Given the index of a declarator chunk, check whether that chunk /// directly specifies the return type of a function and, if so, find /// an appropriate place for it. /// /// \param i - a notional index which the search will start /// immediately inside /// /// \param onlyBlockPointers Whether we should only look into block /// pointer types (vs. all pointer types). static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, unsigned i, bool onlyBlockPointers) { assert(i <= declarator.getNumTypeObjects()); DeclaratorChunk *result = nullptr; // First, look inwards past parens for a function declarator. for (; i != 0; --i) { DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); switch (fnChunk.Kind) { case DeclaratorChunk::Paren: continue; // If we find anything except a function, bail out. case DeclaratorChunk::Pointer: case DeclaratorChunk::BlockPointer: case DeclaratorChunk::Array: case DeclaratorChunk::Reference: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pipe: return result; // If we do find a function declarator, scan inwards from that, // looking for a (block-)pointer declarator. case DeclaratorChunk::Function: for (--i; i != 0; --i) { DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); switch (ptrChunk.Kind) { case DeclaratorChunk::Paren: case DeclaratorChunk::Array: case DeclaratorChunk::Function: case DeclaratorChunk::Reference: case DeclaratorChunk::Pipe: continue; case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pointer: if (onlyBlockPointers) continue; LLVM_FALLTHROUGH; case DeclaratorChunk::BlockPointer: result = &ptrChunk; goto continue_outer; } llvm_unreachable("bad declarator chunk kind"); } // If we run out of declarators doing that, we're done. return result; } llvm_unreachable("bad declarator chunk kind"); // Okay, reconsider from our new point. continue_outer: ; } // Ran out of chunks, bail out. return result; } /// Given that an objc_gc attribute was written somewhere on a /// declaration *other* than on the declarator itself (for which, use /// distributeObjCPointerTypeAttrFromDeclarator), and given that it /// didn't apply in whatever position it was written in, try to move /// it to a more appropriate position. static void distributeObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type) { Declarator &declarator = state.getDeclarator(); // Move it to the outermost normal or block pointer declarator. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { DeclaratorChunk &chunk = declarator.getTypeObject(i-1); switch (chunk.Kind) { case DeclaratorChunk::Pointer: case DeclaratorChunk::BlockPointer: { // But don't move an ARC ownership attribute to the return type // of a block. DeclaratorChunk *destChunk = nullptr; if (state.isProcessingDeclSpec() && attr.getKind() == ParsedAttr::AT_ObjCOwnership) destChunk = maybeMovePastReturnType(declarator, i - 1, /*onlyBlockPointers=*/true); if (!destChunk) destChunk = &chunk; moveAttrFromListToList(attr, state.getCurrentAttributes(), destChunk->getAttrs()); return; } case DeclaratorChunk::Paren: case DeclaratorChunk::Array: continue; // We may be starting at the return type of a block. case DeclaratorChunk::Function: if (state.isProcessingDeclSpec() && attr.getKind() == ParsedAttr::AT_ObjCOwnership) { if (DeclaratorChunk *dest = maybeMovePastReturnType( declarator, i, /*onlyBlockPointers=*/true)) { moveAttrFromListToList(attr, state.getCurrentAttributes(), dest->getAttrs()); return; } } goto error; // Don't walk through these. case DeclaratorChunk::Reference: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pipe: goto error; } } error: diagnoseBadTypeAttribute(state.getSema(), attr, type); } /// Distribute an objc_gc type attribute that was written on the /// declarator. static void distributeObjCPointerTypeAttrFromDeclarator( TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { Declarator &declarator = state.getDeclarator(); // objc_gc goes on the innermost pointer to something that's not a // pointer. unsigned innermost = -1U; bool considerDeclSpec = true; for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { DeclaratorChunk &chunk = declarator.getTypeObject(i); switch (chunk.Kind) { case DeclaratorChunk::Pointer: case DeclaratorChunk::BlockPointer: innermost = i; continue; case DeclaratorChunk::Reference: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Paren: case DeclaratorChunk::Array: case DeclaratorChunk::Pipe: continue; case DeclaratorChunk::Function: considerDeclSpec = false; goto done; } } done: // That might actually be the decl spec if we weren't blocked by // anything in the declarator. if (considerDeclSpec) { if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { // Splice the attribute into the decl spec. Prevents the // attribute from being applied multiple times and gives // the source-location-filler something to work with. state.saveDeclSpecAttrs(); declarator.getMutableDeclSpec().getAttributes().takeOneFrom( declarator.getAttributes(), &attr); return; } } // Otherwise, if we found an appropriate chunk, splice the attribute // into it. if (innermost != -1U) { moveAttrFromListToList(attr, declarator.getAttributes(), declarator.getTypeObject(innermost).getAttrs()); return; } // Otherwise, diagnose when we're done building the type. declarator.getAttributes().remove(&attr); state.addIgnoredTypeAttr(attr); } /// A function type attribute was written somewhere in a declaration /// *other* than on the declarator itself or in the decl spec. Given /// that it didn't apply in whatever position it was written in, try /// to move it to a more appropriate position. static void distributeFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type) { Declarator &declarator = state.getDeclarator(); // Try to push the attribute from the return type of a function to // the function itself. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { DeclaratorChunk &chunk = declarator.getTypeObject(i-1); switch (chunk.Kind) { case DeclaratorChunk::Function: moveAttrFromListToList(attr, state.getCurrentAttributes(), chunk.getAttrs()); return; case DeclaratorChunk::Paren: case DeclaratorChunk::Pointer: case DeclaratorChunk::BlockPointer: case DeclaratorChunk::Array: case DeclaratorChunk::Reference: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pipe: continue; } } diagnoseBadTypeAttribute(state.getSema(), attr, type); } /// Try to distribute a function type attribute to the innermost /// function chunk or type. Returns true if the attribute was /// distributed, false if no location was found. static bool distributeFunctionTypeAttrToInnermost( TypeProcessingState &state, ParsedAttr &attr, ParsedAttributesView &attrList, QualType &declSpecType) { Declarator &declarator = state.getDeclarator(); // Put it on the innermost function chunk, if there is one. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { DeclaratorChunk &chunk = declarator.getTypeObject(i); if (chunk.Kind != DeclaratorChunk::Function) continue; moveAttrFromListToList(attr, attrList, chunk.getAttrs()); return true; } return handleFunctionTypeAttr(state, attr, declSpecType); } /// A function type attribute was written in the decl spec. Try to /// apply it somewhere. static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { state.saveDeclSpecAttrs(); // C++11 attributes before the decl specifiers actually appertain to // the declarators. Move them straight there. We don't support the // 'put them wherever you like' semantics we allow for GNU attributes. if (attr.isCXX11Attribute()) { moveAttrFromListToList(attr, state.getCurrentAttributes(), state.getDeclarator().getAttributes()); return; } // Try to distribute to the innermost. if (distributeFunctionTypeAttrToInnermost( state, attr, state.getCurrentAttributes(), declSpecType)) return; // If that failed, diagnose the bad attribute when the declarator is // fully built. state.addIgnoredTypeAttr(attr); } /// A function type attribute was written on the declarator. Try to /// apply it somewhere. static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { Declarator &declarator = state.getDeclarator(); // Try to distribute to the innermost. if (distributeFunctionTypeAttrToInnermost( state, attr, declarator.getAttributes(), declSpecType)) return; // If that failed, diagnose the bad attribute when the declarator is // fully built. declarator.getAttributes().remove(&attr); state.addIgnoredTypeAttr(attr); } /// Given that there are attributes written on the declarator /// itself, try to distribute any type attributes to the appropriate /// declarator chunk. /// /// These are attributes like the following: /// int f ATTR; /// int (f ATTR)(); /// but not necessarily this: /// int f() ATTR; static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, QualType &declSpecType) { // Collect all the type attributes from the declarator itself. assert(!state.getDeclarator().getAttributes().empty() && "declarator has no attrs!"); // The called functions in this loop actually remove things from the current // list, so iterating over the existing list isn't possible. Instead, make a // non-owning copy and iterate over that. ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; for (ParsedAttr &attr : AttrsCopy) { // Do not distribute C++11 attributes. They have strict rules for what // they appertain to. if (attr.isCXX11Attribute()) continue; switch (attr.getKind()) { OBJC_POINTER_TYPE_ATTRS_CASELIST: distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); break; FUNCTION_TYPE_ATTRS_CASELIST: distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); break; MS_TYPE_ATTRS_CASELIST: // Microsoft type attributes cannot go after the declarator-id. continue; NULLABILITY_TYPE_ATTRS_CASELIST: // Nullability specifiers cannot go after the declarator-id. // Objective-C __kindof does not get distributed. case ParsedAttr::AT_ObjCKindOf: continue; default: break; } } } /// Add a synthetic '()' to a block-literal declarator if it is /// required, given the return type. static void maybeSynthesizeBlockSignature(TypeProcessingState &state, QualType declSpecType) { Declarator &declarator = state.getDeclarator(); // First, check whether the declarator would produce a function, // i.e. whether the innermost semantic chunk is a function. if (declarator.isFunctionDeclarator()) { // If so, make that declarator a prototyped declarator. declarator.getFunctionTypeInfo().hasPrototype = true; return; } // If there are any type objects, the type as written won't name a // function, regardless of the decl spec type. This is because a // block signature declarator is always an abstract-declarator, and // abstract-declarators can't just be parentheses chunks. Therefore // we need to build a function chunk unless there are no type // objects and the decl spec type is a function. if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) return; // Note that there *are* cases with invalid declarators where // declarators consist solely of parentheses. In general, these // occur only in failed efforts to make function declarators, so // faking up the function chunk is still the right thing to do. // Otherwise, we need to fake up a function declarator. SourceLocation loc = declarator.getBeginLoc(); // ...and *prepend* it to the declarator. SourceLocation NoLoc; declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( /*HasProto=*/true, /*IsAmbiguous=*/false, /*LParenLoc=*/NoLoc, /*ArgInfo=*/nullptr, /*NumParams=*/0, /*EllipsisLoc=*/NoLoc, /*RParenLoc=*/NoLoc, /*RefQualifierIsLvalueRef=*/true, /*RefQualifierLoc=*/NoLoc, /*MutableLoc=*/NoLoc, EST_None, /*ESpecRange=*/SourceRange(), /*Exceptions=*/nullptr, /*ExceptionRanges=*/nullptr, /*NumExceptions=*/0, /*NoexceptExpr=*/nullptr, /*ExceptionSpecTokens=*/nullptr, /*DeclsInPrototype=*/None, loc, loc, declarator)); // For consistency, make sure the state still has us as processing // the decl spec. assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); state.setCurrentChunkIndex(declarator.getNumTypeObjects()); } static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID) { // If this occurs outside a template instantiation, warn the user about // it; they probably didn't mean to specify a redundant qualifier. typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { if (!(RemoveTQs & Qual.first)) continue; if (!S.inTemplateInstantiation()) { if (TypeQuals & Qual.first) S.Diag(Qual.second, DiagID) << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar << FixItHint::CreateRemoval(Qual.second); } TypeQuals &= ~Qual.first; } } /// Return true if this is omitted block return type. Also check type /// attributes and type qualifiers when returning true. static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, QualType Result) { if (!isOmittedBlockReturnType(declarator)) return false; // Warn if we see type attributes for omitted return type on a block literal. SmallVector<ParsedAttr *, 2> ToBeRemoved; for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { if (AL.isInvalid() || !AL.isTypeAttr()) continue; S.Diag(AL.getLoc(), diag::warn_block_literal_attributes_on_omitted_return_type) << AL; ToBeRemoved.push_back(&AL); } // Remove bad attributes from the list. for (ParsedAttr *AL : ToBeRemoved) declarator.getMutableDeclSpec().getAttributes().remove(AL); // Warn if we see type qualifiers for omitted return type on a block literal. const DeclSpec &DS = declarator.getDeclSpec(); unsigned TypeQuals = DS.getTypeQualifiers(); diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, diag::warn_block_literal_qualifiers_on_omitted_return_type); declarator.getMutableDeclSpec().ClearTypeQualifiers(); return true; } /// Apply Objective-C type arguments to the given type. static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, ArrayRef<TypeSourceInfo *> typeArgs, SourceRange typeArgsRange, bool failOnError = false) { // We can only apply type arguments to an Objective-C class type. const auto *objcObjectType = type->getAs<ObjCObjectType>(); if (!objcObjectType || !objcObjectType->getInterface()) { S.Diag(loc, diag::err_objc_type_args_non_class) << type << typeArgsRange; if (failOnError) return QualType(); return type; } // The class type must be parameterized. ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); if (!typeParams) { S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) << objcClass->getDeclName() << FixItHint::CreateRemoval(typeArgsRange); if (failOnError) return QualType(); return type; } // The type must not already be specialized. if (objcObjectType->isSpecialized()) { S.Diag(loc, diag::err_objc_type_args_specialized_class) << type << FixItHint::CreateRemoval(typeArgsRange); if (failOnError) return QualType(); return type; } // Check the type arguments. SmallVector<QualType, 4> finalTypeArgs; unsigned numTypeParams = typeParams->size(); bool anyPackExpansions = false; for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { TypeSourceInfo *typeArgInfo = typeArgs[i]; QualType typeArg = typeArgInfo->getType(); // Type arguments cannot have explicit qualifiers or nullability. // We ignore indirect sources of these, e.g. behind typedefs or // template arguments. if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { bool diagnosed = false; SourceRange rangeToRemove; if (auto attr = qual.getAs<AttributedTypeLoc>()) { rangeToRemove = attr.getLocalSourceRange(); if (attr.getTypePtr()->getImmediateNullability()) { typeArg = attr.getTypePtr()->getModifiedType(); S.Diag(attr.getBeginLoc(), diag::err_objc_type_arg_explicit_nullability) << typeArg << FixItHint::CreateRemoval(rangeToRemove); diagnosed = true; } } if (!diagnosed) { S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) << typeArg << typeArg.getQualifiers().getAsString() << FixItHint::CreateRemoval(rangeToRemove); } } // Remove qualifiers even if they're non-local. typeArg = typeArg.getUnqualifiedType(); finalTypeArgs.push_back(typeArg); if (typeArg->getAs<PackExpansionType>()) anyPackExpansions = true; // Find the corresponding type parameter, if there is one. ObjCTypeParamDecl *typeParam = nullptr; if (!anyPackExpansions) { if (i < numTypeParams) { typeParam = typeParams->begin()[i]; } else { // Too many arguments. S.Diag(loc, diag::err_objc_type_args_wrong_arity) << false << objcClass->getDeclName() << (unsigned)typeArgs.size() << numTypeParams; S.Diag(objcClass->getLocation(), diag::note_previous_decl) << objcClass; if (failOnError) return QualType(); return type; } } // Objective-C object pointer types must be substitutable for the bounds. if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { // If we don't have a type parameter to match against, assume // everything is fine. There was a prior pack expansion that // means we won't be able to match anything. if (!typeParam) { assert(anyPackExpansions && "Too many arguments?"); continue; } // Retrieve the bound. QualType bound = typeParam->getUnderlyingType(); const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); // Determine whether the type argument is substitutable for the bound. if (typeArgObjC->isObjCIdType()) { // When the type argument is 'id', the only acceptable type // parameter bound is 'id'. if (boundObjC->isObjCIdType()) continue; } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { // Otherwise, we follow the assignability rules. continue; } // Diagnose the mismatch. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), diag::err_objc_type_arg_does_not_match_bound) << typeArg << bound << typeParam->getDeclName(); S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) << typeParam->getDeclName(); if (failOnError) return QualType(); return type; } // Block pointer types are permitted for unqualified 'id' bounds. if (typeArg->isBlockPointerType()) { // If we don't have a type parameter to match against, assume // everything is fine. There was a prior pack expansion that // means we won't be able to match anything. if (!typeParam) { assert(anyPackExpansions && "Too many arguments?"); continue; } // Retrieve the bound. QualType bound = typeParam->getUnderlyingType(); if (bound->isBlockCompatibleObjCPointerType(S.Context)) continue; // Diagnose the mismatch. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), diag::err_objc_type_arg_does_not_match_bound) << typeArg << bound << typeParam->getDeclName(); S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) << typeParam->getDeclName(); if (failOnError) return QualType(); return type; } // Dependent types will be checked at instantiation time. if (typeArg->isDependentType()) { continue; } // Diagnose non-id-compatible type arguments. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), diag::err_objc_type_arg_not_id_compatible) << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); if (failOnError) return QualType(); return type; } // Make sure we didn't have the wrong number of arguments. if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { S.Diag(loc, diag::err_objc_type_args_wrong_arity) << (typeArgs.size() < typeParams->size()) << objcClass->getDeclName() << (unsigned)finalTypeArgs.size() << (unsigned)numTypeParams; S.Diag(objcClass->getLocation(), diag::note_previous_decl) << objcClass; if (failOnError) return QualType(); return type; } // Success. Form the specialized type. return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); } QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError) { QualType Result = QualType(Decl->getTypeForDecl(), 0); if (!Protocols.empty()) { bool HasError; Result = Context.applyObjCProtocolQualifiers(Result, Protocols, HasError); if (HasError) { Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); if (FailOnError) Result = QualType(); } if (FailOnError && Result.isNull()) return QualType(); } return Result; } QualType Sema::BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError) { QualType Result = BaseType; if (!TypeArgs.empty()) { Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc), FailOnError); if (FailOnError && Result.isNull()) return QualType(); } if (!Protocols.empty()) { bool HasError; Result = Context.applyObjCProtocolQualifiers(Result, Protocols, HasError); if (HasError) { Diag(Loc, diag::err_invalid_protocol_qualifiers) << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); if (FailOnError) Result = QualType(); } if (FailOnError && Result.isNull()) return QualType(); } return Result; } TypeResult Sema::actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc) { // Form id<protocol-list>. QualType Result = Context.getObjCObjectType( Context.ObjCBuiltinIdTy, { }, llvm::makeArrayRef( (ObjCProtocolDecl * const *)protocols.data(), protocols.size()), false); Result = Context.getObjCObjectPointerType(Result); TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); TypeLoc ResultTL = ResultTInfo->getTypeLoc(); auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() .castAs<ObjCObjectTypeLoc>(); ObjCObjectTL.setHasBaseTypeAsWritten(false); ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); // No type arguments. ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); // Fill in protocol qualifiers. ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); for (unsigned i = 0, n = protocols.size(); i != n; ++i) ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); // We're done. Return the completed type to the parser. return CreateParsedType(Result, ResultTInfo); } TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc) { TypeSourceInfo *BaseTypeInfo = nullptr; QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); if (T.isNull()) return true; // Handle missing type-source info. if (!BaseTypeInfo) BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); // Extract type arguments. SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { TypeSourceInfo *TypeArgInfo = nullptr; QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); if (TypeArg.isNull()) { ActualTypeArgInfos.clear(); break; } assert(TypeArgInfo && "No type source info?"); ActualTypeArgInfos.push_back(TypeArgInfo); } // Build the object type. QualType Result = BuildObjCObjectType( T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, ProtocolLAngleLoc, llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), Protocols.size()), ProtocolLocs, ProtocolRAngleLoc, /*FailOnError=*/false); if (Result == T) return BaseType; // Create source information for this type. TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); TypeLoc ResultTL = ResultTInfo->getTypeLoc(); // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an // object pointer type. Fill in source information for it. if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { // The '*' is implicit. ObjCObjectPointerTL.setStarLoc(SourceLocation()); ResultTL = ObjCObjectPointerTL.getPointeeLoc(); } auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); // Type argument information. if (ObjCObjectTL.getNumTypeArgs() > 0) { assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()); ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); } else { ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); } // Protocol qualifier information. if (ObjCObjectTL.getNumProtocols() > 0) { assert(ObjCObjectTL.getNumProtocols() == Protocols.size()); ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); for (unsigned i = 0, n = Protocols.size(); i != n; ++i) ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); } else { ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); } // Base type. ObjCObjectTL.setHasBaseTypeAsWritten(true); if (ObjCObjectTL.getType() == T) ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); else ObjCObjectTL.getBaseLoc().initialize(Context, Loc); // We're done. Return the completed type to the parser. return CreateParsedType(Result, ResultTInfo); } static OpenCLAccessAttr::Spelling getImageAccess(const ParsedAttributesView &Attrs) { for (const ParsedAttr &AL : Attrs) if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); return OpenCLAccessAttr::Keyword_read_only; } /// Convert the specified declspec to the appropriate type /// object. /// \param state Specifies the declarator containing the declaration specifier /// to be converted, along with other associated processing state. /// \returns The type described by the declaration specifiers. This function /// never returns null. static QualType ConvertDeclSpecToType(TypeProcessingState &state) { // FIXME: Should move the logic from DeclSpec::Finish to here for validity // checking. Sema &S = state.getSema(); Declarator &declarator = state.getDeclarator(); DeclSpec &DS = declarator.getMutableDeclSpec(); SourceLocation DeclLoc = declarator.getIdentifierLoc(); if (DeclLoc.isInvalid()) DeclLoc = DS.getBeginLoc(); ASTContext &Context = S.Context; QualType Result; switch (DS.getTypeSpecType()) { case DeclSpec::TST_void: Result = Context.VoidTy; break; case DeclSpec::TST_char: if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) Result = Context.CharTy; else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) Result = Context.SignedCharTy; else { assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value"); Result = Context.UnsignedCharTy; } break; case DeclSpec::TST_wchar: if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) Result = Context.WCharTy; else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) << DS.getSpecifierName(DS.getTypeSpecType(), Context.getPrintingPolicy()); Result = Context.getSignedWCharType(); } else { assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value"); S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) << DS.getSpecifierName(DS.getTypeSpecType(), Context.getPrintingPolicy()); Result = Context.getUnsignedWCharType(); } break; case DeclSpec::TST_char8: assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value"); Result = Context.Char8Ty; break; case DeclSpec::TST_char16: assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value"); Result = Context.Char16Ty; break; case DeclSpec::TST_char32: assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value"); Result = Context.Char32Ty; break; case DeclSpec::TST_unspecified: // If this is a missing declspec in a block literal return context, then it // is inferred from the return statements inside the block. // The declspec is always missing in a lambda expr context; it is either // specified with a trailing return type or inferred. if (S.getLangOpts().CPlusPlus14 && declarator.getContext() == DeclaratorContext::LambdaExprContext) { // In C++1y, a lambda's implicit return type is 'auto'. Result = Context.getAutoDeductType(); break; } else if (declarator.getContext() == DeclaratorContext::LambdaExprContext || checkOmittedBlockReturnType(S, declarator, Context.DependentTy)) { Result = Context.DependentTy; break; } // Unspecified typespec defaults to int in C90. However, the C90 grammar // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, // type-qualifier, or storage-class-specifier. If not, emit an extwarn. // Note that the one exception to this is function definitions, which are // allowed to be completely missing a declspec. This is handled in the // parser already though by it pretending to have seen an 'int' in this // case. if (S.getLangOpts().ImplicitInt) { // In C89 mode, we only warn if there is a completely missing declspec // when one is not allowed. if (DS.isEmpty()) { S.Diag(DeclLoc, diag::ext_missing_declspec) << DS.getSourceRange() << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); } } else if (!DS.hasTypeSpecifier()) { // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: // "At least one type specifier shall be given in the declaration // specifiers in each declaration, and in the specifier-qualifier list in // each struct declaration and type name." if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) { S.Diag(DeclLoc, diag::err_missing_type_specifier) << DS.getSourceRange(); // When this occurs in C++ code, often something is very broken with the // value being declared, poison it as invalid so we don't get chains of // errors. declarator.setInvalidType(true); } else if ((S.getLangOpts().OpenCLVersion >= 200 || S.getLangOpts().OpenCLCPlusPlus) && DS.isTypeSpecPipe()) { S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) << DS.getSourceRange(); declarator.setInvalidType(true); } else { S.Diag(DeclLoc, diag::ext_missing_type_specifier) << DS.getSourceRange(); } } LLVM_FALLTHROUGH; case DeclSpec::TST_int: { if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { switch (DS.getTypeSpecWidth()) { case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; case DeclSpec::TSW_short: Result = Context.ShortTy; break; case DeclSpec::TSW_long: Result = Context.LongTy; break; case DeclSpec::TSW_longlong: Result = Context.LongLongTy; // 'long long' is a C99 or C++11 feature. if (!S.getLangOpts().C99) { if (S.getLangOpts().CPlusPlus) S.Diag(DS.getTypeSpecWidthLoc(), S.getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); else S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); } break; } } else { switch (DS.getTypeSpecWidth()) { case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; case DeclSpec::TSW_longlong: Result = Context.UnsignedLongLongTy; // 'long long' is a C99 or C++11 feature. if (!S.getLangOpts().C99) { if (S.getLangOpts().CPlusPlus) S.Diag(DS.getTypeSpecWidthLoc(), S.getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); else S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); } break; } } break; } case DeclSpec::TST_accum: { switch (DS.getTypeSpecWidth()) { case DeclSpec::TSW_short: Result = Context.ShortAccumTy; break; case DeclSpec::TSW_unspecified: Result = Context.AccumTy; break; case DeclSpec::TSW_long: Result = Context.LongAccumTy; break; case DeclSpec::TSW_longlong: llvm_unreachable("Unable to specify long long as _Accum width"); } if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) Result = Context.getCorrespondingUnsignedType(Result); if (DS.isTypeSpecSat()) Result = Context.getCorrespondingSaturatedType(Result); break; } case DeclSpec::TST_fract: { switch (DS.getTypeSpecWidth()) { case DeclSpec::TSW_short: Result = Context.ShortFractTy; break; case DeclSpec::TSW_unspecified: Result = Context.FractTy; break; case DeclSpec::TSW_long: Result = Context.LongFractTy; break; case DeclSpec::TSW_longlong: llvm_unreachable("Unable to specify long long as _Fract width"); } if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) Result = Context.getCorrespondingUnsignedType(Result); if (DS.isTypeSpecSat()) Result = Context.getCorrespondingSaturatedType(Result); break; } case DeclSpec::TST_int128: if (!S.Context.getTargetInfo().hasInt128Type() && !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__int128"; if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) Result = Context.UnsignedInt128Ty; else Result = Context.Int128Ty; break; case DeclSpec::TST_float16: // CUDA host and device may have different _Float16 support, therefore // do not diagnose _Float16 usage to avoid false alarm. // ToDo: more precise diagnostics for CUDA. if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_Float16"; Result = Context.Float16Ty; break; case DeclSpec::TST_half: Result = Context.HalfTy; break; case DeclSpec::TST_float: Result = Context.FloatTy; break; case DeclSpec::TST_double: if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) Result = Context.LongDoubleTy; else Result = Context.DoubleTy; break; case DeclSpec::TST_float128: if (!S.Context.getTargetInfo().hasFloat128Type() && !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__float128"; Result = Context.Float128Ty; break; case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool break; case DeclSpec::TST_decimal32: // _Decimal32 case DeclSpec::TST_decimal64: // _Decimal64 case DeclSpec::TST_decimal128: // _Decimal128 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); Result = Context.IntTy; declarator.setInvalidType(true); break; case DeclSpec::TST_class: case DeclSpec::TST_enum: case DeclSpec::TST_union: case DeclSpec::TST_struct: case DeclSpec::TST_interface: { TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); if (!D) { // This can happen in C++ with ambiguous lookups. Result = Context.IntTy; declarator.setInvalidType(true); break; } // If the type is deprecated or unavailable, diagnose it. S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); // TypeQuals handled by caller. Result = Context.getTypeDeclType(D); // In both C and C++, make an ElaboratedType. ElaboratedTypeKeyword Keyword = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, DS.isTypeSpecOwned() ? D : nullptr); break; } case DeclSpec::TST_typename: { assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!"); Result = S.GetTypeFromParser(DS.getRepAsType()); if (Result.isNull()) { declarator.setInvalidType(true); } // TypeQuals handled by caller. break; } case DeclSpec::TST_typeofType: // FIXME: Preserve type source info. Result = S.GetTypeFromParser(DS.getRepAsType()); assert(!Result.isNull() && "Didn't get a type for typeof?"); if (!Result->isDependentType()) if (const TagType *TT = Result->getAs<TagType>()) S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); // TypeQuals handled by caller. Result = Context.getTypeOfType(Result); break; case DeclSpec::TST_typeofExpr: { Expr *E = DS.getRepAsExpr(); assert(E && "Didn't get an expression for typeof?"); // TypeQuals handled by caller. Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); if (Result.isNull()) { Result = Context.IntTy; declarator.setInvalidType(true); } break; } case DeclSpec::TST_decltype: { Expr *E = DS.getRepAsExpr(); assert(E && "Didn't get an expression for decltype?"); // TypeQuals handled by caller. Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); if (Result.isNull()) { Result = Context.IntTy; declarator.setInvalidType(true); } break; } case DeclSpec::TST_underlyingType: Result = S.GetTypeFromParser(DS.getRepAsType()); assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); Result = S.BuildUnaryTransformType(Result, UnaryTransformType::EnumUnderlyingType, DS.getTypeSpecTypeLoc()); if (Result.isNull()) { Result = Context.IntTy; declarator.setInvalidType(true); } break; case DeclSpec::TST_auto: Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false); break; case DeclSpec::TST_auto_type: Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); break; case DeclSpec::TST_decltype_auto: Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto, /*IsDependent*/ false); break; case DeclSpec::TST_unknown_anytype: Result = Context.UnknownAnyTy; break; case DeclSpec::TST_atomic: Result = S.GetTypeFromParser(DS.getRepAsType()); assert(!Result.isNull() && "Didn't get a type for _Atomic?"); Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); if (Result.isNull()) { Result = Context.IntTy; declarator.setInvalidType(true); } break; #define GENERIC_IMAGE_TYPE(ImgType, Id) \ case DeclSpec::TST_##ImgType##_t: \ switch (getImageAccess(DS.getAttributes())) { \ case OpenCLAccessAttr::Keyword_write_only: \ Result = Context.Id##WOTy; \ break; \ case OpenCLAccessAttr::Keyword_read_write: \ Result = Context.Id##RWTy; \ break; \ case OpenCLAccessAttr::Keyword_read_only: \ Result = Context.Id##ROTy; \ break; \ case OpenCLAccessAttr::SpellingNotCalculated: \ llvm_unreachable("Spelling not yet calculated"); \ } \ break; #include "clang/Basic/OpenCLImageTypes.def" case DeclSpec::TST_error: Result = Context.IntTy; declarator.setInvalidType(true); break; } if (S.getLangOpts().OpenCL && S.checkOpenCLDisabledTypeDeclSpec(DS, Result)) declarator.setInvalidType(true); bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || DS.getTypeSpecType() == DeclSpec::TST_fract; // Only fixed point types can be saturated if (DS.isTypeSpecSat() && !IsFixedPointType) S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) << DS.getSpecifierName(DS.getTypeSpecType(), Context.getPrintingPolicy()); // Handle complex types. if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { if (S.getLangOpts().Freestanding) S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); Result = Context.getComplexType(Result); } else if (DS.isTypeAltiVecVector()) { unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); VectorType::VectorKind VecKind = VectorType::AltiVecVector; if (DS.isTypeAltiVecPixel()) VecKind = VectorType::AltiVecPixel; else if (DS.isTypeAltiVecBool()) VecKind = VectorType::AltiVecBool; Result = Context.getVectorType(Result, 128/typeSize, VecKind); } // FIXME: Imaginary. if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); // Before we process any type attributes, synthesize a block literal // function declarator if necessary. if (declarator.getContext() == DeclaratorContext::BlockLiteralContext) maybeSynthesizeBlockSignature(state, Result); // Apply any type attributes from the decl spec. This may cause the // list of type attributes to be temporarily saved while the type // attributes are pushed around. // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) if (!DS.isTypeSpecPipe()) processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); // Apply const/volatile/restrict qualifiers to T. if (unsigned TypeQuals = DS.getTypeQualifiers()) { // Warn about CV qualifiers on function types. // C99 6.7.3p8: // If the specification of a function type includes any type qualifiers, // the behavior is undefined. // C++11 [dcl.fct]p7: // The effect of a cv-qualifier-seq in a function declarator is not the // same as adding cv-qualification on top of the function type. In the // latter case, the cv-qualifiers are ignored. if (TypeQuals && Result->isFunctionType()) { diagnoseAndRemoveTypeQualifiers( S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, S.getLangOpts().CPlusPlus ? diag::warn_typecheck_function_qualifiers_ignored : diag::warn_typecheck_function_qualifiers_unspecified); // No diagnostic for 'restrict' or '_Atomic' applied to a // function type; we'll diagnose those later, in BuildQualifiedType. } // C++11 [dcl.ref]p1: // Cv-qualified references are ill-formed except when the // cv-qualifiers are introduced through the use of a typedef-name // or decltype-specifier, in which case the cv-qualifiers are ignored. // // There don't appear to be any other contexts in which a cv-qualified // reference type could be formed, so the 'ill-formed' clause here appears // to never happen. if (TypeQuals && Result->isReferenceType()) { diagnoseAndRemoveTypeQualifiers( S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, diag::warn_typecheck_reference_qualifiers); } // C90 6.5.3 constraints: "The same type qualifier shall not appear more // than once in the same specifier-list or qualifier-list, either directly // or via one or more typedefs." if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus && TypeQuals & Result.getCVRQualifiers()) { if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) << "const"; } if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) << "volatile"; } // C90 doesn't have restrict nor _Atomic, so it doesn't force us to // produce a warning in this case. } QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); // If adding qualifiers fails, just use the unqualified type. if (Qualified.isNull()) declarator.setInvalidType(true); else Result = Qualified; } assert(!Result.isNull() && "This function should not return a null type"); return Result; } static std::string getPrintableNameForEntity(DeclarationName Entity) { if (Entity) return Entity.getAsString(); return "type name"; } QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS) { if (T.isNull()) return QualType(); // Ignore any attempt to form a cv-qualified reference. if (T->isReferenceType()) { Qs.removeConst(); Qs.removeVolatile(); } // Enforce C99 6.7.3p2: "Types other than pointer types derived from // object or incomplete types shall not be restrict-qualified." if (Qs.hasRestrict()) { unsigned DiagID = 0; QualType ProblemTy; if (T->isAnyPointerType() || T->isReferenceType() || T->isMemberPointerType()) { QualType EltTy; if (T->isObjCObjectPointerType()) EltTy = T; else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) EltTy = PTy->getPointeeType(); else EltTy = T->getPointeeType(); // If we have a pointer or reference, the pointee must have an object // incomplete type. if (!EltTy->isIncompleteOrObjectType()) { DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; ProblemTy = EltTy; } } else if (!T->isDependentType()) { DiagID = diag::err_typecheck_invalid_restrict_not_pointer; ProblemTy = T; } if (DiagID) { Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; Qs.removeRestrict(); } } return Context.getQualifiedType(T, Qs); } QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRAU, const DeclSpec *DS) { if (T.isNull()) return QualType(); // Ignore any attempt to form a cv-qualified reference. if (T->isReferenceType()) CVRAU &= ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and // TQ_unaligned; unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); // C11 6.7.3/5: // If the same qualifier appears more than once in the same // specifier-qualifier-list, either directly or via one or more typedefs, // the behavior is the same as if it appeared only once. // // It's not specified what happens when the _Atomic qualifier is applied to // a type specified with the _Atomic specifier, but we assume that this // should be treated as if the _Atomic qualifier appeared multiple times. if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { // C11 6.7.3/5: // If other qualifiers appear along with the _Atomic qualifier in a // specifier-qualifier-list, the resulting type is the so-qualified // atomic type. // // Don't need to worry about array types here, since _Atomic can't be // applied to such types. SplitQualType Split = T.getSplitUnqualifiedType(); T = BuildAtomicType(QualType(Split.Ty, 0), DS ? DS->getAtomicSpecLoc() : Loc); if (T.isNull()) return T; Split.Quals.addCVRQualifiers(CVR); return BuildQualifiedType(T, Loc, Split.Quals); } Qualifiers Q = Qualifiers::fromCVRMask(CVR); Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); return BuildQualifiedType(T, Loc, Q, DS); } /// Build a paren type including \p T. QualType Sema::BuildParenType(QualType T) { return Context.getParenType(T); } /// Given that we're building a pointer or reference to the given static QualType inferARCLifetimeForPointee(Sema &S, QualType type, SourceLocation loc, bool isReference) { // Bail out if retention is unrequired or already specified. if (!type->isObjCLifetimeType() || type.getObjCLifetime() != Qualifiers::OCL_None) return type; Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; // If the object type is const-qualified, we can safely use // __unsafe_unretained. This is safe (because there are no read // barriers), and it'll be safe to coerce anything but __weak* to // the resulting type. if (type.isConstQualified()) { implicitLifetime = Qualifiers::OCL_ExplicitNone; // Otherwise, check whether the static type does not require // retaining. This currently only triggers for Class (possibly // protocol-qualifed, and arrays thereof). } else if (type->isObjCARCImplicitlyUnretainedType()) { implicitLifetime = Qualifiers::OCL_ExplicitNone; // If we are in an unevaluated context, like sizeof, skip adding a // qualification. } else if (S.isUnevaluatedContext()) { return type; // If that failed, give an error and recover using __strong. __strong // is the option most likely to prevent spurious second-order diagnostics, // like when binding a reference to a field. } else { // These types can show up in private ivars in system headers, so // we need this to not be an error in those cases. Instead we // want to delay. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { S.DelayedDiagnostics.add( sema::DelayedDiagnostic::makeForbiddenType(loc, diag::err_arc_indirect_no_ownership, type, isReference)); } else { S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; } implicitLifetime = Qualifiers::OCL_Strong; } assert(implicitLifetime && "didn't infer any lifetime!"); Qualifiers qs; qs.addObjCLifetime(implicitLifetime); return S.Context.getQualifiedType(type, qs); } static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ std::string Quals = FnTy->getMethodQuals().getAsString(); switch (FnTy->getRefQualifier()) { case RQ_None: break; case RQ_LValue: if (!Quals.empty()) Quals += ' '; Quals += '&'; break; case RQ_RValue: if (!Quals.empty()) Quals += ' '; Quals += "&&"; break; } return Quals; } namespace { /// Kinds of declarator that cannot contain a qualified function type. /// /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: /// a function type with a cv-qualifier or a ref-qualifier can only appear /// at the topmost level of a type. /// /// Parens and member pointers are permitted. We don't diagnose array and /// function declarators, because they don't allow function types at all. /// /// The values of this enum are used in diagnostics. enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; } // end anonymous namespace /// Check whether the type T is a qualified function type, and if it is, /// diagnose that it cannot be contained within the given kind of declarator. static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, QualifiedFunctionKind QFK) { // Does T refer to a function type with a cv-qualifier or a ref-qualifier? const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); if (!FPT || (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) return false; S.Diag(Loc, diag::err_compound_qualified_function_type) << QFK << isa<FunctionType>(T.IgnoreParens()) << T << getFunctionQualifiersAsString(FPT); return true; } bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) { const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); if (!FPT || (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) return false; Diag(Loc, diag::err_qualified_function_typeid) << T << getFunctionQualifiersAsString(FPT); return true; } /// Build a pointer type. /// /// \param T The type to which we'll be building a pointer. /// /// \param Loc The location of the entity whose type involves this /// pointer type or, if there is no such entity, the location of the /// type that will have pointer type. /// /// \param Entity The name of the entity that involves the pointer /// type, if known. /// /// \returns A suitable pointer type, if there are no /// errors. Otherwise, returns a NULL type. QualType Sema::BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity) { if (T->isReferenceType()) { // C++ 8.3.2p4: There shall be no ... pointers to references ... Diag(Loc, diag::err_illegal_decl_pointer_to_reference) << getPrintableNameForEntity(Entity) << T; return QualType(); } if (T->isFunctionType() && getLangOpts().OpenCL) { Diag(Loc, diag::err_opencl_function_pointer); return QualType(); } if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) return QualType(); assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); // In ARC, it is forbidden to build pointers to unqualified pointers. if (getLangOpts().ObjCAutoRefCount) T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); // Build the pointer type. return Context.getPointerType(T); } /// Build a reference type. /// /// \param T The type to which we'll be building a reference. /// /// \param Loc The location of the entity whose type involves this /// reference type or, if there is no such entity, the location of the /// type that will have reference type. /// /// \param Entity The name of the entity that involves the reference /// type, if known. /// /// \returns A suitable reference type, if there are no /// errors. Otherwise, returns a NULL type. QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, SourceLocation Loc, DeclarationName Entity) { assert(Context.getCanonicalType(T) != Context.OverloadTy && "Unresolved overloaded function type"); // C++0x [dcl.ref]p6: // If a typedef (7.1.3), a type template-parameter (14.3.1), or a // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a // type T, an attempt to create the type "lvalue reference to cv TR" creates // the type "lvalue reference to T", while an attempt to create the type // "rvalue reference to cv TR" creates the type TR. bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); // C++ [dcl.ref]p4: There shall be no references to references. // // According to C++ DR 106, references to references are only // diagnosed when they are written directly (e.g., "int & &"), // but not when they happen via a typedef: // // typedef int& intref; // typedef intref& intref2; // // Parser::ParseDeclaratorInternal diagnoses the case where // references are written directly; here, we handle the // collapsing of references-to-references as described in C++0x. // DR 106 and 540 introduce reference-collapsing into C++98/03. // C++ [dcl.ref]p1: // A declarator that specifies the type "reference to cv void" // is ill-formed. if (T->isVoidType()) { Diag(Loc, diag::err_reference_to_void); return QualType(); } if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) return QualType(); // In ARC, it is forbidden to build references to unqualified pointers. if (getLangOpts().ObjCAutoRefCount) T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); // Handle restrict on references. if (LValueRef) return Context.getLValueReferenceType(T, SpelledAsLValue); return Context.getRValueReferenceType(T); } /// Build a Read-only Pipe type. /// /// \param T The type to which we'll be building a Pipe. /// /// \param Loc We do not use it for now. /// /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a /// NULL type. QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { return Context.getReadPipeType(T); } /// Build a Write-only Pipe type. /// /// \param T The type to which we'll be building a Pipe. /// /// \param Loc We do not use it for now. /// /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a /// NULL type. QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { return Context.getWritePipeType(T); } /// Check whether the specified array size makes the array type a VLA. If so, /// return true, if not, return the size of the array in SizeVal. static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode // (like gnu99, but not c99) accept any evaluatable value as an extension. class VLADiagnoser : public Sema::VerifyICEDiagnoser { public: VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { } void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; } } Diagnoser; return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, S.LangOpts.GNUMode || S.LangOpts.OpenCL).isInvalid(); } /// Build an array type. /// /// \param T The type of each element in the array. /// /// \param ASM C99 array size modifier (e.g., '*', 'static'). /// /// \param ArraySize Expression describing the size of the array. /// /// \param Brackets The range from the opening '[' to the closing ']'. /// /// \param Entity The name of the entity that involves the array /// type, if known. /// /// \returns A suitable array type, if there are no errors. Otherwise, /// returns a NULL type. QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity) { SourceLocation Loc = Brackets.getBegin(); if (getLangOpts().CPlusPlus) { // C++ [dcl.array]p1: // T is called the array element type; this type shall not be a reference // type, the (possibly cv-qualified) type void, a function type or an // abstract class type. // // C++ [dcl.array]p3: // When several "array of" specifications are adjacent, [...] only the // first of the constant expressions that specify the bounds of the arrays // may be omitted. // // Note: function types are handled in the common path with C. if (T->isReferenceType()) { Diag(Loc, diag::err_illegal_decl_array_of_references) << getPrintableNameForEntity(Entity) << T; return QualType(); } if (T->isVoidType() || T->isIncompleteArrayType()) { Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; return QualType(); } if (RequireNonAbstractType(Brackets.getBegin(), T, diag::err_array_of_abstract_type)) return QualType(); // Mentioning a member pointer type for an array type causes us to lock in // an inheritance model, even if it's inside an unused typedef. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) if (!MPTy->getClass()->isDependentType()) (void)isCompleteType(Loc, T); } else { // C99 6.7.5.2p1: If the element type is an incomplete or function type, // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) if (RequireCompleteType(Loc, T, diag::err_illegal_decl_array_incomplete_type)) return QualType(); } if (T->isFunctionType()) { Diag(Loc, diag::err_illegal_decl_array_of_functions) << getPrintableNameForEntity(Entity) << T; return QualType(); } if (const RecordType *EltTy = T->getAs<RecordType>()) { // If the element type is a struct or union that contains a variadic // array, accept it as a GNU extension: C99 6.7.2.1p2. if (EltTy->getDecl()->hasFlexibleArrayMember()) Diag(Loc, diag::ext_flexible_array_in_array) << T; } else if (T->isObjCObjectType()) { Diag(Loc, diag::err_objc_array_of_interfaces) << T; return QualType(); } // Do placeholder conversions on the array size expression. if (ArraySize && ArraySize->hasPlaceholderType()) { ExprResult Result = CheckPlaceholderExpr(ArraySize); if (Result.isInvalid()) return QualType(); ArraySize = Result.get(); } // Do lvalue-to-rvalue conversions on the array size expression. if (ArraySize && !ArraySize->isRValue()) { ExprResult Result = DefaultLvalueConversion(ArraySize); if (Result.isInvalid()) return QualType(); ArraySize = Result.get(); } // C99 6.7.5.2p1: The size expression shall have integer type. // C++11 allows contextual conversions to such types. if (!getLangOpts().CPlusPlus11 && ArraySize && !ArraySize->isTypeDependent() && !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) << ArraySize->getType() << ArraySize->getSourceRange(); return QualType(); } llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); if (!ArraySize) { if (ASM == ArrayType::Star) T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); else T = Context.getIncompleteArrayType(T, ASM, Quals); } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); } else if ((!T->isDependentType() && !T->isIncompleteType() && !T->isConstantSizeType()) || isArraySizeVLA(*this, ArraySize, ConstVal)) { // Even in C++11, don't allow contextual conversions in the array bound // of a VLA. if (getLangOpts().CPlusPlus11 && !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) << ArraySize->getType() << ArraySize->getSourceRange(); return QualType(); } // C99: an array with an element type that has a non-constant-size is a VLA. // C99: an array with a non-ICE size is a VLA. We accept any expression // that we can fold to a non-zero positive value as an extension. T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); } else { // C99 6.7.5.2p1: If the expression is a constant expression, it shall // have a value greater than zero. if (ConstVal.isSigned() && ConstVal.isNegative()) { if (Entity) Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); else Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size) << ArraySize->getSourceRange(); return QualType(); } if (ConstVal == 0) { // GCC accepts zero sized static arrays. We allow them when // we're not in a SFINAE context. Diag(ArraySize->getBeginLoc(), isSFINAEContext() ? diag::err_typecheck_zero_array_size : diag::ext_typecheck_zero_array_size) << ArraySize->getSourceRange(); if (ASM == ArrayType::Static) { Diag(ArraySize->getBeginLoc(), diag::warn_typecheck_zero_static_array_size) << ArraySize->getSourceRange(); ASM = ArrayType::Normal; } } else if (!T->isDependentType() && !T->isVariablyModifiedType() && !T->isIncompleteType() && !T->isUndeducedType()) { // Is the array too large? unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) << ConstVal.toString(10) << ArraySize->getSourceRange(); return QualType(); } } T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals); } // OpenCL v1.2 s6.9.d: variable length arrays are not supported. if (getLangOpts().OpenCL && T->isVariableArrayType()) { Diag(Loc, diag::err_opencl_vla); return QualType(); } if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { // CUDA device code and some other targets don't support VLAs. targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) ? diag::err_cuda_vla : diag::err_vla_unsupported) << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) ? CurrentCUDATarget() : CFT_InvalidTarget); } // If this is not C99, extwarn about VLA's and C99 array size modifiers. if (!getLangOpts().C99) { if (T->isVariableArrayType()) { // Prohibit the use of VLAs during template argument deduction. if (isSFINAEContext()) { Diag(Loc, diag::err_vla_in_sfinae); return QualType(); } // Just extwarn about VLAs. else Diag(Loc, diag::ext_vla); } else if (ASM != ArrayType::Normal || Quals != 0) Diag(Loc, getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx : diag::ext_c99_array_usage) << ASM; } if (T->isVariableArrayType()) { // Warn about VLAs for -Wvla. Diag(Loc, diag::warn_vla_used); } // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. if (getLangOpts().OpenCL) { const QualType ArrType = Context.getBaseElementType(T); if (ArrType->isBlockPointerType() || ArrType->isPipeType() || ArrType->isSamplerT() || ArrType->isImageType()) { Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; return QualType(); } } return T; } QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, SourceLocation AttrLoc) { // The base type must be integer (not Boolean or enumeration) or float, and // can't already be a vector. if (!CurType->isDependentType() && (!CurType->isBuiltinType() || CurType->isBooleanType() || (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) { Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; return QualType(); } if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, VectorType::GenericVector); llvm::APSInt VecSize(32); if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) { Diag(AttrLoc, diag::err_attribute_argument_type) << "vector_size" << AANT_ArgumentIntegerConstant << SizeExpr->getSourceRange(); return QualType(); } if (CurType->isDependentType()) return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, VectorType::GenericVector); unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8); unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); if (VectorSize == 0) { Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange(); return QualType(); } // vecSize is specified in bytes - convert to bits. if (VectorSize % TypeSize) { Diag(AttrLoc, diag::err_attribute_invalid_size) << SizeExpr->getSourceRange(); return QualType(); } if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) { Diag(AttrLoc, diag::err_attribute_size_too_large) << SizeExpr->getSourceRange(); return QualType(); } return Context.getVectorType(CurType, VectorSize / TypeSize, VectorType::GenericVector); } /// Build an ext-vector type. /// /// Run the required checks for the extended vector type. QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc) { // Unlike gcc's vector_size attribute, we do not allow vectors to be defined // in conjunction with complex types (pointers, arrays, functions, etc.). // // Additionally, OpenCL prohibits vectors of booleans (they're considered a // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors // of bool aren't allowed. if ((!T->isDependentType() && !T->isIntegerType() && !T->isRealFloatingType()) || T->isBooleanType()) { Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; return QualType(); } if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { llvm::APSInt vecSize(32); if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { Diag(AttrLoc, diag::err_attribute_argument_type) << "ext_vector_type" << AANT_ArgumentIntegerConstant << ArraySize->getSourceRange(); return QualType(); } // Unlike gcc's vector_size attribute, the size is specified as the // number of elements, not the number of bytes. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); if (vectorSize == 0) { Diag(AttrLoc, diag::err_attribute_zero_size) << ArraySize->getSourceRange(); return QualType(); } if (VectorType::isVectorSizeTooLarge(vectorSize)) { Diag(AttrLoc, diag::err_attribute_size_too_large) << ArraySize->getSourceRange(); return QualType(); } return Context.getExtVectorType(T, vectorSize); } return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); } bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { if (T->isArrayType() || T->isFunctionType()) { Diag(Loc, diag::err_func_returning_array_function) << T->isFunctionType() << T; return true; } // Functions cannot return half FP. if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << FixItHint::CreateInsertion(Loc, "*"); return true; } // Methods cannot return interface types. All ObjC objects are // passed by reference. if (T->isObjCObjectType()) { Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T << FixItHint::CreateInsertion(Loc, "*"); return true; } // __ptrauth is illegal on a function return type. if (T.getPointerAuth()) { Diag(Loc, diag::err_ptrauth_qualifier_return) << T; return true; } if (T.hasNonTrivialToPrimitiveDestructCUnion() || T.hasNonTrivialToPrimitiveCopyCUnion()) checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); // C++2a [dcl.fct]p12: // A volatile-qualified return type is deprecated if (T.isVolatileQualified() && getLangOpts().CPlusPlus2a) Diag(Loc, diag::warn_deprecated_volatile_return) << T; return false; } /// Check the extended parameter information. Most of the necessary /// checking should occur when applying the parameter attribute; the /// only other checks required are positional restrictions. static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, const FunctionProtoType::ExtProtoInfo &EPI, llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { assert(EPI.ExtParameterInfos && "shouldn't get here without param infos"); bool hasCheckedSwiftCall = false; auto checkForSwiftCC = [&](unsigned paramIndex) { // Only do this once. if (hasCheckedSwiftCall) return; hasCheckedSwiftCall = true; if (EPI.ExtInfo.getCC() == CC_Swift) return; S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()); }; for (size_t paramIndex = 0, numParams = paramTypes.size(); paramIndex != numParams; ++paramIndex) { switch (EPI.ExtParameterInfos[paramIndex].getABI()) { // Nothing interesting to check for orindary-ABI parameters. case ParameterABI::Ordinary: continue; // swift_indirect_result parameters must be a prefix of the function // arguments. case ParameterABI::SwiftIndirectResult: checkForSwiftCC(paramIndex); if (paramIndex != 0 && EPI.ExtParameterInfos[paramIndex - 1].getABI() != ParameterABI::SwiftIndirectResult) { S.Diag(getParamLoc(paramIndex), diag::err_swift_indirect_result_not_first); } continue; case ParameterABI::SwiftContext: checkForSwiftCC(paramIndex); continue; // swift_error parameters must be preceded by a swift_context parameter. case ParameterABI::SwiftErrorResult: checkForSwiftCC(paramIndex); if (paramIndex == 0 || EPI.ExtParameterInfos[paramIndex - 1].getABI() != ParameterABI::SwiftContext) { S.Diag(getParamLoc(paramIndex), diag::err_swift_error_result_not_after_swift_context); } continue; } llvm_unreachable("bad ABI kind"); } } QualType Sema::BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI) { bool Invalid = false; Invalid |= CheckFunctionReturnType(T, Loc); for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { // FIXME: Loc is too inprecise here, should use proper locations for args. QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); if (ParamType->isVoidType()) { Diag(Loc, diag::err_param_with_void_type); Invalid = true; } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { // Disallow half FP arguments. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << FixItHint::CreateInsertion(Loc, "*"); Invalid = true; } else if (ParamType.getPointerAuth()) { // __ptrauth is illegal on a function return type. Diag(Loc, diag::err_ptrauth_qualifier_param) << T; Invalid = true; } // C++2a [dcl.fct]p4: // A parameter with volatile-qualified type is deprecated if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus2a) Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType; ParamTypes[Idx] = ParamType; } if (EPI.ExtParameterInfos) { checkExtParameterInfos(*this, ParamTypes, EPI, [=](unsigned i) { return Loc; }); } if (EPI.ExtInfo.getProducesResult()) { // This is just a warning, so we can't fail to build if we see it. checkNSReturnsRetainedReturnType(Loc, T); } if (Invalid) return QualType(); return Context.getFunctionType(T, ParamTypes, EPI); } /// Build a member pointer type \c T Class::*. /// /// \param T the type to which the member pointer refers. /// \param Class the class type into which the member pointer points. /// \param Loc the location where this type begins /// \param Entity the name of the entity that will have this member pointer type /// /// \returns a member pointer type, if successful, or a NULL type if there was /// an error. QualType Sema::BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity) { // Verify that we're not building a pointer to pointer to function with // exception specification. if (CheckDistantExceptionSpec(T)) { Diag(Loc, diag::err_distant_exception_spec); return QualType(); } // C++ 8.3.3p3: A pointer to member shall not point to ... a member // with reference type, or "cv void." if (T->isReferenceType()) { Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) << getPrintableNameForEntity(Entity) << T; return QualType(); } if (T->isVoidType()) { Diag(Loc, diag::err_illegal_decl_mempointer_to_void) << getPrintableNameForEntity(Entity); return QualType(); } if (!Class->isDependentType() && !Class->isRecordType()) { Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; return QualType(); } // Adjust the default free function calling convention to the default method // calling convention. bool IsCtorOrDtor = (Entity.getNameKind() == DeclarationName::CXXConstructorName) || (Entity.getNameKind() == DeclarationName::CXXDestructorName); if (T->isFunctionType()) adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); return Context.getMemberPointerType(T, Class.getTypePtr()); } /// Build a block pointer type. /// /// \param T The type to which we'll be building a block pointer. /// /// \param Loc The source location, used for diagnostics. /// /// \param Entity The name of the entity that involves the block pointer /// type, if known. /// /// \returns A suitable block pointer type, if there are no /// errors. Otherwise, returns a NULL type. QualType Sema::BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity) { if (!T->isFunctionType()) { Diag(Loc, diag::err_nonfunction_block_type); return QualType(); } if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) return QualType(); return Context.getBlockPointerType(T); } QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { QualType QT = Ty.get(); if (QT.isNull()) { if (TInfo) *TInfo = nullptr; return QualType(); } TypeSourceInfo *DI = nullptr; if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { QT = LIT->getType(); DI = LIT->getTypeSourceInfo(); } if (TInfo) *TInfo = DI; return QT; } static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex); /// Given that this is the declaration of a parameter under ARC, /// attempt to infer attributes and such for pointer-to-whatever /// types. static void inferARCWriteback(TypeProcessingState &state, QualType &declSpecType) { Sema &S = state.getSema(); Declarator &declarator = state.getDeclarator(); // TODO: should we care about decl qualifiers? // Check whether the declarator has the expected form. We walk // from the inside out in order to make the block logic work. unsigned outermostPointerIndex = 0; bool isBlockPointer = false; unsigned numPointers = 0; for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { unsigned chunkIndex = i; DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); switch (chunk.Kind) { case DeclaratorChunk::Paren: // Ignore parens. break; case DeclaratorChunk::Reference: case DeclaratorChunk::Pointer: // Count the number of pointers. Treat references // interchangeably as pointers; if they're mis-ordered, normal // type building will discover that. outermostPointerIndex = chunkIndex; numPointers++; break; case DeclaratorChunk::BlockPointer: // If we have a pointer to block pointer, that's an acceptable // indirect reference; anything else is not an application of // the rules. if (numPointers != 1) return; numPointers++; outermostPointerIndex = chunkIndex; isBlockPointer = true; // We don't care about pointer structure in return values here. goto done; case DeclaratorChunk::Array: // suppress if written (id[])? case DeclaratorChunk::Function: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pipe: return; } } done: // If we have *one* pointer, then we want to throw the qualifier on // the declaration-specifiers, which means that it needs to be a // retainable object type. if (numPointers == 1) { // If it's not a retainable object type, the rule doesn't apply. if (!declSpecType->isObjCRetainableType()) return; // If it already has lifetime, don't do anything. if (declSpecType.getObjCLifetime()) return; // Otherwise, modify the type in-place. Qualifiers qs; if (declSpecType->isObjCARCImplicitlyUnretainedType()) qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); else qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); declSpecType = S.Context.getQualifiedType(declSpecType, qs); // If we have *two* pointers, then we want to throw the qualifier on // the outermost pointer. } else if (numPointers == 2) { // If we don't have a block pointer, we need to check whether the // declaration-specifiers gave us something that will turn into a // retainable object pointer after we slap the first pointer on it. if (!isBlockPointer && !declSpecType->isObjCObjectType()) return; // Look for an explicit lifetime attribute there. DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); if (chunk.Kind != DeclaratorChunk::Pointer && chunk.Kind != DeclaratorChunk::BlockPointer) return; for (const ParsedAttr &AL : chunk.getAttrs()) if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) return; transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, outermostPointerIndex); // Any other number of pointers/references does not trigger the rule. } else return; // TODO: mark whether we did this inference? } void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc, SourceLocation VolatileQualLoc, SourceLocation RestrictQualLoc, SourceLocation AtomicQualLoc, SourceLocation UnalignedQualLoc) { if (!Quals) return; struct Qual { const char *Name; unsigned Mask; SourceLocation Loc; } const QualKinds[5] = { { "const", DeclSpec::TQ_const, ConstQualLoc }, { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } }; SmallString<32> QualStr; unsigned NumQuals = 0; SourceLocation Loc; FixItHint FixIts[5]; // Build a string naming the redundant qualifiers. for (auto &E : QualKinds) { if (Quals & E.Mask) { if (!QualStr.empty()) QualStr += ' '; QualStr += E.Name; // If we have a location for the qualifier, offer a fixit. SourceLocation QualLoc = E.Loc; if (QualLoc.isValid()) { FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); if (Loc.isInvalid() || getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) Loc = QualLoc; } ++NumQuals; } } Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; } // Diagnose pointless type qualifiers on the return type of a function. static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex) { if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { // FIXME: TypeSourceInfo doesn't preserve location information for // qualifiers. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, RetTy.getLocalCVRQualifiers(), D.getIdentifierLoc()); return; } for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, End = D.getNumTypeObjects(); OuterChunkIndex != End; ++OuterChunkIndex) { DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); switch (OuterChunk.Kind) { case DeclaratorChunk::Paren: continue; case DeclaratorChunk::Pointer: { DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; S.diagnoseIgnoredQualifiers( diag::warn_qual_return_type, PTI.TypeQuals, SourceLocation(), SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc), SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc)); return; } case DeclaratorChunk::Function: case DeclaratorChunk::BlockPointer: case DeclaratorChunk::Reference: case DeclaratorChunk::Array: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pipe: // FIXME: We can't currently provide an accurate source location and a // fix-it hint for these. unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, RetTy.getCVRQualifiers() | AtomicQual, D.getIdentifierLoc()); return; } llvm_unreachable("unknown declarator chunk kind"); } // If the qualifiers come from a conversion function type, don't diagnose // them -- they're not necessarily redundant, since such a conversion // operator can be explicitly called as "x.operator const int()". if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) return; // Just parens all the way out to the decl specifiers. Diagnose any qualifiers // which are present there. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, D.getDeclSpec().getTypeQualifiers(), D.getIdentifierLoc(), D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), D.getDeclSpec().getRestrictSpecLoc(), D.getDeclSpec().getAtomicSpecLoc(), D.getDeclSpec().getUnalignedSpecLoc()); } static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TypeSourceInfo *&ReturnTypeInfo) { Sema &SemaRef = state.getSema(); Declarator &D = state.getDeclarator(); QualType T; ReturnTypeInfo = nullptr; // The TagDecl owned by the DeclSpec. TagDecl *OwnedTagDecl = nullptr; switch (D.getName().getKind()) { case UnqualifiedIdKind::IK_ImplicitSelfParam: case UnqualifiedIdKind::IK_OperatorFunctionId: case UnqualifiedIdKind::IK_Identifier: case UnqualifiedIdKind::IK_LiteralOperatorId: case UnqualifiedIdKind::IK_TemplateId: T = ConvertDeclSpecToType(state); if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); // Owned declaration is embedded in declarator. OwnedTagDecl->setEmbeddedInDeclarator(true); } break; case UnqualifiedIdKind::IK_ConstructorName: case UnqualifiedIdKind::IK_ConstructorTemplateId: case UnqualifiedIdKind::IK_DestructorName: // Constructors and destructors don't have return types. Use // "void" instead. T = SemaRef.Context.VoidTy; processTypeAttrs(state, T, TAL_DeclSpec, D.getMutableDeclSpec().getAttributes()); break; case UnqualifiedIdKind::IK_DeductionGuideName: // Deduction guides have a trailing return type and no type in their // decl-specifier sequence. Use a placeholder return type for now. T = SemaRef.Context.DependentTy; break; case UnqualifiedIdKind::IK_ConversionFunctionId: // The result type of a conversion function is the type that it // converts to. T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, &ReturnTypeInfo); break; } if (!D.getAttributes().empty()) distributeTypeAttrsFromDeclarator(state, T); // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. if (DeducedType *Deduced = T->getContainedDeducedType()) { AutoType *Auto = dyn_cast<AutoType>(Deduced); int Error = -1; // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or // class template argument deduction)? bool IsCXXAutoType = (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); bool IsDeducedReturnType = false; switch (D.getContext()) { case DeclaratorContext::LambdaExprContext: // Declared return type of a lambda-declarator is implicit and is always // 'auto'. break; case DeclaratorContext::ObjCParameterContext: case DeclaratorContext::ObjCResultContext: case DeclaratorContext::PrototypeContext: Error = 0; break; case DeclaratorContext::LambdaExprParameterContext: // In C++14, generic lambdas allow 'auto' in their parameters. if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) Error = 16; else { // If auto is mentioned in a lambda parameter context, convert it to a // template parameter type. sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda(); assert(LSI && "No LambdaScopeInfo on the stack!"); const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; const unsigned AutoParameterPosition = LSI->TemplateParams.size(); const bool IsParameterPack = D.hasEllipsis(); // Create the TemplateTypeParmDecl here to retrieve the corresponding // template parameter type. Template parameters are temporarily added // to the TU until the associated TemplateDecl is created. TemplateTypeParmDecl *CorrespondingTemplateParam = TemplateTypeParmDecl::Create( SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(), /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(), TemplateParameterDepth, AutoParameterPosition, /*Identifier*/ nullptr, false, IsParameterPack); CorrespondingTemplateParam->setImplicit(); LSI->TemplateParams.push_back(CorrespondingTemplateParam); // Replace the 'auto' in the function parameter with this invented // template type parameter. // FIXME: Retain some type sugar to indicate that this was written // as 'auto'. T = state.ReplaceAutoType( T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0)); } break; case DeclaratorContext::MemberContext: { if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || D.isFunctionDeclarator()) break; bool Cxx = SemaRef.getLangOpts().CPlusPlus; switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { case TTK_Enum: llvm_unreachable("unhandled tag kind"); case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; case TTK_Class: Error = 5; /* Class member */ break; case TTK_Interface: Error = 6; /* Interface member */ break; } if (D.getDeclSpec().isFriendSpecified()) Error = 20; // Friend type break; } case DeclaratorContext::CXXCatchContext: case DeclaratorContext::ObjCCatchContext: Error = 7; // Exception declaration break; case DeclaratorContext::TemplateParamContext: if (isa<DeducedTemplateSpecializationType>(Deduced)) Error = 19; // Template parameter else if (!SemaRef.getLangOpts().CPlusPlus17) Error = 8; // Template parameter (until C++17) break; case DeclaratorContext::BlockLiteralContext: Error = 9; // Block literal break; case DeclaratorContext::TemplateArgContext: // Within a template argument list, a deduced template specialization // type will be reinterpreted as a template template argument. if (isa<DeducedTemplateSpecializationType>(Deduced) && !D.getNumTypeObjects() && D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) break; LLVM_FALLTHROUGH; case DeclaratorContext::TemplateTypeArgContext: Error = 10; // Template type argument break; case DeclaratorContext::AliasDeclContext: case DeclaratorContext::AliasTemplateContext: Error = 12; // Type alias break; case DeclaratorContext::TrailingReturnContext: case DeclaratorContext::TrailingReturnVarContext: if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) Error = 13; // Function return type IsDeducedReturnType = true; break; case DeclaratorContext::ConversionIdContext: if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) Error = 14; // conversion-type-id IsDeducedReturnType = true; break; case DeclaratorContext::FunctionalCastContext: if (isa<DeducedTemplateSpecializationType>(Deduced)) break; LLVM_FALLTHROUGH; case DeclaratorContext::TypeNameContext: Error = 15; // Generic break; case DeclaratorContext::FileContext: case DeclaratorContext::BlockContext: case DeclaratorContext::ForContext: case DeclaratorContext::InitStmtContext: case DeclaratorContext::ConditionContext: // FIXME: P0091R3 (erroneously) does not permit class template argument // deduction in conditions, for-init-statements, and other declarations // that are not simple-declarations. break; case DeclaratorContext::CXXNewContext: // FIXME: P0091R3 does not permit class template argument deduction here, // but we follow GCC and allow it anyway. if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) Error = 17; // 'new' type break; case DeclaratorContext::KNRTypeListContext: Error = 18; // K&R function parameter break; } if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) Error = 11; // In Objective-C it is an error to use 'auto' on a function declarator // (and everywhere for '__auto_type'). if (D.isFunctionDeclarator() && (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) Error = 13; bool HaveTrailing = false; // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator // contains a trailing return type. That is only legal at the outermost // level. Check all declarator chunks (outermost first) anyway, to give // better diagnostics. // We don't support '__auto_type' with trailing return types. // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'? if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType && D.hasTrailingReturnType()) { HaveTrailing = true; Error = -1; } SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) AutoRange = D.getName().getSourceRange(); if (Error != -1) { unsigned Kind; if (Auto) { switch (Auto->getKeyword()) { case AutoTypeKeyword::Auto: Kind = 0; break; case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; case AutoTypeKeyword::GNUAutoType: Kind = 2; break; } } else { assert(isa<DeducedTemplateSpecializationType>(Deduced) && "unknown auto type"); Kind = 3; } auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) << QualType(Deduced, 0) << AutoRange; if (auto *TD = TN.getAsTemplateDecl()) SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); T = SemaRef.Context.IntTy; D.setInvalidType(true); } else if (Auto && !HaveTrailing && D.getContext() != DeclaratorContext::LambdaExprContext) { // If there was a trailing return type, we already got // warn_cxx98_compat_trailing_return_type in the parser. SemaRef.Diag(AutoRange.getBegin(), D.getContext() == DeclaratorContext::LambdaExprParameterContext ? diag::warn_cxx11_compat_generic_lambda : IsDeducedReturnType ? diag::warn_cxx11_compat_deduced_return_type : diag::warn_cxx98_compat_auto_type_specifier) << AutoRange; } } if (SemaRef.getLangOpts().CPlusPlus && OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { // Check the contexts where C++ forbids the declaration of a new class // or enumeration in a type-specifier-seq. unsigned DiagID = 0; switch (D.getContext()) { case DeclaratorContext::TrailingReturnContext: case DeclaratorContext::TrailingReturnVarContext: // Class and enumeration definitions are syntactically not allowed in // trailing return types. llvm_unreachable("parser should not have allowed this"); break; case DeclaratorContext::FileContext: case DeclaratorContext::MemberContext: case DeclaratorContext::BlockContext: case DeclaratorContext::ForContext: case DeclaratorContext::InitStmtContext: case DeclaratorContext::BlockLiteralContext: case DeclaratorContext::LambdaExprContext: // C++11 [dcl.type]p3: // A type-specifier-seq shall not define a class or enumeration unless // it appears in the type-id of an alias-declaration (7.1.3) that is not // the declaration of a template-declaration. case DeclaratorContext::AliasDeclContext: break; case DeclaratorContext::AliasTemplateContext: DiagID = diag::err_type_defined_in_alias_template; break; case DeclaratorContext::TypeNameContext: case DeclaratorContext::FunctionalCastContext: case DeclaratorContext::ConversionIdContext: case DeclaratorContext::TemplateParamContext: case DeclaratorContext::CXXNewContext: case DeclaratorContext::CXXCatchContext: case DeclaratorContext::ObjCCatchContext: case DeclaratorContext::TemplateArgContext: case DeclaratorContext::TemplateTypeArgContext: DiagID = diag::err_type_defined_in_type_specifier; break; case DeclaratorContext::PrototypeContext: case DeclaratorContext::LambdaExprParameterContext: case DeclaratorContext::ObjCParameterContext: case DeclaratorContext::ObjCResultContext: case DeclaratorContext::KNRTypeListContext: // C++ [dcl.fct]p6: // Types shall not be defined in return or parameter types. DiagID = diag::err_type_defined_in_param_type; break; case DeclaratorContext::ConditionContext: // C++ 6.4p2: // The type-specifier-seq shall not contain typedef and shall not declare // a new class or enumeration. DiagID = diag::err_type_defined_in_condition; break; } if (DiagID != 0) { SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) << SemaRef.Context.getTypeDeclType(OwnedTagDecl); D.setInvalidType(true); } } assert(!T.isNull() && "This function should not return a null type"); return T; } /// Produce an appropriate diagnostic for an ambiguity between a function /// declarator and a C++ direct-initializer. static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, DeclaratorChunk &DeclType, QualType RT) { const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); // If the return type is void there is no ambiguity. if (RT->isVoidType()) return; // An initializer for a non-class type can have at most one argument. if (!RT->isRecordType() && FTI.NumParams > 1) return; // An initializer for a reference must have exactly one argument. if (RT->isReferenceType() && FTI.NumParams != 1) return; // Only warn if this declarator is declaring a function at block scope, and // doesn't have a storage class (such as 'extern') specified. if (!D.isFunctionDeclarator() || D.getFunctionDefinitionKind() != FDK_Declaration || !S.CurContext->isFunctionOrMethod() || D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified) return; // Inside a condition, a direct initializer is not permitted. We allow one to // be parsed in order to give better diagnostics in condition parsing. if (D.getContext() == DeclaratorContext::ConditionContext) return; SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); S.Diag(DeclType.Loc, FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration : diag::warn_empty_parens_are_function_decl) << ParenRange; // If the declaration looks like: // T var1, // f(); // and name lookup finds a function named 'f', then the ',' was // probably intended to be a ';'. if (!D.isFirstDeclarator() && D.getIdentifier()) { FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); if (Comma.getFileID() != Name.getFileID() || Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { LookupResult Result(S, D.getIdentifier(), SourceLocation(), Sema::LookupOrdinaryName); if (S.LookupName(Result, S.getCurScope())) S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << D.getIdentifier(); Result.suppressDiagnostics(); } } if (FTI.NumParams > 0) { // For a declaration with parameters, eg. "T var(T());", suggest adding // parens around the first parameter to turn the declaration into a // variable declaration. SourceRange Range = FTI.Params[0].Param->getSourceRange(); SourceLocation B = Range.getBegin(); SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); // FIXME: Maybe we should suggest adding braces instead of parens // in C++11 for classes that don't have an initializer_list constructor. S.Diag(B, diag::note_additional_parens_for_variable_declaration) << FixItHint::CreateInsertion(B, "(") << FixItHint::CreateInsertion(E, ")"); } else { // For a declaration without parameters, eg. "T var();", suggest replacing // the parens with an initializer to turn the declaration into a variable // declaration. const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); // Empty parens mean value-initialization, and no parens mean // default initialization. These are equivalent if the default // constructor is user-provided or if zero-initialization is a // no-op. if (RD && RD->hasDefinition() && (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) << FixItHint::CreateRemoval(ParenRange); else { std::string Init = S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); if (Init.empty() && S.LangOpts.CPlusPlus11) Init = "{}"; if (!Init.empty()) S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) << FixItHint::CreateReplacement(ParenRange, Init); } } } /// Produce an appropriate diagnostic for a declarator with top-level /// parentheses. static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); assert(Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses"); // This is a syntactic check; we're not interested in cases that arise // during template instantiation. if (S.inTemplateInstantiation()) return; // Check whether this could be intended to be a construction of a temporary // object in C++ via a function-style cast. bool CouldBeTemporaryObject = S.getLangOpts().CPlusPlus && D.isExpressionContext() && !D.isInvalidType() && D.getIdentifier() && D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && (T->isRecordType() || T->isDependentType()) && D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); bool StartsWithDeclaratorId = true; for (auto &C : D.type_objects()) { switch (C.Kind) { case DeclaratorChunk::Paren: if (&C == &Paren) continue; LLVM_FALLTHROUGH; case DeclaratorChunk::Pointer: StartsWithDeclaratorId = false; continue; case DeclaratorChunk::Array: if (!C.Arr.NumElts) CouldBeTemporaryObject = false; continue; case DeclaratorChunk::Reference: // FIXME: Suppress the warning here if there is no initializer; we're // going to give an error anyway. // We assume that something like 'T (&x) = y;' is highly likely to not // be intended to be a temporary object. CouldBeTemporaryObject = false; StartsWithDeclaratorId = false; continue; case DeclaratorChunk::Function: // In a new-type-id, function chunks require parentheses. if (D.getContext() == DeclaratorContext::CXXNewContext) return; // FIXME: "A(f())" deserves a vexing-parse warning, not just a // redundant-parens warning, but we don't know whether the function // chunk was syntactically valid as an expression here. CouldBeTemporaryObject = false; continue; case DeclaratorChunk::BlockPointer: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pipe: // These cannot appear in expressions. CouldBeTemporaryObject = false; StartsWithDeclaratorId = false; continue; } } // FIXME: If there is an initializer, assume that this is not intended to be // a construction of a temporary object. // Check whether the name has already been declared; if not, this is not a // function-style cast. if (CouldBeTemporaryObject) { LookupResult Result(S, D.getIdentifier(), SourceLocation(), Sema::LookupOrdinaryName); if (!S.LookupName(Result, S.getCurScope())) CouldBeTemporaryObject = false; Result.suppressDiagnostics(); } SourceRange ParenRange(Paren.Loc, Paren.EndLoc); if (!CouldBeTemporaryObject) { // If we have A (::B), the parentheses affect the meaning of the program. // Suppress the warning in that case. Don't bother looking at the DeclSpec // here: even (e.g.) "int ::x" is visually ambiguous even though it's // formally unambiguous. if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; NNS = NNS->getPrefix()) { if (NNS->getKind() == NestedNameSpecifier::Global) return; } } S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) << ParenRange << FixItHint::CreateRemoval(Paren.Loc) << FixItHint::CreateRemoval(Paren.EndLoc); return; } S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) << ParenRange << D.getIdentifier(); auto *RD = T->getAsCXXRecordDecl(); if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) S.Diag(Paren.Loc, diag::note_raii_guard_add_name) << FixItHint::CreateInsertion(Paren.Loc, " varname") << T << D.getIdentifier(); // FIXME: A cast to void is probably a better suggestion in cases where it's // valid (when there is no initializer and we're not in a condition). S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) << FixItHint::CreateInsertion(D.getBeginLoc(), "(") << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) << FixItHint::CreateRemoval(Paren.Loc) << FixItHint::CreateRemoval(Paren.EndLoc); } /// Helper for figuring out the default CC for a function declarator type. If /// this is the outermost chunk, then we can determine the CC from the /// declarator context. If not, then this could be either a member function /// type or normal function type. static CallingConv getCCForDeclaratorChunk( Sema &S, Declarator &D, const ParsedAttributesView &AttrList, const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); // Check for an explicit CC attribute. for (const ParsedAttr &AL : AttrList) { switch (AL.getKind()) { CALLING_CONV_ATTRS_CASELIST : { // Ignore attributes that don't validate or can't apply to the // function type. We'll diagnose the failure to apply them in // handleFunctionTypeAttr. CallingConv CC; if (!S.CheckCallingConvAttr(AL, CC) && (!FTI.isVariadic || supportsVariadicCall(CC))) { return CC; } break; } default: break; } } bool IsCXXInstanceMethod = false; if (S.getLangOpts().CPlusPlus) { // Look inwards through parentheses to see if this chunk will form a // member pointer type or if we're the declarator. Any type attributes // between here and there will override the CC we choose here. unsigned I = ChunkIndex; bool FoundNonParen = false; while (I && !FoundNonParen) { --I; if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) FoundNonParen = true; } if (FoundNonParen) { // If we're not the declarator, we're a regular function type unless we're // in a member pointer. IsCXXInstanceMethod = D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; } else if (D.getContext() == DeclaratorContext::LambdaExprContext) { // This can only be a call operator for a lambda, which is an instance // method. IsCXXInstanceMethod = true; } else { // We're the innermost decl chunk, so must be a function declarator. assert(D.isFunctionDeclarator()); // If we're inside a record, we're declaring a method, but it could be // explicitly or implicitly static. IsCXXInstanceMethod = D.isFirstDeclarationOfMember() && D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && !D.isStaticMember(); } } CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, IsCXXInstanceMethod); // Attribute AT_OpenCLKernel affects the calling convention for SPIR // and AMDGPU targets, hence it cannot be treated as a calling // convention attribute. This is the simplest place to infer // calling convention for OpenCL kernels. if (S.getLangOpts().OpenCL) { for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { CC = CC_OpenCLKernel; break; } } } return CC; } namespace { /// A simple notion of pointer kinds, which matches up with the various /// pointer declarators. enum class SimplePointerKind { Pointer, BlockPointer, MemberPointer, Array, }; } // end anonymous namespace IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { switch (nullability) { case NullabilityKind::NonNull: if (!Ident__Nonnull) Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); return Ident__Nonnull; case NullabilityKind::Nullable: if (!Ident__Nullable) Ident__Nullable = PP.getIdentifierInfo("_Nullable"); return Ident__Nullable; case NullabilityKind::Unspecified: if (!Ident__Null_unspecified) Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); return Ident__Null_unspecified; } llvm_unreachable("Unknown nullability kind."); } /// Retrieve the identifier "NSError". IdentifierInfo *Sema::getNSErrorIdent() { if (!Ident_NSError) Ident_NSError = PP.getIdentifierInfo("NSError"); return Ident_NSError; } /// Check whether there is a nullability attribute of any kind in the given /// attribute list. static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { for (const ParsedAttr &AL : attrs) { if (AL.getKind() == ParsedAttr::AT_TypeNonNull || AL.getKind() == ParsedAttr::AT_TypeNullable || AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) return true; } return false; } namespace { /// Describes the kind of a pointer a declarator describes. enum class PointerDeclaratorKind { // Not a pointer. NonPointer, // Single-level pointer. SingleLevelPointer, // Multi-level pointer (of any pointer kind). MultiLevelPointer, // CFFooRef* MaybePointerToCFRef, // CFErrorRef* CFErrorRefPointer, // NSError** NSErrorPointerPointer, }; /// Describes a declarator chunk wrapping a pointer that marks inference as /// unexpected. // These values must be kept in sync with diagnostics. enum class PointerWrappingDeclaratorKind { /// Pointer is top-level. None = -1, /// Pointer is an array element. Array = 0, /// Pointer is the referent type of a C++ reference. Reference = 1 }; } // end anonymous namespace /// Classify the given declarator, whose type-specified is \c type, based on /// what kind of pointer it refers to. /// /// This is used to determine the default nullability. static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, PointerWrappingDeclaratorKind &wrappingKind) { unsigned numNormalPointers = 0; // For any dependent type, we consider it a non-pointer. if (type->isDependentType()) return PointerDeclaratorKind::NonPointer; // Look through the declarator chunks to identify pointers. for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { DeclaratorChunk &chunk = declarator.getTypeObject(i); switch (chunk.Kind) { case DeclaratorChunk::Array: if (numNormalPointers == 0) wrappingKind = PointerWrappingDeclaratorKind::Array; break; case DeclaratorChunk::Function: case DeclaratorChunk::Pipe: break; case DeclaratorChunk::BlockPointer: case DeclaratorChunk::MemberPointer: return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer : PointerDeclaratorKind::SingleLevelPointer; case DeclaratorChunk::Paren: break; case DeclaratorChunk::Reference: if (numNormalPointers == 0) wrappingKind = PointerWrappingDeclaratorKind::Reference; break; case DeclaratorChunk::Pointer: ++numNormalPointers; if (numNormalPointers > 2) return PointerDeclaratorKind::MultiLevelPointer; break; } } // Then, dig into the type specifier itself. unsigned numTypeSpecifierPointers = 0; do { // Decompose normal pointers. if (auto ptrType = type->getAs<PointerType>()) { ++numNormalPointers; if (numNormalPointers > 2) return PointerDeclaratorKind::MultiLevelPointer; type = ptrType->getPointeeType(); ++numTypeSpecifierPointers; continue; } // Decompose block pointers. if (type->getAs<BlockPointerType>()) { return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer : PointerDeclaratorKind::SingleLevelPointer; } // Decompose member pointers. if (type->getAs<MemberPointerType>()) { return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer : PointerDeclaratorKind::SingleLevelPointer; } // Look at Objective-C object pointers. if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { ++numNormalPointers; ++numTypeSpecifierPointers; // If this is NSError**, report that. if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { return PointerDeclaratorKind::NSErrorPointerPointer; } } break; } // Look at Objective-C class types. if (auto objcClass = type->getAs<ObjCInterfaceType>()) { if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) return PointerDeclaratorKind::NSErrorPointerPointer; } break; } // If at this point we haven't seen a pointer, we won't see one. if (numNormalPointers == 0) return PointerDeclaratorKind::NonPointer; if (auto recordType = type->getAs<RecordType>()) { RecordDecl *recordDecl = recordType->getDecl(); // If this is CFErrorRef*, report it as such. if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 && S.isCFError(recordDecl)) { return PointerDeclaratorKind::CFErrorRefPointer; } break; } break; } while (true); switch (numNormalPointers) { case 0: return PointerDeclaratorKind::NonPointer; case 1: return PointerDeclaratorKind::SingleLevelPointer; case 2: return PointerDeclaratorKind::MaybePointerToCFRef; default: return PointerDeclaratorKind::MultiLevelPointer; } } bool Sema::isCFError(RecordDecl *recordDecl) { // If we already know about CFError, test it directly. if (CFError) { return (CFError == recordDecl); } // Check whether this is CFError, which we identify based on being // bridged to NSError. CFErrorRef used to be declared with "objc_bridge" but // is now declared with "objc_bridge_mutable", so look for either one of the // two attributes. if (recordDecl->getTagKind() == TTK_Struct) { IdentifierInfo *bridgedType = nullptr; if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) bridgedType = bridgeAttr->getBridgedType(); else if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeMutableAttr>()) bridgedType = bridgeAttr->getBridgedType(); if (bridgedType == getNSErrorIdent()) { CFError = recordDecl; return true; } } return false; } static FileID getNullabilityCompletenessCheckFileID(Sema &S, SourceLocation loc) { // If we're anywhere in a function, method, or closure context, don't perform // completeness checks. for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { if (ctx->isFunctionOrMethod()) return FileID(); if (ctx->isFileContext()) break; } // We only care about the expansion location. loc = S.SourceMgr.getExpansionLoc(loc); FileID file = S.SourceMgr.getFileID(loc); if (file.isInvalid()) return FileID(); // Retrieve file information. bool invalid = false; const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); if (invalid || !sloc.isFile()) return FileID(); // We don't want to perform completeness checks on the main file or in // system headers. const SrcMgr::FileInfo &fileInfo = sloc.getFile(); if (fileInfo.getIncludeLoc().isInvalid()) return FileID(); if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && S.Diags.getSuppressSystemWarnings()) { return FileID(); } return file; } /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, /// taking into account whitespace before and after. static void fixItNullability(Sema &S, DiagnosticBuilder &Diag, SourceLocation PointerLoc, NullabilityKind Nullability) { assert(PointerLoc.isValid()); if (PointerLoc.isMacroID()) return; SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); if (!FixItLoc.isValid() || FixItLoc == PointerLoc) return; const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); if (!NextChar) return; SmallString<32> InsertionTextBuf{" "}; InsertionTextBuf += getNullabilitySpelling(Nullability); InsertionTextBuf += " "; StringRef InsertionText = InsertionTextBuf.str(); if (isWhitespace(*NextChar)) { InsertionText = InsertionText.drop_back(); } else if (NextChar[-1] == '[') { if (NextChar[0] == ']') InsertionText = InsertionText.drop_back().drop_front(); else InsertionText = InsertionText.drop_front(); } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) && !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) { InsertionText = InsertionText.drop_back().drop_front(); } Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); } static void emitNullabilityConsistencyWarning(Sema &S, SimplePointerKind PointerKind, SourceLocation PointerLoc, SourceLocation PointerEndLoc) { assert(PointerLoc.isValid()); if (PointerKind == SimplePointerKind::Array) { S.Diag(PointerLoc, diag::warn_nullability_missing_array); } else { S.Diag(PointerLoc, diag::warn_nullability_missing) << static_cast<unsigned>(PointerKind); } auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; if (FixItLoc.isMacroID()) return; auto addFixIt = [&](NullabilityKind Nullability) { auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); Diag << static_cast<unsigned>(Nullability); Diag << static_cast<unsigned>(PointerKind); fixItNullability(S, Diag, FixItLoc, Nullability); }; addFixIt(NullabilityKind::Nullable); addFixIt(NullabilityKind::NonNull); } /// Complains about missing nullability if the file containing \p pointerLoc /// has other uses of nullability (either the keywords or the \c assume_nonnull /// pragma). /// /// If the file has \e not seen other uses of nullability, this particular /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). static void checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, SourceLocation pointerLoc, SourceLocation pointerEndLoc = SourceLocation()) { // Determine which file we're performing consistency checking for. FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); if (file.isInvalid()) return; // If we haven't seen any type nullability in this file, we won't warn now // about anything. FileNullability &fileNullability = S.NullabilityMap[file]; if (!fileNullability.SawTypeNullability) { // If this is the first pointer declarator in the file, and the appropriate // warning is on, record it in case we need to diagnose it retroactively. diag::kind diagKind; if (pointerKind == SimplePointerKind::Array) diagKind = diag::warn_nullability_missing_array; else diagKind = diag::warn_nullability_missing; if (fileNullability.PointerLoc.isInvalid() && !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { fileNullability.PointerLoc = pointerLoc; fileNullability.PointerEndLoc = pointerEndLoc; fileNullability.PointerKind = static_cast<unsigned>(pointerKind); } return; } // Complain about missing nullability. emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); } /// Marks that a nullability feature has been used in the file containing /// \p loc. /// /// If this file already had pointer types in it that were missing nullability, /// the first such instance is retroactively diagnosed. /// /// \sa checkNullabilityConsistency static void recordNullabilitySeen(Sema &S, SourceLocation loc) { FileID file = getNullabilityCompletenessCheckFileID(S, loc); if (file.isInvalid()) return; FileNullability &fileNullability = S.NullabilityMap[file]; if (fileNullability.SawTypeNullability) return; fileNullability.SawTypeNullability = true; // If we haven't seen any type nullability before, now we have. Retroactively // diagnose the first unannotated pointer, if there was one. if (fileNullability.PointerLoc.isInvalid()) return; auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, fileNullability.PointerEndLoc); } /// Returns true if any of the declarator chunks before \p endIndex include a /// level of indirection: array, pointer, reference, or pointer-to-member. /// /// Because declarator chunks are stored in outer-to-inner order, testing /// every chunk before \p endIndex is testing all chunks that embed the current /// chunk as part of their type. /// /// It is legal to pass the result of Declarator::getNumTypeObjects() as the /// end index, in which case all chunks are tested. static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { unsigned i = endIndex; while (i != 0) { // Walk outwards along the declarator chunks. --i; const DeclaratorChunk &DC = D.getTypeObject(i); switch (DC.Kind) { case DeclaratorChunk::Paren: break; case DeclaratorChunk::Array: case DeclaratorChunk::Pointer: case DeclaratorChunk::Reference: case DeclaratorChunk::MemberPointer: return true; case DeclaratorChunk::Function: case DeclaratorChunk::BlockPointer: case DeclaratorChunk::Pipe: // These are invalid anyway, so just ignore. break; } } return false; } static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { return (Chunk.Kind == DeclaratorChunk::Pointer || Chunk.Kind == DeclaratorChunk::Array); } template<typename AttrT> static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) { AL.setUsedAsTypeAttr(); return ::new (Ctx) AttrT(Ctx, AL); } static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, NullabilityKind NK) { switch (NK) { case NullabilityKind::NonNull: return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); case NullabilityKind::Nullable: return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); case NullabilityKind::Unspecified: return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); } llvm_unreachable("unknown NullabilityKind"); } // Diagnose whether this is a case with the multiple addr spaces. // Returns true if this is an invalid case. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified // by qualifiers for two or more different address spaces." static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, LangAS ASNew, SourceLocation AttrLoc) { if (ASOld != LangAS::Default) { if (ASOld != ASNew) { S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); return true; } // Emit a warning if they are identical; it's likely unintended. S.Diag(AttrLoc, diag::warn_attribute_address_multiple_identical_qualifiers); } return false; } static TypeSourceInfo * GetTypeSourceInfoForDeclarator(TypeProcessingState &State, QualType T, TypeSourceInfo *ReturnTypeInfo); static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo) { // The TypeSourceInfo that this function returns will not be a null type. // If there is an error, this function will fill in a dummy type as fallback. QualType T = declSpecType; Declarator &D = state.getDeclarator(); Sema &S = state.getSema(); ASTContext &Context = S.Context; const LangOptions &LangOpts = S.getLangOpts(); // The name we're declaring, if any. DeclarationName Name; if (D.getIdentifier()) Name = D.getIdentifier(); // Does this declaration declare a typedef-name? bool IsTypedefName = D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || D.getContext() == DeclaratorContext::AliasDeclContext || D.getContext() == DeclaratorContext::AliasTemplateContext; // Does T refer to a function type with a cv-qualifier or a ref-qualifier? bool IsQualifiedFunction = T->isFunctionProtoType() && (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); // If T is 'decltype(auto)', the only declarators we can have are parens // and at most one function declarator if this is a function declaration. // If T is a deduced class template specialization type, we can have no // declarator chunks at all. if (auto *DT = T->getAs<DeducedType>()) { const AutoType *AT = T->getAs<AutoType>(); bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { unsigned Index = E - I - 1; DeclaratorChunk &DeclChunk = D.getTypeObject(Index); unsigned DiagId = IsClassTemplateDeduction ? diag::err_deduced_class_template_compound_type : diag::err_decltype_auto_compound_type; unsigned DiagKind = 0; switch (DeclChunk.Kind) { case DeclaratorChunk::Paren: // FIXME: Rejecting this is a little silly. if (IsClassTemplateDeduction) { DiagKind = 4; break; } continue; case DeclaratorChunk::Function: { if (IsClassTemplateDeduction) { DiagKind = 3; break; } unsigned FnIndex; if (D.isFunctionDeclarationContext() && D.isFunctionDeclarator(FnIndex) && FnIndex == Index) continue; DiagId = diag::err_decltype_auto_function_declarator_not_declaration; break; } case DeclaratorChunk::Pointer: case DeclaratorChunk::BlockPointer: case DeclaratorChunk::MemberPointer: DiagKind = 0; break; case DeclaratorChunk::Reference: DiagKind = 1; break; case DeclaratorChunk::Array: DiagKind = 2; break; case DeclaratorChunk::Pipe: break; } S.Diag(DeclChunk.Loc, DiagId) << DiagKind; D.setInvalidType(true); break; } } } // Determine whether we should infer _Nonnull on pointer types. Optional<NullabilityKind> inferNullability; bool inferNullabilityCS = false; bool inferNullabilityInnerOnly = false; bool inferNullabilityInnerOnlyComplete = false; // Are we in an assume-nonnull region? bool inAssumeNonNullRegion = false; SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); if (assumeNonNullLoc.isValid()) { inAssumeNonNullRegion = true; recordNullabilitySeen(S, assumeNonNullLoc); } // Whether to complain about missing nullability specifiers or not. enum { /// Never complain. CAMN_No, /// Complain on the inner pointers (but not the outermost /// pointer). CAMN_InnerPointers, /// Complain about any pointers that don't have nullability /// specified or inferred. CAMN_Yes } complainAboutMissingNullability = CAMN_No; unsigned NumPointersRemaining = 0; auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; if (IsTypedefName) { // For typedefs, we do not infer any nullability (the default), // and we only complain about missing nullability specifiers on // inner pointers. complainAboutMissingNullability = CAMN_InnerPointers; if (T->canHaveNullability(/*ResultIfUnknown*/false) && !T->getNullability(S.Context)) { // Note that we allow but don't require nullability on dependent types. ++NumPointersRemaining; } for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { DeclaratorChunk &chunk = D.getTypeObject(i); switch (chunk.Kind) { case DeclaratorChunk::Array: case DeclaratorChunk::Function: case DeclaratorChunk::Pipe: break; case DeclaratorChunk::BlockPointer: case DeclaratorChunk::MemberPointer: ++NumPointersRemaining; break; case DeclaratorChunk::Paren: case DeclaratorChunk::Reference: continue; case DeclaratorChunk::Pointer: ++NumPointersRemaining; continue; } } } else { bool isFunctionOrMethod = false; switch (auto context = state.getDeclarator().getContext()) { case DeclaratorContext::ObjCParameterContext: case DeclaratorContext::ObjCResultContext: case DeclaratorContext::PrototypeContext: case DeclaratorContext::TrailingReturnContext: case DeclaratorContext::TrailingReturnVarContext: isFunctionOrMethod = true; LLVM_FALLTHROUGH; case DeclaratorContext::MemberContext: if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { complainAboutMissingNullability = CAMN_No; break; } // Weak properties are inferred to be nullable. if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { inferNullability = NullabilityKind::Nullable; break; } LLVM_FALLTHROUGH; case DeclaratorContext::FileContext: case DeclaratorContext::KNRTypeListContext: { complainAboutMissingNullability = CAMN_Yes; // Nullability inference depends on the type and declarator. auto wrappingKind = PointerWrappingDeclaratorKind::None; switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { case PointerDeclaratorKind::NonPointer: case PointerDeclaratorKind::MultiLevelPointer: // Cannot infer nullability. break; case PointerDeclaratorKind::SingleLevelPointer: // Infer _Nonnull if we are in an assumes-nonnull region. if (inAssumeNonNullRegion) { complainAboutInferringWithinChunk = wrappingKind; inferNullability = NullabilityKind::NonNull; inferNullabilityCS = (context == DeclaratorContext::ObjCParameterContext || context == DeclaratorContext::ObjCResultContext); } break; case PointerDeclaratorKind::CFErrorRefPointer: case PointerDeclaratorKind::NSErrorPointerPointer: // Within a function or method signature, infer _Nullable at both // levels. if (isFunctionOrMethod && inAssumeNonNullRegion) inferNullability = NullabilityKind::Nullable; break; case PointerDeclaratorKind::MaybePointerToCFRef: if (isFunctionOrMethod) { // On pointer-to-pointer parameters marked cf_returns_retained or // cf_returns_not_retained, if the outer pointer is explicit then // infer the inner pointer as _Nullable. auto hasCFReturnsAttr = [](const ParsedAttributesView &AttrList) -> bool { return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); }; if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { if (hasCFReturnsAttr(D.getAttributes()) || hasCFReturnsAttr(InnermostChunk->getAttrs()) || hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { inferNullability = NullabilityKind::Nullable; inferNullabilityInnerOnly = true; } } } break; } break; } case DeclaratorContext::ConversionIdContext: complainAboutMissingNullability = CAMN_Yes; break; case DeclaratorContext::AliasDeclContext: case DeclaratorContext::AliasTemplateContext: case DeclaratorContext::BlockContext: case DeclaratorContext::BlockLiteralContext: case DeclaratorContext::ConditionContext: case DeclaratorContext::CXXCatchContext: case DeclaratorContext::CXXNewContext: case DeclaratorContext::ForContext: case DeclaratorContext::InitStmtContext: case DeclaratorContext::LambdaExprContext: case DeclaratorContext::LambdaExprParameterContext: case DeclaratorContext::ObjCCatchContext: case DeclaratorContext::TemplateParamContext: case DeclaratorContext::TemplateArgContext: case DeclaratorContext::TemplateTypeArgContext: case DeclaratorContext::TypeNameContext: case DeclaratorContext::FunctionalCastContext: // Don't infer in these contexts. break; } } // Local function that returns true if its argument looks like a va_list. auto isVaList = [&S](QualType T) -> bool { auto *typedefTy = T->getAs<TypedefType>(); if (!typedefTy) return false; TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); do { if (typedefTy->getDecl() == vaListTypedef) return true; if (auto *name = typedefTy->getDecl()->getIdentifier()) if (name->isStr("va_list")) return true; typedefTy = typedefTy->desugar()->getAs<TypedefType>(); } while (typedefTy); return false; }; // Local function that checks the nullability for a given pointer declarator. // Returns true if _Nonnull was inferred. auto inferPointerNullability = [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, SourceLocation pointerEndLoc, ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { // We've seen a pointer. if (NumPointersRemaining > 0) --NumPointersRemaining; // If a nullability attribute is present, there's nothing to do. if (hasNullabilityAttr(attrs)) return nullptr; // If we're supposed to infer nullability, do so now. if (inferNullability && !inferNullabilityInnerOnlyComplete) { ParsedAttr::Syntax syntax = inferNullabilityCS ? ParsedAttr::AS_ContextSensitiveKeyword : ParsedAttr::AS_Keyword; ParsedAttr *nullabilityAttr = Pool.create( S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), nullptr, SourceLocation(), nullptr, 0, syntax); attrs.addAtEnd(nullabilityAttr); if (inferNullabilityCS) { state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); } if (pointerLoc.isValid() && complainAboutInferringWithinChunk != PointerWrappingDeclaratorKind::None) { auto Diag = S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); Diag << static_cast<int>(complainAboutInferringWithinChunk); fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); } if (inferNullabilityInnerOnly) inferNullabilityInnerOnlyComplete = true; return nullabilityAttr; } // If we're supposed to complain about missing nullability, do so // now if it's truly missing. switch (complainAboutMissingNullability) { case CAMN_No: break; case CAMN_InnerPointers: if (NumPointersRemaining == 0) break; LLVM_FALLTHROUGH; case CAMN_Yes: checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); } return nullptr; }; // If the type itself could have nullability but does not, infer pointer // nullability and perform consistency checking. if (S.CodeSynthesisContexts.empty()) { if (T->canHaveNullability(/*ResultIfUnknown*/false) && !T->getNullability(S.Context)) { if (isVaList(T)) { // Record that we've seen a pointer, but do nothing else. if (NumPointersRemaining > 0) --NumPointersRemaining; } else { SimplePointerKind pointerKind = SimplePointerKind::Pointer; if (T->isBlockPointerType()) pointerKind = SimplePointerKind::BlockPointer; else if (T->isMemberPointerType()) pointerKind = SimplePointerKind::MemberPointer; if (auto *attr = inferPointerNullability( pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), D.getDeclSpec().getEndLoc(), D.getMutableDeclSpec().getAttributes(), D.getMutableDeclSpec().getAttributePool())) { T = state.getAttributedType( createNullabilityAttr(Context, *attr, *inferNullability), T, T); } } } if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && D.isPrototypeContext() && !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { checkNullabilityConsistency(S, SimplePointerKind::Array, D.getDeclSpec().getTypeSpecTypeLoc()); } } bool ExpectNoDerefChunk = state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); // Walk the DeclTypeInfo, building the recursive type as we go. // DeclTypeInfos are ordered from the identifier out, which is // opposite of what we want :). for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { unsigned chunkIndex = e - i - 1; state.setCurrentChunkIndex(chunkIndex); DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; switch (DeclType.Kind) { case DeclaratorChunk::Paren: if (i == 0) warnAboutRedundantParens(S, D, T); T = S.BuildParenType(T); break; case DeclaratorChunk::BlockPointer: // If blocks are disabled, emit an error. if (!LangOpts.Blocks) S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; // Handle pointer nullability. inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, DeclType.EndLoc, DeclType.getAttrs(), state.getDeclarator().getAttributePool()); T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly // qualified with const. if (LangOpts.OpenCL) DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); } break; case DeclaratorChunk::Pointer: // Verify that we're not building a pointer to pointer to function with // exception specification. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); D.setInvalidType(true); // Build the type anyway. } // Handle pointer nullability inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, DeclType.EndLoc, DeclType.getAttrs(), state.getDeclarator().getAttributePool()); if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { T = Context.getObjCObjectPointerType(T); if (DeclType.Ptr.TypeQuals) T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); break; } // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. if (LangOpts.OpenCL) { if (T->isImageType() || T->isSamplerT() || T->isPipeType() || T->isBlockPointerType()) { S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; D.setInvalidType(true); } } T = S.BuildPointerType(T, DeclType.Loc, Name); if (DeclType.Ptr.TypeQuals) T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); break; case DeclaratorChunk::Reference: { // Verify that we're not building a reference to pointer to function with // exception specification. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); D.setInvalidType(true); // Build the type anyway. } T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); if (DeclType.Ref.HasRestrict) T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); break; } case DeclaratorChunk::Array: { // Verify that we're not building an array of pointers to function with // exception specification. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); D.setInvalidType(true); // Build the type anyway. } DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); ArrayType::ArraySizeModifier ASM; if (ATI.isStar) ASM = ArrayType::Star; else if (ATI.hasStatic) ASM = ArrayType::Static; else ASM = ArrayType::Normal; if (ASM == ArrayType::Star && !D.isPrototypeContext()) { // FIXME: This check isn't quite right: it allows star in prototypes // for function definitions, and disallows some edge cases detailed // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); ASM = ArrayType::Normal; D.setInvalidType(true); } // C99 6.7.5.2p1: The optional type qualifiers and the keyword static // shall appear only in a declaration of a function parameter with an // array type, ... if (ASM == ArrayType::Static || ATI.TypeQuals) { if (!(D.isPrototypeContext() || D.getContext() == DeclaratorContext::KNRTypeListContext)) { S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << (ASM == ArrayType::Static ? "'static'" : "type qualifier"); // Remove the 'static' and the type qualifiers. if (ASM == ArrayType::Static) ASM = ArrayType::Normal; ATI.TypeQuals = 0; D.setInvalidType(true); } // C99 6.7.5.2p1: ... and then only in the outermost array type // derivation. if (hasOuterPointerLikeChunk(D, chunkIndex)) { S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << (ASM == ArrayType::Static ? "'static'" : "type qualifier"); if (ASM == ArrayType::Static) ASM = ArrayType::Normal; ATI.TypeQuals = 0; D.setInvalidType(true); } } const AutoType *AT = T->getContainedAutoType(); // Allow arrays of auto if we are a generic lambda parameter. // i.e. [](auto (&array)[5]) { return array[0]; }; OK if (AT && D.getContext() != DeclaratorContext::LambdaExprParameterContext) { // We've already diagnosed this for decltype(auto). if (!AT->isDecltypeAuto()) S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) << getPrintableNameForEntity(Name) << T; T = QualType(); break; } // Array parameters can be marked nullable as well, although it's not // necessary if they're marked 'static'. if (complainAboutMissingNullability == CAMN_Yes && !hasNullabilityAttr(DeclType.getAttrs()) && ASM != ArrayType::Static && D.isPrototypeContext() && !hasOuterPointerLikeChunk(D, chunkIndex)) { checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); } T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, SourceRange(DeclType.Loc, DeclType.EndLoc), Name); break; } case DeclaratorChunk::Function: { // If the function declarator has a prototype (i.e. it is not () and // does not have a K&R-style identifier list), then the arguments are part // of the type, otherwise the argument list is (). DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; IsQualifiedFunction = FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); // Check for auto functions and trailing return type and adjust the // return type accordingly. if (!D.isInvalidType()) { // trailing-return-type is only required if we're declaring a function, // and not, for instance, a pointer to a function. if (D.getDeclSpec().hasAutoTypeSpec() && !FTI.hasTrailingReturnType() && chunkIndex == 0) { if (!S.getLangOpts().CPlusPlus14) { S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto ? diag::err_auto_missing_trailing_return : diag::err_deduced_return_type); T = Context.IntTy; D.setInvalidType(true); } else { S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::warn_cxx11_compat_deduced_return_type); } } else if (FTI.hasTrailingReturnType()) { // T must be exactly 'auto' at this point. See CWG issue 681. if (isa<ParenType>(T)) { S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) << T << D.getSourceRange(); D.setInvalidType(true); } else if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) { if (T != Context.DependentTy) { S.Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_with_complex_decl) << D.getSourceRange(); D.setInvalidType(true); } } else if (D.getContext() != DeclaratorContext::LambdaExprContext && (T.hasQualifiers() || !isa<AutoType>(T) || cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) { S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_trailing_return_without_auto) << T << D.getDeclSpec().getSourceRange(); D.setInvalidType(true); } T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); if (T.isNull()) { // An error occurred parsing the trailing return type. T = Context.IntTy; D.setInvalidType(true); } } else { // This function type is not the type of the entity being declared, // so checking the 'auto' is not the responsibility of this chunk. } } // C99 6.7.5.3p1: The return type may not be a function or array type. // For conversion functions, we'll diagnose this particular error later. if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && (D.getName().getKind() != UnqualifiedIdKind::IK_ConversionFunctionId)) { unsigned diagID = diag::err_func_returning_array_function; // Last processing chunk in block context means this function chunk // represents the block. if (chunkIndex == 0 && D.getContext() == DeclaratorContext::BlockLiteralContext) diagID = diag::err_block_returning_array_function; S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; T = Context.IntTy; D.setInvalidType(true); } // Do not allow returning half FP value. // FIXME: This really should be in BuildFunctionType. if (T->isHalfType()) { if (S.getLangOpts().OpenCL) { if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) << T << 0 /*pointer hint*/; D.setInvalidType(true); } } else if (!S.getLangOpts().HalfArgsAndReturns) { S.Diag(D.getIdentifierLoc(), diag::err_parameters_retval_cannot_have_fp16_type) << 1; D.setInvalidType(true); } } // __ptrauth is illegal on a function return type. if (T.getPointerAuth()) { S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_return) << T; } if (LangOpts.OpenCL) { // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a // function. if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || T->isPipeType()) { S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) << T << 1 /*hint off*/; D.setInvalidType(true); } // OpenCL doesn't support variadic functions and blocks // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. // We also allow here any toolchain reserved identifiers. if (FTI.isVariadic && !(D.getIdentifier() && ((D.getIdentifier()->getName() == "printf" && (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) || D.getIdentifier()->getName().startswith("__")))) { S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); D.setInvalidType(true); } } // Methods cannot return interface types. All ObjC objects are // passed by reference. if (T->isObjCObjectType()) { SourceLocation DiagLoc, FixitLoc; if (TInfo) { DiagLoc = TInfo->getTypeLoc().getBeginLoc(); FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); } else { DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); } S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T << FixItHint::CreateInsertion(FixitLoc, "*"); T = Context.getObjCObjectPointerType(T); if (TInfo) { TypeLocBuilder TLB; TLB.pushFullCopy(TInfo->getTypeLoc()); ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); TLoc.setStarLoc(FixitLoc); TInfo = TLB.getTypeSourceInfo(Context, T); } D.setInvalidType(true); } // cv-qualifiers on return types are pointless except when the type is a // class type in C++. if ((T.getCVRQualifiers() || T->isAtomicType()) && !(S.getLangOpts().CPlusPlus && (T->isDependentType() || T->isRecordType()))) { if (T->isVoidType() && !S.getLangOpts().CPlusPlus && D.getFunctionDefinitionKind() == FDK_Definition) { // [6.9.1/3] qualified void return is invalid on a C // function definition. Apparently ok on declarations and // in C++ though (!) S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; } else diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); // C++2a [dcl.fct]p12: // A volatile-qualified return type is deprecated if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus2a) S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; } // Objective-C ARC ownership qualifiers are ignored on the function // return type (by type canonicalization). Complain if this attribute // was written here. if (T.getQualifiers().hasObjCLifetime()) { SourceLocation AttrLoc; if (chunkIndex + 1 < D.getNumTypeObjects()) { DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { AttrLoc = AL.getLoc(); break; } } } if (AttrLoc.isInvalid()) { for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { AttrLoc = AL.getLoc(); break; } } } if (AttrLoc.isValid()) { // The ownership attributes are almost always written via // the predefined // __strong/__weak/__autoreleasing/__unsafe_unretained. if (AttrLoc.isMacroID()) AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) << T.getQualifiers().getObjCLifetime(); } } if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { // C++ [dcl.fct]p6: // Types shall not be defined in return or parameter types. TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) << Context.getTypeDeclType(Tag); } // Exception specs are not allowed in typedefs. Complain, but add it // anyway. if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) S.Diag(FTI.getExceptionSpecLocBeg(), diag::err_exception_spec_in_typedef) << (D.getContext() == DeclaratorContext::AliasDeclContext || D.getContext() == DeclaratorContext::AliasTemplateContext); // If we see "T var();" or "T var(T());" at block scope, it is probably // an attempt to initialize a variable, not a function declaration. if (FTI.isAmbiguous) warnAboutAmbiguousFunction(S, D, DeclType, T); FunctionType::ExtInfo EI( getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus && !LangOpts.OpenCL) { // Simple void foo(), where the incoming T is the result type. T = Context.getFunctionNoProtoType(T, EI); } else { // We allow a zero-parameter variadic function in C if the // function is marked with the "overloadable" attribute. Scan // for this attribute now. if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable)) S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); if (FTI.NumParams && FTI.Params[0].Param == nullptr) { // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function // definition. S.Diag(FTI.Params[0].IdentLoc, diag::err_ident_list_in_fn_declaration); D.setInvalidType(true); // Recover by creating a K&R-style function type. T = Context.getFunctionNoProtoType(T, EI); break; } FunctionProtoType::ExtProtoInfo EPI; EPI.ExtInfo = EI; EPI.Variadic = FTI.isVariadic; EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); EPI.TypeQuals.addCVRUQualifiers( FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() : 0); EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None : FTI.RefQualifierIsLValueRef? RQ_LValue : RQ_RValue; // Otherwise, we have a function with a parameter list that is // potentially variadic. SmallVector<QualType, 16> ParamTys; ParamTys.reserve(FTI.NumParams); SmallVector<FunctionProtoType::ExtParameterInfo, 16> ExtParameterInfos(FTI.NumParams); bool HasAnyInterestingExtParameterInfos = false; for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); QualType ParamTy = Param->getType(); assert(!ParamTy.isNull() && "Couldn't parse type?"); // Look for 'void'. void is allowed only as a single parameter to a // function with no other parameters (C99 6.7.5.3p10). We record // int(void) as a FunctionProtoType with an empty parameter list. if (ParamTy->isVoidType()) { // If this is something like 'float(int, void)', reject it. 'void' // is an incomplete type (C99 6.2.5p19) and function decls cannot // have parameters of incomplete type. if (FTI.NumParams != 1 || FTI.isVariadic) { S.Diag(DeclType.Loc, diag::err_void_only_param); ParamTy = Context.IntTy; Param->setType(ParamTy); } else if (FTI.Params[i].Ident) { // Reject, but continue to parse 'int(void abc)'. S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); ParamTy = Context.IntTy; Param->setType(ParamTy); } else { // Reject, but continue to parse 'float(const void)'. if (ParamTy.hasQualifiers()) S.Diag(DeclType.Loc, diag::err_void_param_qualified); // Do not add 'void' to the list. break; } } else if (ParamTy->isHalfType()) { // Disallow half FP parameters. // FIXME: This really should be in BuildFunctionType. if (S.getLangOpts().OpenCL) { if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { S.Diag(Param->getLocation(), diag::err_opencl_half_param) << ParamTy; D.setInvalidType(); Param->setInvalidDecl(); } } else if (!S.getLangOpts().HalfArgsAndReturns) { S.Diag(Param->getLocation(), diag::err_parameters_retval_cannot_have_fp16_type) << 0; D.setInvalidType(); } } else if (!FTI.hasPrototype) { if (ParamTy->isPromotableIntegerType()) { ParamTy = Context.getPromotedIntegerType(ParamTy); Param->setKNRPromoted(true); } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { if (BTy->getKind() == BuiltinType::Float) { ParamTy = Context.DoubleTy; Param->setKNRPromoted(true); } } } if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); HasAnyInterestingExtParameterInfos = true; } if (auto attr = Param->getAttr<ParameterABIAttr>()) { ExtParameterInfos[i] = ExtParameterInfos[i].withABI(attr->getABI()); HasAnyInterestingExtParameterInfos = true; } if (Param->hasAttr<PassObjectSizeAttr>()) { ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); HasAnyInterestingExtParameterInfos = true; } if (Param->hasAttr<NoEscapeAttr>()) { ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); HasAnyInterestingExtParameterInfos = true; } ParamTys.push_back(ParamTy); } if (HasAnyInterestingExtParameterInfos) { EPI.ExtParameterInfos = ExtParameterInfos.data(); checkExtParameterInfos(S, ParamTys, EPI, [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); } SmallVector<QualType, 4> Exceptions; SmallVector<ParsedType, 2> DynamicExceptions; SmallVector<SourceRange, 2> DynamicExceptionRanges; Expr *NoexceptExpr = nullptr; if (FTI.getExceptionSpecType() == EST_Dynamic) { // FIXME: It's rather inefficient to have to split into two vectors // here. unsigned N = FTI.getNumExceptions(); DynamicExceptions.reserve(N); DynamicExceptionRanges.reserve(N); for (unsigned I = 0; I != N; ++I) { DynamicExceptions.push_back(FTI.Exceptions[I].Ty); DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); } } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { NoexceptExpr = FTI.NoexceptExpr; } S.checkExceptionSpecification(D.isFunctionDeclarationContext(), FTI.getExceptionSpecType(), DynamicExceptions, DynamicExceptionRanges, NoexceptExpr, Exceptions, EPI.ExceptionSpec); // FIXME: Set address space from attrs for C++ mode here. // OpenCLCPlusPlus: A class member function has an address space. auto IsClassMember = [&]() { return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && state.getDeclarator() .getCXXScopeSpec() .getScopeRep() ->getKind() == NestedNameSpecifier::TypeSpec) || state.getDeclarator().getContext() == DeclaratorContext::MemberContext; }; if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { LangAS ASIdx = LangAS::Default; // Take address space attr if any and mark as invalid to avoid adding // them later while creating QualType. if (FTI.MethodQualifiers) for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { LangAS ASIdxNew = attr.asOpenCLLangAS(); if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, attr.getLoc())) D.setInvalidType(true); else ASIdx = ASIdxNew; } // If a class member function's address space is not set, set it to // __generic. LangAS AS = (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx); EPI.TypeQuals.addAddressSpace(AS); } T = Context.getFunctionType(T, ParamTys, EPI); } break; } case DeclaratorChunk::MemberPointer: { // The scope spec must refer to a class, or be dependent. CXXScopeSpec &SS = DeclType.Mem.Scope(); QualType ClsType; // Handle pointer nullability. inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, DeclType.EndLoc, DeclType.getAttrs(), state.getDeclarator().getAttributePool()); if (SS.isInvalid()) { // Avoid emitting extra errors if we already errored on the scope. D.setInvalidType(true); } else if (S.isDependentScopeSpecifier(SS) || dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { NestedNameSpecifier *NNS = SS.getScopeRep(); NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); switch (NNS->getKind()) { case NestedNameSpecifier::Identifier: ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, NNS->getAsIdentifier()); break; case NestedNameSpecifier::Namespace: case NestedNameSpecifier::NamespaceAlias: case NestedNameSpecifier::Global: case NestedNameSpecifier::Super: llvm_unreachable("Nested-name-specifier must name a type"); case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: ClsType = QualType(NNS->getAsType(), 0); // Note: if the NNS has a prefix and ClsType is a nondependent // TemplateSpecializationType, then the NNS prefix is NOT included // in ClsType; hence we wrap ClsType into an ElaboratedType. // NOTE: in particular, no wrap occurs if ClsType already is an // Elaborated, DependentName, or DependentTemplateSpecialization. if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); break; } } else { S.Diag(DeclType.Mem.Scope().getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass) << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") << DeclType.Mem.Scope().getRange(); D.setInvalidType(true); } if (!ClsType.isNull()) T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); if (T.isNull()) { T = Context.IntTy; D.setInvalidType(true); } else if (DeclType.Mem.TypeQuals) { T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); } break; } case DeclaratorChunk::Pipe: { T = S.BuildReadPipeType(T, DeclType.Loc); processTypeAttrs(state, T, TAL_DeclSpec, D.getMutableDeclSpec().getAttributes()); break; } } if (T.isNull()) { D.setInvalidType(true); T = Context.IntTy; } // See if there are any attributes on this declarator chunk. processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); if (DeclType.Kind != DeclaratorChunk::Paren) { if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); ExpectNoDerefChunk = state.didParseNoDeref(); } } if (ExpectNoDerefChunk) S.Diag(state.getDeclarator().getBeginLoc(), diag::warn_noderef_on_non_pointer_or_array); // GNU warning -Wstrict-prototypes // Warn if a function declaration is without a prototype. // This warning is issued for all kinds of unprototyped function // declarations (i.e. function type typedef, function pointer etc.) // C99 6.7.5.3p14: // The empty list in a function declarator that is not part of a definition // of that function specifies that no information about the number or types // of the parameters is supplied. if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) { bool IsBlock = false; for (const DeclaratorChunk &DeclType : D.type_objects()) { switch (DeclType.Kind) { case DeclaratorChunk::BlockPointer: IsBlock = true; break; case DeclaratorChunk::Function: { const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; // We supress the warning when there's no LParen location, as this // indicates the declaration was an implicit declaration, which gets // warned about separately via -Wimplicit-function-declaration. if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid()) S.Diag(DeclType.Loc, diag::warn_strict_prototypes) << IsBlock << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); IsBlock = false; break; } default: break; } } } assert(!T.isNull() && "T must not be null after this point"); if (LangOpts.CPlusPlus && T->isFunctionType()) { const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); // C++ 8.3.5p4: // A cv-qualifier-seq shall only be part of the function type // for a nonstatic member function, the function type to which a pointer // to member refers, or the top-level function type of a function typedef // declaration. // // Core issue 547 also allows cv-qualifiers on function types that are // top-level template type arguments. enum { NonMember, Member, DeductionGuide } Kind = NonMember; if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) Kind = DeductionGuide; else if (!D.getCXXScopeSpec().isSet()) { if ((D.getContext() == DeclaratorContext::MemberContext || D.getContext() == DeclaratorContext::LambdaExprContext) && !D.getDeclSpec().isFriendSpecified()) Kind = Member; } else { DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); if (!DC || DC->isRecord()) Kind = Member; } // C++11 [dcl.fct]p6 (w/DR1417): // An attempt to specify a function type with a cv-qualifier-seq or a // ref-qualifier (including by typedef-name) is ill-formed unless it is: // - the function type for a non-static member function, // - the function type to which a pointer to member refers, // - the top-level function type of a function typedef declaration or // alias-declaration, // - the type-id in the default argument of a type-parameter, or // - the type-id of a template-argument for a type-parameter // // FIXME: Checking this here is insufficient. We accept-invalid on: // // template<typename T> struct S { void f(T); }; // S<int() const> s; // // ... for instance. if (IsQualifiedFunction && !(Kind == Member && D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArgContext && D.getContext() != DeclaratorContext::TemplateTypeArgContext) { SourceLocation Loc = D.getBeginLoc(); SourceRange RemovalRange; unsigned I; if (D.isFunctionDeclarator(I)) { SmallVector<SourceLocation, 4> RemovalLocs; const DeclaratorChunk &Chunk = D.getTypeObject(I); assert(Chunk.Kind == DeclaratorChunk::Function); if (Chunk.Fun.hasRefQualifier()) RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); if (Chunk.Fun.hasMethodTypeQualifiers()) Chunk.Fun.MethodQualifiers->forEachQualifier( [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { RemovalLocs.push_back(SL); }); if (!RemovalLocs.empty()) { llvm::sort(RemovalLocs, BeforeThanCompare<SourceLocation>(S.getSourceManager())); RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); Loc = RemovalLocs.front(); } } S.Diag(Loc, diag::err_invalid_qualified_function_type) << Kind << D.isFunctionDeclarator() << T << getFunctionQualifiersAsString(FnTy) << FixItHint::CreateRemoval(RemovalRange); // Strip the cv-qualifiers and ref-qualifiers from the type. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); EPI.TypeQuals.removeCVRQualifiers(); EPI.RefQualifier = RQ_None; T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), EPI); // Rebuild any parens around the identifier in the function type. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) break; T = S.BuildParenType(T); } } } // Apply any undistributed attributes from the declarator. processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); // Diagnose any ignored type attributes. state.diagnoseIgnoredTypeAttrs(T); // C++0x [dcl.constexpr]p9: // A constexpr specifier used in an object declaration declares the object // as const. if (D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr && T->isObjectType()) T.addConst(); // C++2a [dcl.fct]p4: // A parameter with volatile-qualified type is deprecated if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus2a && (D.getContext() == DeclaratorContext::PrototypeContext || D.getContext() == DeclaratorContext::LambdaExprParameterContext)) S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; // If there was an ellipsis in the declarator, the declaration declares a // parameter pack whose type may be a pack expansion type. if (D.hasEllipsis()) { // C++0x [dcl.fct]p13: // A declarator-id or abstract-declarator containing an ellipsis shall // only be used in a parameter-declaration. Such a parameter-declaration // is a parameter pack (14.5.3). [...] switch (D.getContext()) { case DeclaratorContext::PrototypeContext: case DeclaratorContext::LambdaExprParameterContext: // C++0x [dcl.fct]p13: // [...] When it is part of a parameter-declaration-clause, the // parameter pack is a function parameter pack (14.5.3). The type T // of the declarator-id of the function parameter pack shall contain // a template parameter pack; each template parameter pack in T is // expanded by the function parameter pack. // // We represent function parameter packs as function parameters whose // type is a pack expansion. if (!T->containsUnexpandedParameterPack()) { S.Diag(D.getEllipsisLoc(), diag::err_function_parameter_pack_without_parameter_packs) << T << D.getSourceRange(); D.setEllipsisLoc(SourceLocation()); } else { T = Context.getPackExpansionType(T, None); } break; case DeclaratorContext::TemplateParamContext: // C++0x [temp.param]p15: // If a template-parameter is a [...] is a parameter-declaration that // declares a parameter pack (8.3.5), then the template-parameter is a // template parameter pack (14.5.3). // // Note: core issue 778 clarifies that, if there are any unexpanded // parameter packs in the type of the non-type template parameter, then // it expands those parameter packs. if (T->containsUnexpandedParameterPack()) T = Context.getPackExpansionType(T, None); else S.Diag(D.getEllipsisLoc(), LangOpts.CPlusPlus11 ? diag::warn_cxx98_compat_variadic_templates : diag::ext_variadic_templates); break; case DeclaratorContext::FileContext: case DeclaratorContext::KNRTypeListContext: case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic // here? case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic // here? case DeclaratorContext::TypeNameContext: case DeclaratorContext::FunctionalCastContext: case DeclaratorContext::CXXNewContext: case DeclaratorContext::AliasDeclContext: case DeclaratorContext::AliasTemplateContext: case DeclaratorContext::MemberContext: case DeclaratorContext::BlockContext: case DeclaratorContext::ForContext: case DeclaratorContext::InitStmtContext: case DeclaratorContext::ConditionContext: case DeclaratorContext::CXXCatchContext: case DeclaratorContext::ObjCCatchContext: case DeclaratorContext::BlockLiteralContext: case DeclaratorContext::LambdaExprContext: case DeclaratorContext::ConversionIdContext: case DeclaratorContext::TrailingReturnContext: case DeclaratorContext::TrailingReturnVarContext: case DeclaratorContext::TemplateArgContext: case DeclaratorContext::TemplateTypeArgContext: // FIXME: We may want to allow parameter packs in block-literal contexts // in the future. S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); D.setEllipsisLoc(SourceLocation()); break; } } assert(!T.isNull() && "T must not be null at the end of this function"); if (D.isInvalidType()) return Context.getTrivialTypeSourceInfo(T); return GetTypeSourceInfoForDeclarator(state, T, TInfo); } /// GetTypeForDeclarator - Convert the type for the specified /// declarator to Type instances. /// /// The result of this call will never be null, but the associated /// type may be a null type if there's an unrecoverable error. TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { // Determine the type of the declarator. Not all forms of declarator // have a type. TypeProcessingState state(*this, D); TypeSourceInfo *ReturnTypeInfo = nullptr; QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) inferARCWriteback(state, T); return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); } static void transferARCOwnershipToDeclSpec(Sema &S, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership) { if (declSpecTy->isObjCRetainableType() && declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { Qualifiers qs; qs.addObjCLifetime(ownership); declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); } } static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex) { Sema &S = state.getSema(); Declarator &D = state.getDeclarator(); // Look for an explicit lifetime attribute. DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) return; const char *attrStr = nullptr; switch (ownership) { case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; case Qualifiers::OCL_Strong: attrStr = "strong"; break; case Qualifiers::OCL_Weak: attrStr = "weak"; break; case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; } IdentifierLoc *Arg = new (S.Context) IdentifierLoc; Arg->Ident = &S.Context.Idents.get(attrStr); Arg->Loc = SourceLocation(); ArgsUnion Args(Arg); // If there wasn't one, add one (with an invalid source location // so that we don't make an AttributedType for it). ParsedAttr *attr = D.getAttributePool().create( &S.Context.Idents.get("objc_ownership"), SourceLocation(), /*scope*/ nullptr, SourceLocation(), /*args*/ &Args, 1, ParsedAttr::AS_GNU); chunk.getAttrs().addAtEnd(attr); // TODO: mark whether we did this inference? } /// Used for transferring ownership in casts resulting in l-values. static void transferARCOwnership(TypeProcessingState &state, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership) { Sema &S = state.getSema(); Declarator &D = state.getDeclarator(); int inner = -1; bool hasIndirection = false; for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { DeclaratorChunk &chunk = D.getTypeObject(i); switch (chunk.Kind) { case DeclaratorChunk::Paren: // Ignore parens. break; case DeclaratorChunk::Array: case DeclaratorChunk::Reference: case DeclaratorChunk::Pointer: if (inner != -1) hasIndirection = true; inner = i; break; case DeclaratorChunk::BlockPointer: if (inner != -1) transferARCOwnershipToDeclaratorChunk(state, ownership, i); return; case DeclaratorChunk::Function: case DeclaratorChunk::MemberPointer: case DeclaratorChunk::Pipe: return; } } if (inner == -1) return; DeclaratorChunk &chunk = D.getTypeObject(inner); if (chunk.Kind == DeclaratorChunk::Pointer) { if (declSpecTy->isObjCRetainableType()) return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); if (declSpecTy->isObjCObjectType() && hasIndirection) return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); } else { assert(chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference); return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); } } TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { TypeProcessingState state(*this, D); TypeSourceInfo *ReturnTypeInfo = nullptr; QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); if (getLangOpts().ObjC) { Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); if (ownership != Qualifiers::OCL_None) transferARCOwnership(state, declSpecTy, ownership); } return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); } static void fillAttributedTypeLoc(AttributedTypeLoc TL, TypeProcessingState &State) { TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); } namespace { class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { ASTContext &Context; TypeProcessingState &State; const DeclSpec &DS; public: TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State, const DeclSpec &DS) : Context(Context), State(State), DS(DS) {} void VisitAttributedTypeLoc(AttributedTypeLoc TL) { Visit(TL.getModifiedLoc()); fillAttributedTypeLoc(TL, State); } void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { Visit(TL.getInnerLoc()); TL.setExpansionLoc( State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); } void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { Visit(TL.getUnqualifiedLoc()); } void VisitTypedefTypeLoc(TypedefTypeLoc TL) { TL.setNameLoc(DS.getTypeSpecTypeLoc()); } void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { TL.setNameLoc(DS.getTypeSpecTypeLoc()); // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires // addition field. What we have is good enough for dispay of location // of 'fixit' on interface name. TL.setNameEndLoc(DS.getEndLoc()); } void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { TypeSourceInfo *RepTInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); TL.copy(RepTInfo->getTypeLoc()); } void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { TypeSourceInfo *RepTInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); TL.copy(RepTInfo->getTypeLoc()); } void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); // If we got no declarator info from previous Sema routines, // just fill with the typespec loc. if (!TInfo) { TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); return; } TypeLoc OldTL = TInfo->getTypeLoc(); if (TInfo->getType()->getAs<ElaboratedType>()) { ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() .castAs<TemplateSpecializationTypeLoc>(); TL.copy(NamedTL); } else { TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); } } void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); TL.setParensRange(DS.getTypeofParensRange()); } void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); TL.setParensRange(DS.getTypeofParensRange()); assert(DS.getRepAsType()); TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); TL.setUnderlyingTInfo(TInfo); } void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { // FIXME: This holds only because we only have one unary transform. assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); TL.setKWLoc(DS.getTypeSpecTypeLoc()); TL.setParensRange(DS.getTypeofParensRange()); assert(DS.getRepAsType()); TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); TL.setUnderlyingTInfo(TInfo); } void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { // By default, use the source location of the type specifier. TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); if (TL.needsExtraLocalData()) { // Set info for the written builtin specifiers. TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); // Try to have a meaningful source location. if (TL.getWrittenSignSpec() != TSS_unspecified) TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); if (TL.getWrittenWidthSpec() != TSW_unspecified) TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); } } void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { ElaboratedTypeKeyword Keyword = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); if (DS.getTypeSpecType() == TST_typename) { TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); if (TInfo) { TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); return; } } TL.setElaboratedKeywordLoc(Keyword != ETK_None ? DS.getTypeSpecTypeLoc() : SourceLocation()); const CXXScopeSpec& SS = DS.getTypeSpecScope(); TL.setQualifierLoc(SS.getWithLocInContext(Context)); Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); } void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { assert(DS.getTypeSpecType() == TST_typename); TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); assert(TInfo); TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); } void VisitDependentTemplateSpecializationTypeLoc( DependentTemplateSpecializationTypeLoc TL) { assert(DS.getTypeSpecType() == TST_typename); TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); assert(TInfo); TL.copy( TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); } void VisitTagTypeLoc(TagTypeLoc TL) { TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); } void VisitAtomicTypeLoc(AtomicTypeLoc TL) { // An AtomicTypeLoc can come from either an _Atomic(...) type specifier // or an _Atomic qualifier. if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { TL.setKWLoc(DS.getTypeSpecTypeLoc()); TL.setParensRange(DS.getTypeofParensRange()); TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); assert(TInfo); TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); } else { TL.setKWLoc(DS.getAtomicSpecLoc()); // No parens, to indicate this was spelled as an _Atomic qualifier. TL.setParensRange(SourceRange()); Visit(TL.getValueLoc()); } } void VisitPipeTypeLoc(PipeTypeLoc TL) { TL.setKWLoc(DS.getTypeSpecTypeLoc()); TypeSourceInfo *TInfo = nullptr; Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); } void VisitTypeLoc(TypeLoc TL) { // FIXME: add other typespec types and change this to an assert. TL.initialize(Context, DS.getTypeSpecTypeLoc()); } }; class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { ASTContext &Context; TypeProcessingState &State; const DeclaratorChunk &Chunk; public: DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, const DeclaratorChunk &Chunk) : Context(Context), State(State), Chunk(Chunk) {} void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { llvm_unreachable("qualified type locs not expected here!"); } void VisitDecayedTypeLoc(DecayedTypeLoc TL) { llvm_unreachable("decayed type locs not expected here!"); } void VisitAttributedTypeLoc(AttributedTypeLoc TL) { fillAttributedTypeLoc(TL, State); } void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { // nothing } void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::BlockPointer); TL.setCaretLoc(Chunk.Loc); } void VisitPointerTypeLoc(PointerTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Pointer); TL.setStarLoc(Chunk.Loc); } void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Pointer); TL.setStarLoc(Chunk.Loc); } void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::MemberPointer); const CXXScopeSpec& SS = Chunk.Mem.Scope(); NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); const Type* ClsTy = TL.getClass(); QualType ClsQT = QualType(ClsTy, 0); TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); // Now copy source location info into the type loc component. TypeLoc ClsTL = ClsTInfo->getTypeLoc(); switch (NNSLoc.getNestedNameSpecifier()->getKind()) { case NestedNameSpecifier::Identifier: assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); { DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); DNTLoc.setElaboratedKeywordLoc(SourceLocation()); DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); } break; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: if (isa<ElaboratedType>(ClsTy)) { ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); ETLoc.setElaboratedKeywordLoc(SourceLocation()); ETLoc.setQualifierLoc(NNSLoc.getPrefix()); TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); } else { ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); } break; case NestedNameSpecifier::Namespace: case NestedNameSpecifier::NamespaceAlias: case NestedNameSpecifier::Global: case NestedNameSpecifier::Super: llvm_unreachable("Nested-name-specifier must name a type"); } // Finally fill in MemberPointerLocInfo fields. TL.setStarLoc(Chunk.Loc); TL.setClassTInfo(ClsTInfo); } void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Reference); // 'Amp' is misleading: this might have been originally /// spelled with AmpAmp. TL.setAmpLoc(Chunk.Loc); } void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Reference); assert(!Chunk.Ref.LValueRef); TL.setAmpAmpLoc(Chunk.Loc); } void VisitArrayTypeLoc(ArrayTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Array); TL.setLBracketLoc(Chunk.Loc); TL.setRBracketLoc(Chunk.EndLoc); TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); } void VisitFunctionTypeLoc(FunctionTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Function); TL.setLocalRangeBegin(Chunk.Loc); TL.setLocalRangeEnd(Chunk.EndLoc); const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; TL.setLParenLoc(FTI.getLParenLoc()); TL.setRParenLoc(FTI.getRParenLoc()); for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); TL.setParam(tpi++, Param); } TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); } void VisitParenTypeLoc(ParenTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Paren); TL.setLParenLoc(Chunk.Loc); TL.setRParenLoc(Chunk.EndLoc); } void VisitPipeTypeLoc(PipeTypeLoc TL) { assert(Chunk.Kind == DeclaratorChunk::Pipe); TL.setKWLoc(Chunk.Loc); } void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { TL.setExpansionLoc(Chunk.Loc); } void VisitTypeLoc(TypeLoc TL) { llvm_unreachable("unsupported TypeLoc kind in declarator!"); } }; } // end anonymous namespace static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { SourceLocation Loc; switch (Chunk.Kind) { case DeclaratorChunk::Function: case DeclaratorChunk::Array: case DeclaratorChunk::Paren: case DeclaratorChunk::Pipe: llvm_unreachable("cannot be _Atomic qualified"); case DeclaratorChunk::Pointer: Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); break; case DeclaratorChunk::BlockPointer: case DeclaratorChunk::Reference: case DeclaratorChunk::MemberPointer: // FIXME: Provide a source location for the _Atomic keyword. break; } ATL.setKWLoc(Loc); ATL.setParensRange(SourceRange()); } static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, const ParsedAttributesView &Attrs) { for (const ParsedAttr &AL : Attrs) { if (AL.getKind() == ParsedAttr::AT_AddressSpace) { DASTL.setAttrNameLoc(AL.getLoc()); DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); DASTL.setAttrOperandParensRange(SourceRange()); return; } } llvm_unreachable( "no address_space attribute found at the expected location!"); } /// Create and instantiate a TypeSourceInfo with type source information. /// /// \param T QualType referring to the type as written in source code. /// /// \param ReturnTypeInfo For declarators whose return type does not show /// up in the normal place in the declaration specifiers (such as a C++ /// conversion function), this pointer will refer to a type source information /// for that return type. static TypeSourceInfo * GetTypeSourceInfoForDeclarator(TypeProcessingState &State, QualType T, TypeSourceInfo *ReturnTypeInfo) { Sema &S = State.getSema(); Declarator &D = State.getDeclarator(); TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); // Handle parameter packs whose type is a pack expansion. if (isa<PackExpansionType>(T)) { CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); } for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { // An AtomicTypeLoc might be produced by an atomic qualifier in this // declarator chunk. if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { fillAtomicQualLoc(ATL, D.getTypeObject(i)); CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); } while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { TL.setExpansionLoc( State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); } while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { fillAttributedTypeLoc(TL, State); CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); } while (DependentAddressSpaceTypeLoc TL = CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); } // FIXME: Ordering here? while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); } // If we have different source information for the return type, use // that. This really only applies to C++ conversion functions. if (ReturnTypeInfo) { TypeLoc TL = ReturnTypeInfo->getTypeLoc(); assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); } else { TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL); } return TInfo; } /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser // and Sema during declaration parsing. Try deallocating/caching them when // it's appropriate, instead of allocating them and keeping them around. LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), TypeAlignment); new (LocT) LocInfoType(T, TInfo); assert(LocT->getTypeClass() != T->getTypeClass() && "LocInfoType's TypeClass conflicts with an existing Type class"); return ParsedType::make(QualType(LocT, 0)); } void LocInfoType::getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const { llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser"); } TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { // C99 6.7.6: Type names have no identifier. This is already validated by // the parser. assert(D.getIdentifier() == nullptr && "Type name should have no identifier!"); TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); QualType T = TInfo->getType(); if (D.isInvalidType()) return true; // Make sure there are no unused decl attributes on the declarator. // We don't want to do this for ObjC parameters because we're going // to apply them to the actual parameter declaration. // Likewise, we don't want to do this for alias declarations, because // we are actually going to build a declaration from this eventually. if (D.getContext() != DeclaratorContext::ObjCParameterContext && D.getContext() != DeclaratorContext::AliasDeclContext && D.getContext() != DeclaratorContext::AliasTemplateContext) checkUnusedDeclAttributes(D); if (getLangOpts().CPlusPlus) { // Check that there are no default arguments (C++ only). CheckExtraCXXDefaultArguments(D); } return CreateParsedType(T, TInfo); } ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { QualType T = Context.getObjCInstanceType(); TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); return CreateParsedType(T, TInfo); } //===----------------------------------------------------------------------===// // Type Attribute Processing //===----------------------------------------------------------------------===// /// Build an AddressSpace index from a constant expression and diagnose any /// errors related to invalid address_spaces. Returns true on successfully /// building an AddressSpace index. static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, const Expr *AddrSpace, SourceLocation AttrLoc) { if (!AddrSpace->isValueDependent()) { llvm::APSInt addrSpace(32); if (!AddrSpace->isIntegerConstantExpr(addrSpace, S.Context)) { S.Diag(AttrLoc, diag::err_attribute_argument_type) << "'address_space'" << AANT_ArgumentIntegerConstant << AddrSpace->getSourceRange(); return false; } // Bounds checking. if (addrSpace.isSigned()) { if (addrSpace.isNegative()) { S.Diag(AttrLoc, diag::err_attribute_address_space_negative) << AddrSpace->getSourceRange(); return false; } addrSpace.setIsSigned(false); } llvm::APSInt max(addrSpace.getBitWidth()); max = Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; if (addrSpace > max) { S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); return false; } ASIdx = getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); return true; } // Default value for DependentAddressSpaceTypes ASIdx = LangAS::Default; return true; } /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression /// is uninstantiated. If instantiated it will apply the appropriate address /// space to the type. This function allows dependent template variables to be /// used in conjunction with the address_space attribute QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc) { if (!AddrSpace->isValueDependent()) { if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, AttrLoc)) return QualType(); return Context.getAddrSpaceQualType(T, ASIdx); } // A check with similar intentions as checking if a type already has an // address space except for on a dependent types, basically if the // current type is already a DependentAddressSpaceType then its already // lined up to have another address space on it and we can't have // multiple address spaces on the one pointer indirection if (T->getAs<DependentAddressSpaceType>()) { Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); return QualType(); } return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); } QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc) { LangAS ASIdx; if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) return QualType(); return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); } /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the /// specified type. The attribute contains 1 argument, the id of the address /// space for the type. static void HandleAddressSpaceTypeAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State) { Sema &S = State.getSema(); // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be // qualified by an address-space qualifier." if (Type->isFunctionType()) { S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); Attr.setInvalid(); return; } LangAS ASIdx; if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { // Check the attribute arguments. if (Attr.getNumArgs() != 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr << 1; Attr.setInvalid(); return; } Expr *ASArgExpr; if (Attr.isArgIdent(0)) { // Special case where the argument is a template id. CXXScopeSpec SS; SourceLocation TemplateKWLoc; UnqualifiedId id; id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); ExprResult AddrSpace = S.ActOnIdExpression( S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false, /*IsAddressOfOperand=*/false); if (AddrSpace.isInvalid()) return; ASArgExpr = static_cast<Expr *>(AddrSpace.get()); } else { ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); } LangAS ASIdx; if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { Attr.setInvalid(); return; } ASTContext &Ctx = S.Context; auto *ASAttr = ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); // If the expression is not value dependent (not templated), then we can // apply the address space qualifiers just to the equivalent type. // Otherwise, we make an AttributedType with the modified and equivalent // type the same, and wrap it in a DependentAddressSpaceType. When this // dependent type is resolved, the qualifier is added to the equivalent type // later. QualType T; if (!ASArgExpr->isValueDependent()) { QualType EquivType = S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); if (EquivType.isNull()) { Attr.setInvalid(); return; } T = State.getAttributedType(ASAttr, Type, EquivType); } else { T = State.getAttributedType(ASAttr, Type, Type); T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); } if (!T.isNull()) Type = T; else Attr.setInvalid(); } else { // The keyword-based type attributes imply which address space to use. ASIdx = Attr.asOpenCLLangAS(); if (ASIdx == LangAS::Default) llvm_unreachable("Invalid address space"); if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, Attr.getLoc())) { Attr.setInvalid(); return; } Type = S.Context.getAddrSpaceQualType(Type, ASIdx); } } /// handleObjCOwnershipTypeAttr - Process an objc_ownership /// attribute on the specified type. /// /// Returns 'true' if the attribute was handled. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type) { bool NonObjCPointer = false; if (!type->isDependentType() && !type->isUndeducedType()) { if (const PointerType *ptr = type->getAs<PointerType>()) { QualType pointee = ptr->getPointeeType(); if (pointee->isObjCRetainableType() || pointee->isPointerType()) return false; // It is important not to lose the source info that there was an attribute // applied to non-objc pointer. We will create an attributed type but // its type will be the same as the original type. NonObjCPointer = true; } else if (!type->isObjCRetainableType()) { return false; } // Don't accept an ownership attribute in the declspec if it would // just be the return type of a block pointer. if (state.isProcessingDeclSpec()) { Declarator &D = state.getDeclarator(); if (maybeMovePastReturnType(D, D.getNumTypeObjects(), /*onlyBlockPointers=*/true)) return false; } } Sema &S = state.getSema(); SourceLocation AttrLoc = attr.getLoc(); if (AttrLoc.isMacroID()) AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); if (!attr.isArgIdent(0)) { S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr << AANT_ArgumentString; attr.setInvalid(); return true; } IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; Qualifiers::ObjCLifetime lifetime; if (II->isStr("none")) lifetime = Qualifiers::OCL_ExplicitNone; else if (II->isStr("strong")) lifetime = Qualifiers::OCL_Strong; else if (II->isStr("weak")) lifetime = Qualifiers::OCL_Weak; else if (II->isStr("autoreleasing")) lifetime = Qualifiers::OCL_Autoreleasing; else { S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; attr.setInvalid(); return true; } // Just ignore lifetime attributes other than __weak and __unsafe_unretained // outside of ARC mode. if (!S.getLangOpts().ObjCAutoRefCount && lifetime != Qualifiers::OCL_Weak && lifetime != Qualifiers::OCL_ExplicitNone) { return true; } SplitQualType underlyingType = type.split(); // Check for redundant/conflicting ownership qualifiers. if (Qualifiers::ObjCLifetime previousLifetime = type.getQualifiers().getObjCLifetime()) { // If it's written directly, that's an error. if (S.Context.hasDirectOwnershipQualifier(type)) { S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) << type; return true; } // Otherwise, if the qualifiers actually conflict, pull sugar off // and remove the ObjCLifetime qualifiers. if (previousLifetime != lifetime) { // It's possible to have multiple local ObjCLifetime qualifiers. We // can't stop after we reach a type that is directly qualified. const Type *prevTy = nullptr; while (!prevTy || prevTy != underlyingType.Ty) { prevTy = underlyingType.Ty; underlyingType = underlyingType.getSingleStepDesugaredType(); } underlyingType.Quals.removeObjCLifetime(); } } underlyingType.Quals.addObjCLifetime(lifetime); if (NonObjCPointer) { StringRef name = attr.getAttrName()->getName(); switch (lifetime) { case Qualifiers::OCL_None: case Qualifiers::OCL_ExplicitNone: break; case Qualifiers::OCL_Strong: name = "__strong"; break; case Qualifiers::OCL_Weak: name = "__weak"; break; case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; } S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name << TDS_ObjCObjOrBlock << type; } // Don't actually add the __unsafe_unretained qualifier in non-ARC files, // because having both 'T' and '__unsafe_unretained T' exist in the type // system causes unfortunate widespread consistency problems. (For example, // they're not considered compatible types, and we mangle them identicially // as template arguments.) These problems are all individually fixable, // but it's easier to just not add the qualifier and instead sniff it out // in specific places using isObjCInertUnsafeUnretainedType(). // // Doing this does means we miss some trivial consistency checks that // would've triggered in ARC, but that's better than trying to solve all // the coexistence problems with __unsafe_unretained. if (!S.getLangOpts().ObjCAutoRefCount && lifetime == Qualifiers::OCL_ExplicitNone) { type = state.getAttributedType( createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), type, type); return true; } QualType origType = type; if (!NonObjCPointer) type = S.Context.getQualifiedType(underlyingType); // If we have a valid source location for the attribute, use an // AttributedType instead. if (AttrLoc.isValid()) { type = state.getAttributedType(::new (S.Context) ObjCOwnershipAttr(S.Context, attr, II), origType, type); } auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, unsigned diagnostic, QualType type) { if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { S.DelayedDiagnostics.add( sema::DelayedDiagnostic::makeForbiddenType( S.getSourceManager().getExpansionLoc(loc), diagnostic, type, /*ignored*/ 0)); } else { S.Diag(loc, diagnostic); } }; // Sometimes, __weak isn't allowed. if (lifetime == Qualifiers::OCL_Weak && !S.getLangOpts().ObjCWeak && !NonObjCPointer) { // Use a specialized diagnostic if the runtime just doesn't support them. unsigned diagnostic = (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled : diag::err_arc_weak_no_runtime); // In any case, delay the diagnostic until we know what we're parsing. diagnoseOrDelay(S, AttrLoc, diagnostic, type); attr.setInvalid(); return true; } // Forbid __weak for class objects marked as // objc_arc_weak_reference_unavailable if (lifetime == Qualifiers::OCL_Weak) { if (const ObjCObjectPointerType *ObjT = type->getAs<ObjCObjectPointerType>()) { if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { if (Class->isArcWeakrefUnavailable()) { S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); S.Diag(ObjT->getInterfaceDecl()->getLocation(), diag::note_class_declared); } } } } return true; } /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type /// attribute on the specified type. Returns true to indicate that /// the attribute was handled, false to indicate that the type does /// not permit the attribute. static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type) { Sema &S = state.getSema(); // Delay if this isn't some kind of pointer. if (!type->isPointerType() && !type->isObjCObjectPointerType() && !type->isBlockPointerType()) return false; if (type.getObjCGCAttr() != Qualifiers::GCNone) { S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); attr.setInvalid(); return true; } // Check the attribute arguments. if (!attr.isArgIdent(0)) { S.Diag(attr.getLoc(), diag::err_attribute_argument_type) << attr << AANT_ArgumentString; attr.setInvalid(); return true; } Qualifiers::GC GCAttr; if (attr.getNumArgs() > 1) { S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr << 1; attr.setInvalid(); return true; } IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; if (II->isStr("weak")) GCAttr = Qualifiers::Weak; else if (II->isStr("strong")) GCAttr = Qualifiers::Strong; else { S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) << attr << II; attr.setInvalid(); return true; } QualType origType = type; type = S.Context.getObjCGCQualType(origType, GCAttr); // Make an attributed type to preserve the source information. if (attr.getLoc().isValid()) type = state.getAttributedType( ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); return true; } namespace { /// A helper class to unwrap a type down to a function for the /// purposes of applying attributes there. /// /// Use: /// FunctionTypeUnwrapper unwrapped(SemaRef, T); /// if (unwrapped.isFunctionType()) { /// const FunctionType *fn = unwrapped.get(); /// // change fn somehow /// T = unwrapped.wrap(fn); /// } struct FunctionTypeUnwrapper { enum WrapKind { Desugar, Attributed, Parens, Pointer, BlockPointer, Reference, MemberPointer }; QualType Original; const FunctionType *Fn; SmallVector<unsigned char /*WrapKind*/, 8> Stack; FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { while (true) { const Type *Ty = T.getTypePtr(); if (isa<FunctionType>(Ty)) { Fn = cast<FunctionType>(Ty); return; } else if (isa<ParenType>(Ty)) { T = cast<ParenType>(Ty)->getInnerType(); Stack.push_back(Parens); } else if (isa<PointerType>(Ty)) { T = cast<PointerType>(Ty)->getPointeeType(); Stack.push_back(Pointer); } else if (isa<BlockPointerType>(Ty)) { T = cast<BlockPointerType>(Ty)->getPointeeType(); Stack.push_back(BlockPointer); } else if (isa<MemberPointerType>(Ty)) { T = cast<MemberPointerType>(Ty)->getPointeeType(); Stack.push_back(MemberPointer); } else if (isa<ReferenceType>(Ty)) { T = cast<ReferenceType>(Ty)->getPointeeType(); Stack.push_back(Reference); } else if (isa<AttributedType>(Ty)) { T = cast<AttributedType>(Ty)->getEquivalentType(); Stack.push_back(Attributed); } else { const Type *DTy = Ty->getUnqualifiedDesugaredType(); if (Ty == DTy) { Fn = nullptr; return; } T = QualType(DTy, 0); Stack.push_back(Desugar); } } } bool isFunctionType() const { return (Fn != nullptr); } const FunctionType *get() const { return Fn; } QualType wrap(Sema &S, const FunctionType *New) { // If T wasn't modified from the unwrapped type, do nothing. if (New == get()) return Original; Fn = New; return wrap(S.Context, Original, 0); } private: QualType wrap(ASTContext &C, QualType Old, unsigned I) { if (I == Stack.size()) return C.getQualifiedType(Fn, Old.getQualifiers()); // Build up the inner type, applying the qualifiers from the old // type to the new type. SplitQualType SplitOld = Old.split(); // As a special case, tail-recurse if there are no qualifiers. if (SplitOld.Quals.empty()) return wrap(C, SplitOld.Ty, I); return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); } QualType wrap(ASTContext &C, const Type *Old, unsigned I) { if (I == Stack.size()) return QualType(Fn, 0); switch (static_cast<WrapKind>(Stack[I++])) { case Desugar: // This is the point at which we potentially lose source // information. return wrap(C, Old->getUnqualifiedDesugaredType(), I); case Attributed: return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); case Parens: { QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); return C.getParenType(New); } case Pointer: { QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); return C.getPointerType(New); } case BlockPointer: { QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); return C.getBlockPointerType(New); } case MemberPointer: { const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); QualType New = wrap(C, OldMPT->getPointeeType(), I); return C.getMemberPointerType(New, OldMPT->getClass()); } case Reference: { const ReferenceType *OldRef = cast<ReferenceType>(Old); QualType New = wrap(C, OldRef->getPointeeType(), I); if (isa<LValueReferenceType>(OldRef)) return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); else return C.getRValueReferenceType(New); } } llvm_unreachable("unknown wrapping kind"); } }; } // end anonymous namespace static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, ParsedAttr &PAttr, QualType &Type) { Sema &S = State.getSema(); Attr *A; switch (PAttr.getKind()) { default: llvm_unreachable("Unknown attribute kind"); case ParsedAttr::AT_Ptr32: A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); break; case ParsedAttr::AT_Ptr64: A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); break; case ParsedAttr::AT_SPtr: A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); break; case ParsedAttr::AT_UPtr: A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); break; } attr::Kind NewAttrKind = A->getKind(); QualType Desugared = Type; const AttributedType *AT = dyn_cast<AttributedType>(Type); while (AT) { attr::Kind CurAttrKind = AT->getAttrKind(); // You cannot specify duplicate type attributes, so if the attribute has // already been applied, flag it. if (NewAttrKind == CurAttrKind) { S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; return true; } // You cannot have both __sptr and __uptr on the same type, nor can you // have __ptr32 and __ptr64. if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) || (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) { S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) << "'__ptr32'" << "'__ptr64'"; return true; } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) || (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) { S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) << "'__sptr'" << "'__uptr'"; return true; } Desugared = AT->getEquivalentType(); AT = dyn_cast<AttributedType>(Desugared); } // Pointer type qualifiers can only operate on pointer types, but not // pointer-to-member types. // // FIXME: Should we really be disallowing this attribute if there is any // type sugar between it and the pointer (other than attributes)? Eg, this // disallows the attribute on a parenthesized pointer. // And if so, should we really allow *any* type attribute? if (!isa<PointerType>(Desugared)) { if (Type->isMemberPointerType()) S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; else S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; return true; } Type = State.getAttributedType(A, Type, Type); return false; } /// Rebuild an attributed type without the nullability attribute on it. static QualType rebuildAttributedTypeWithoutNullability(ASTContext &ctx, QualType type) { auto attributed = dyn_cast<AttributedType>(type.getTypePtr()); if (!attributed) return type; // Skip the nullability attribute; we're done. if (attributed->getImmediateNullability()) { return attributed->getModifiedType(); } // Build the modified type. auto modified = rebuildAttributedTypeWithoutNullability( ctx, attributed->getModifiedType()); assert(modified.getTypePtr() != attributed->getModifiedType().getTypePtr()); return ctx.getAttributedType(attributed->getAttrKind(), modified, attributed->getEquivalentType()); } /// Map a nullability attribute kind to a nullability kind. static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { switch (kind) { case ParsedAttr::AT_TypeNonNull: return NullabilityKind::NonNull; case ParsedAttr::AT_TypeNullable: return NullabilityKind::Nullable; case ParsedAttr::AT_TypeNullUnspecified: return NullabilityKind::Unspecified; default: llvm_unreachable("not a nullability attribute kind"); } } static bool checkNullabilityTypeSpecifier(Sema &S, TypeProcessingState *state, ParsedAttr *parsedAttr, QualType &type, NullabilityKind nullability, SourceLocation nullabilityLoc, bool isContextSensitive, bool allowOnArrayType, bool overrideExisting) { bool implicit = (state == nullptr); if (!implicit) recordNullabilitySeen(S, nullabilityLoc); // Check for existing nullability attributes on the type. QualType desugared = type; while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { // Check whether there is already a null if (auto existingNullability = attributed->getImmediateNullability()) { // Duplicated nullability. if (nullability == *existingNullability) { if (implicit) break; S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) << DiagNullabilityKind(nullability, isContextSensitive) << FixItHint::CreateRemoval(nullabilityLoc); break; } if (!overrideExisting) { // Conflicting nullability. S.Diag(nullabilityLoc, diag::err_nullability_conflicting) << DiagNullabilityKind(nullability, isContextSensitive) << DiagNullabilityKind(*existingNullability, false); return true; } // Rebuild the attributed type, dropping the existing nullability. type = rebuildAttributedTypeWithoutNullability(S.Context, type); } desugared = attributed->getModifiedType(); } // If there is already a different nullability specifier, complain. // This (unlike the code above) looks through typedefs that might // have nullability specifiers on them, which means we cannot // provide a useful Fix-It. if (auto existingNullability = desugared->getNullability(S.Context)) { if (nullability != *existingNullability && !implicit) { S.Diag(nullabilityLoc, diag::err_nullability_conflicting) << DiagNullabilityKind(nullability, isContextSensitive) << DiagNullabilityKind(*existingNullability, false); // Try to find the typedef with the existing nullability specifier. if (auto typedefType = desugared->getAs<TypedefType>()) { TypedefNameDecl *typedefDecl = typedefType->getDecl(); QualType underlyingType = typedefDecl->getUnderlyingType(); if (auto typedefNullability = AttributedType::stripOuterNullability(underlyingType)) { if (*typedefNullability == *existingNullability) { S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) << DiagNullabilityKind(*existingNullability, false); } } } return true; } } // If this definitely isn't a pointer type, reject the specifier. if (!desugared->canHaveNullability() && !(allowOnArrayType && desugared->isArrayType())) { if (!implicit) { S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) << DiagNullabilityKind(nullability, isContextSensitive) << type; } return true; } // For the context-sensitive keywords/Objective-C property // attributes, require that the type be a single-level pointer. if (isContextSensitive) { const Type *pointeeType; if (desugared->isArrayType()) pointeeType = desugared->getArrayElementTypeNoTypeQual(); else pointeeType = desugared->getPointeeType().getTypePtr(); if (pointeeType->isAnyPointerType() || pointeeType->isObjCObjectPointerType() || pointeeType->isMemberPointerType()) { S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) << DiagNullabilityKind(nullability, true) << type; S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) << DiagNullabilityKind(nullability, false) << type << FixItHint::CreateReplacement(nullabilityLoc, getNullabilitySpelling(nullability)); return true; } } // Form the attributed type. if (state) { assert(parsedAttr); Attr *A = createNullabilityAttr(S.Context, *parsedAttr, nullability); type = state->getAttributedType(A, type, type); } else { attr::Kind attrKind = AttributedType::getNullabilityAttrKind(nullability); type = S.Context.getAttributedType(attrKind, type, type); } return false; } static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, QualType &type, ParsedAttr &attr, bool allowOnArrayType) { NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); SourceLocation nullabilityLoc = attr.getLoc(); bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); return checkNullabilityTypeSpecifier(state.getSema(), &state, &attr, type, nullability, nullabilityLoc, isContextSensitive, allowOnArrayType, /*overrideExisting*/false); } bool Sema::checkImplicitNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, SourceLocation diagLoc, bool allowArrayTypes, bool overrideExisting) { return checkNullabilityTypeSpecifier(*this, nullptr, nullptr, type, nullability, diagLoc, /*isContextSensitive*/false, allowArrayTypes, overrideExisting); } /// Check the application of the Objective-C '__kindof' qualifier to /// the given type. static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, ParsedAttr &attr) { Sema &S = state.getSema(); if (isa<ObjCTypeParamType>(type)) { // Build the attributed type to record where __kindof occurred. type = state.getAttributedType( createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); return false; } const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() : type->getAs<ObjCObjectType>(); // If not, we can't apply __kindof. if (!objType) { // FIXME: Handle dependent types that aren't yet object types. S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) << type; return true; } // Rebuild the "equivalent" type, which pushes __kindof down into // the object type. // There is no need to apply kindof on an unqualified id type. QualType equivType = S.Context.getObjCObjectType( objType->getBaseType(), objType->getTypeArgsAsWritten(), objType->getProtocols(), /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); // If we started with an object pointer type, rebuild it. if (ptrType) { equivType = S.Context.getObjCObjectPointerType(equivType); if (auto nullability = type->getNullability(S.Context)) { // We create a nullability attribute from the __kindof attribute. // Make sure that will make sense. assert(attr.getAttributeSpellingListIndex() == 0 && "multiple spellings for __kindof?"); Attr *A = createNullabilityAttr(S.Context, attr, *nullability); A->setImplicit(true); equivType = state.getAttributedType(A, equivType, equivType); } } // Build the attributed type to record where __kindof occurred. type = state.getAttributedType( createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); return false; } /// Distribute a nullability type attribute that cannot be applied to /// the type specifier to a pointer, block pointer, or member pointer /// declarator, complaining if necessary. /// /// \returns true if the nullability annotation was distributed, false /// otherwise. static bool distributeNullabilityTypeAttr(TypeProcessingState &state, QualType type, ParsedAttr &attr) { Declarator &declarator = state.getDeclarator(); /// Attempt to move the attribute to the specified chunk. auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { // If there is already a nullability attribute there, don't add // one. if (hasNullabilityAttr(chunk.getAttrs())) return false; // Complain about the nullability qualifier being in the wrong // place. enum { PK_Pointer, PK_BlockPointer, PK_MemberPointer, PK_FunctionPointer, PK_MemberFunctionPointer, } pointerKind = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer : PK_Pointer) : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; auto diag = state.getSema().Diag(attr.getLoc(), diag::warn_nullability_declspec) << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), attr.isContextSensitiveKeywordAttribute()) << type << static_cast<unsigned>(pointerKind); // FIXME: MemberPointer chunks don't carry the location of the *. if (chunk.Kind != DeclaratorChunk::MemberPointer) { diag << FixItHint::CreateRemoval(attr.getLoc()) << FixItHint::CreateInsertion( state.getSema().getPreprocessor().getLocForEndOfToken( chunk.Loc), " " + attr.getAttrName()->getName().str() + " "); } moveAttrFromListToList(attr, state.getCurrentAttributes(), chunk.getAttrs()); return true; }; // Move it to the outermost pointer, member pointer, or block // pointer declarator. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { DeclaratorChunk &chunk = declarator.getTypeObject(i-1); switch (chunk.Kind) { case DeclaratorChunk::Pointer: case DeclaratorChunk::BlockPointer: case DeclaratorChunk::MemberPointer: return moveToChunk(chunk, false); case DeclaratorChunk::Paren: case DeclaratorChunk::Array: continue; case DeclaratorChunk::Function: // Try to move past the return type to a function/block/member // function pointer. if (DeclaratorChunk *dest = maybeMovePastReturnType( declarator, i, /*onlyBlockPointers=*/false)) { return moveToChunk(*dest, true); } return false; // Don't walk through these. case DeclaratorChunk::Reference: case DeclaratorChunk::Pipe: return false; } } return false; } static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { assert(!Attr.isInvalid()); switch (Attr.getKind()) { default: llvm_unreachable("not a calling convention attribute"); case ParsedAttr::AT_CDecl: return createSimpleAttr<CDeclAttr>(Ctx, Attr); case ParsedAttr::AT_FastCall: return createSimpleAttr<FastCallAttr>(Ctx, Attr); case ParsedAttr::AT_StdCall: return createSimpleAttr<StdCallAttr>(Ctx, Attr); case ParsedAttr::AT_ThisCall: return createSimpleAttr<ThisCallAttr>(Ctx, Attr); case ParsedAttr::AT_RegCall: return createSimpleAttr<RegCallAttr>(Ctx, Attr); case ParsedAttr::AT_Pascal: return createSimpleAttr<PascalAttr>(Ctx, Attr); case ParsedAttr::AT_SwiftCall: return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); case ParsedAttr::AT_VectorCall: return createSimpleAttr<VectorCallAttr>(Ctx, Attr); case ParsedAttr::AT_AArch64VectorPcs: return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); case ParsedAttr::AT_Pcs: { // The attribute may have had a fixit applied where we treated an // identifier as a string literal. The contents of the string are valid, // but the form may not be. StringRef Str; if (Attr.isArgExpr(0)) Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); else Str = Attr.getArgAsIdent(0)->Ident->getName(); PcsAttr::PCSType Type; if (!PcsAttr::ConvertStrToPCSType(Str, Type)) llvm_unreachable("already validated the attribute"); return ::new (Ctx) PcsAttr(Ctx, Attr, Type); } case ParsedAttr::AT_IntelOclBicc: return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); case ParsedAttr::AT_MSABI: return createSimpleAttr<MSABIAttr>(Ctx, Attr); case ParsedAttr::AT_SysVABI: return createSimpleAttr<SysVABIAttr>(Ctx, Attr); case ParsedAttr::AT_PreserveMost: return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); case ParsedAttr::AT_PreserveAll: return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); } llvm_unreachable("unexpected attribute kind!"); } /// Process an individual function attribute. Returns true to /// indicate that the attribute was handled, false if it wasn't. static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type) { Sema &S = state.getSema(); FunctionTypeUnwrapper unwrapped(S, type); if (attr.getKind() == ParsedAttr::AT_NoReturn) { if (S.CheckAttrNoArgs(attr)) return true; // Delay if this is not a function type. if (!unwrapped.isFunctionType()) return false; // Otherwise we can process right away. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); return true; } // ns_returns_retained is not always a type attribute, but if we got // here, we're treating it as one right now. if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { if (attr.getNumArgs()) return true; // Delay if this is not a function type. if (!unwrapped.isFunctionType()) return false; // Check whether the return type is reasonable. if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), unwrapped.get()->getReturnType())) return true; // Only actually change the underlying type in ARC builds. QualType origType = type; if (state.getSema().getLangOpts().ObjCAutoRefCount) { FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withProducesResult(true); type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); } type = state.getAttributedType( createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), origType, type); return true; } if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) return true; // Delay if this is not a function type. if (!unwrapped.isFunctionType()) return false; FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); return true; } if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { if (!S.getLangOpts().CFProtectionBranch) { S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); attr.setInvalid(); return true; } if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) return true; // If this is not a function type, warning will be asserted by subject // check. if (!unwrapped.isFunctionType()) return true; FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoCfCheck(true); type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); return true; } if (attr.getKind() == ParsedAttr::AT_Regparm) { unsigned value; if (S.CheckRegparmAttr(attr, value)) return true; // Delay if this is not a function type. if (!unwrapped.isFunctionType()) return false; // Diagnose regparm with fastcall. const FunctionType *fn = unwrapped.get(); CallingConv CC = fn->getCallConv(); if (CC == CC_X86FastCall) { S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) << FunctionType::getNameForCallConv(CC) << "regparm"; attr.setInvalid(); return true; } FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withRegParm(value); type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); return true; } if (attr.getKind() == ParsedAttr::AT_NoThrow) { // Delay if this is not a function type. if (!unwrapped.isFunctionType()) return false; if (S.CheckAttrNoArgs(attr)) { attr.setInvalid(); return true; } // Otherwise we can process right away. auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); // MSVC ignores nothrow if it is in conflict with an explicit exception // specification. if (Proto->hasExceptionSpec()) { switch (Proto->getExceptionSpecType()) { case EST_None: llvm_unreachable("This doesn't have an exception spec!"); case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue: case EST_NoThrow: // Exception spec doesn't conflict with nothrow, so don't warn. LLVM_FALLTHROUGH; case EST_Unparsed: case EST_Uninstantiated: case EST_DependentNoexcept: case EST_Unevaluated: // We don't have enough information to properly determine if there is a // conflict, so suppress the warning. break; case EST_Dynamic: case EST_MSAny: case EST_NoexceptFalse: S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); break; } return true; } type = unwrapped.wrap( S, S.Context .getFunctionTypeWithExceptionSpec( QualType{Proto, 0}, FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) ->getAs<FunctionType>()); return true; } // Delay if the type didn't work out to a function. if (!unwrapped.isFunctionType()) return false; // Otherwise, a calling convention. CallingConv CC; if (S.CheckCallingConvAttr(attr, CC)) return true; const FunctionType *fn = unwrapped.get(); CallingConv CCOld = fn->getCallConv(); Attr *CCAttr = getCCTypeAttr(S.Context, attr); if (CCOld != CC) { // Error out on when there's already an attribute on the type // and the CCs don't match. if (S.getCallingConvAttributedType(type)) { S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) << FunctionType::getNameForCallConv(CC) << FunctionType::getNameForCallConv(CCOld); attr.setInvalid(); return true; } } // Diagnose use of variadic functions with calling conventions that // don't support them (e.g. because they're callee-cleanup). // We delay warning about this on unprototyped function declarations // until after redeclaration checking, just in case we pick up a // prototype that way. And apparently we also "delay" warning about // unprototyped function types in general, despite not necessarily having // much ability to diagnose it later. if (!supportsVariadicCall(CC)) { const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); if (FnP && FnP->isVariadic()) { // stdcall and fastcall are ignored with a warning for GCC and MS // compatibility. if (CC == CC_X86StdCall || CC == CC_X86FastCall) return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) << FunctionType::getNameForCallConv(CC) << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; attr.setInvalid(); return S.Diag(attr.getLoc(), diag::err_cconv_varargs) << FunctionType::getNameForCallConv(CC); } } // Also diagnose fastcall with regparm. if (CC == CC_X86FastCall && fn->getHasRegParm()) { S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); attr.setInvalid(); return true; } // Modify the CC from the wrapped function type, wrap it all back, and then // wrap the whole thing in an AttributedType as written. The modified type // might have a different CC if we ignored the attribute. QualType Equivalent; if (CCOld == CC) { Equivalent = type; } else { auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); Equivalent = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); } type = state.getAttributedType(CCAttr, type, Equivalent); return true; } bool Sema::hasExplicitCallingConv(QualType T) { const AttributedType *AT; // Stop if we'd be stripping off a typedef sugar node to reach the // AttributedType. while ((AT = T->getAs<AttributedType>()) && AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { if (AT->isCallingConv()) return true; T = AT->getModifiedType(); } return false; } void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc) { FunctionTypeUnwrapper Unwrapped(*this, T); const FunctionType *FT = Unwrapped.get(); bool IsVariadic = (isa<FunctionProtoType>(FT) && cast<FunctionProtoType>(FT)->isVariadic()); CallingConv CurCC = FT->getCallConv(); CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); if (CurCC == ToCC) return; // MS compiler ignores explicit calling convention attributes on structors. We // should do the same. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { // Issue a warning on ignored calling convention -- except of __stdcall. // Again, this is what MS compiler does. if (CurCC != CC_X86StdCall) Diag(Loc, diag::warn_cconv_unsupported) << FunctionType::getNameForCallConv(CurCC) << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; // Default adjustment. } else { // Only adjust types with the default convention. For example, on Windows // we should adjust a __cdecl type to __thiscall for instance methods, and a // __thiscall type to __cdecl for static methods. CallingConv DefaultCC = Context.getDefaultCallingConvention(IsVariadic, IsStatic); if (CurCC != DefaultCC || DefaultCC == ToCC) return; if (hasExplicitCallingConv(T)) return; } FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); QualType Wrapped = Unwrapped.wrap(*this, FT); T = Context.getAdjustedType(T, Wrapped); } /// HandleVectorSizeAttribute - this attribute is only applicable to integral /// and float scalars, although arrays, pointers, and function return values are /// allowed in conjunction with this construct. Aggregates with this attribute /// are invalid, even if they are of the same size as a corresponding scalar. /// The raw attribute should contain precisely 1 argument, the vector size for /// the variable, measured in bytes. If curType and rawAttr are well formed, /// this routine will return a new vector type. static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S) { // Check the attribute arguments. if (Attr.getNumArgs() != 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr << 1; Attr.setInvalid(); return; } Expr *SizeExpr; // Special case where the argument is a template id. if (Attr.isArgIdent(0)) { CXXScopeSpec SS; SourceLocation TemplateKWLoc; UnqualifiedId Id; Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, Id, /*HasTrailingLParen=*/false, /*IsAddressOfOperand=*/false); if (Size.isInvalid()) return; SizeExpr = Size.get(); } else { SizeExpr = Attr.getArgAsExpr(0); } QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); if (!T.isNull()) CurType = T; else Attr.setInvalid(); } /// Process the OpenCL-like ext_vector_type attribute when it occurs on /// a type. static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S) { // check the attribute arguments. if (Attr.getNumArgs() != 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr << 1; return; } Expr *sizeExpr; // Special case where the argument is a template id. if (Attr.isArgIdent(0)) { CXXScopeSpec SS; SourceLocation TemplateKWLoc; UnqualifiedId id; id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false, /*IsAddressOfOperand=*/false); if (Size.isInvalid()) return; sizeExpr = Size.get(); } else { sizeExpr = Attr.getArgAsExpr(0); } // Create the vector type. QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); if (!T.isNull()) CurType = T; } static bool isPermittedNeonBaseType(QualType &Ty, VectorType::VectorKind VecKind, Sema &S) { const BuiltinType *BTy = Ty->getAs<BuiltinType>(); if (!BTy) return false; llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); // Signed poly is mathematically wrong, but has been baked into some ABIs by // now. bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || Triple.getArch() == llvm::Triple::aarch64_be; if (VecKind == VectorType::NeonPolyVector) { if (IsPolyUnsigned) { // AArch64 polynomial vectors are unsigned and support poly64. return BTy->getKind() == BuiltinType::UChar || BTy->getKind() == BuiltinType::UShort || BTy->getKind() == BuiltinType::ULong || BTy->getKind() == BuiltinType::ULongLong; } else { // AArch32 polynomial vector are signed. return BTy->getKind() == BuiltinType::SChar || BTy->getKind() == BuiltinType::Short; } } // Non-polynomial vector types: the usual suspects are allowed, as well as // float64_t on AArch64. bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || Triple.getArch() == llvm::Triple::aarch64_be; if (Is64Bit && BTy->getKind() == BuiltinType::Double) return true; return BTy->getKind() == BuiltinType::SChar || BTy->getKind() == BuiltinType::UChar || BTy->getKind() == BuiltinType::Short || BTy->getKind() == BuiltinType::UShort || BTy->getKind() == BuiltinType::Int || BTy->getKind() == BuiltinType::UInt || BTy->getKind() == BuiltinType::Long || BTy->getKind() == BuiltinType::ULong || BTy->getKind() == BuiltinType::LongLong || BTy->getKind() == BuiltinType::ULongLong || BTy->getKind() == BuiltinType::Float || BTy->getKind() == BuiltinType::Half; } /// HandleNeonVectorTypeAttr - The "neon_vector_type" and /// "neon_polyvector_type" attributes are used to create vector types that /// are mangled according to ARM's ABI. Otherwise, these types are identical /// to those created with the "vector_size" attribute. Unlike "vector_size" /// the argument to these Neon attributes is the number of vector elements, /// not the vector size in bytes. The vector width and element type must /// match one of the standard Neon vector types. static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S, VectorType::VectorKind VecKind) { // Target must have NEON (or MVE, whose vectors are similar enough // not to need a separate attribute) if (!S.Context.getTargetInfo().hasFeature("neon") && !S.Context.getTargetInfo().hasFeature("mve")) { S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr; Attr.setInvalid(); return; } // Check the attribute arguments. if (Attr.getNumArgs() != 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr << 1; Attr.setInvalid(); return; } // The number of elements must be an ICE. Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); llvm::APSInt numEltsInt(32); if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr << AANT_ArgumentIntegerConstant << numEltsExpr->getSourceRange(); Attr.setInvalid(); return; } // Only certain element types are supported for Neon vectors. if (!isPermittedNeonBaseType(CurType, VecKind, S)) { S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; Attr.setInvalid(); return; } // The total size of the vector must be 64 or 128 bits. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); unsigned vecSize = typeSize * numElts; if (vecSize != 64 && vecSize != 128) { S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; Attr.setInvalid(); return; } CurType = S.Context.getVectorType(CurType, numElts, VecKind); } /// Handle the __ptrauth qualifier. static void HandlePtrAuthQualifier(QualType &type, const ParsedAttr &attr, Sema &S) { if (attr.getNumArgs() < 1 || attr.getNumArgs() > 3) { S.Diag(attr.getLoc(), diag::err_ptrauth_qualifier_bad_arg_count); attr.setInvalid(); return; } Expr *keyArg = attr.getArgAsExpr(0); Expr *isAddressDiscriminatedArg = attr.getNumArgs() >= 2 ? attr.getArgAsExpr(1) : nullptr; Expr *extraDiscriminatorArg = attr.getNumArgs() >= 3 ? attr.getArgAsExpr(2) : nullptr; unsigned key; if (S.checkConstantPointerAuthKey(keyArg, key)) { attr.setInvalid(); return; } assert(key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range"); bool isInvalid = false; auto checkArg = [&](Expr *arg, unsigned argIndex) -> unsigned { if (!arg) return 0; llvm::APSInt result; if (!arg->isIntegerConstantExpr(result, S.Context)) { isInvalid = true; S.Diag(arg->getExprLoc(), diag::err_ptrauth_qualifier_arg_not_ice); return 0; } unsigned max = (argIndex == 1 ? 1 : PointerAuthQualifier::MaxDiscriminator); if (result < 0 || result > max) { llvm::SmallString<32> value; { llvm::raw_svector_ostream str(value); str << result; } if (argIndex == 1) { S.Diag(arg->getExprLoc(), diag::err_ptrauth_qualifier_address_discrimination_invalid) << value; } else { S.Diag(arg->getExprLoc(), diag::err_ptrauth_qualifier_extra_discriminator_invalid) << value << max; } isInvalid = true; } return result.getZExtValue(); }; bool isAddressDiscriminated = checkArg(isAddressDiscriminatedArg, 1); unsigned extraDiscriminator = checkArg(extraDiscriminatorArg, 2); if (isInvalid) { attr.setInvalid(); return; } if (!type->isPointerType()) { S.Diag(attr.getLoc(), diag::err_ptrauth_qualifier_nonpointer) << type; attr.setInvalid(); return; } if (type.getPointerAuth()) { S.Diag(attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << type; attr.setInvalid(); return; } if (!S.getLangOpts().PointerAuthIntrinsics) { S.diagnosePointerAuthDisabled(attr.getLoc(), attr.getRange()); attr.setInvalid(); return; } PointerAuthQualifier qual(key, isAddressDiscriminated, extraDiscriminator); type = S.Context.getPointerAuthType(type, qual); } /// Handle OpenCL Access Qualifier Attribute. static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S) { // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. if (!(CurType->isImageType() || CurType->isPipeType())) { S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); Attr.setInvalid(); return; } if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { QualType BaseTy = TypedefTy->desugar(); std::string PrevAccessQual; if (BaseTy->isPipeType()) { if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { OpenCLAccessAttr *Attr = TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); PrevAccessQual = Attr->getSpelling(); } else { PrevAccessQual = "read_only"; } } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { switch (ImgType->getKind()) { #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: \ PrevAccessQual = #Access; \ break; #include "clang/Basic/OpenCLImageTypes.def" default: llvm_unreachable("Unable to find corresponding image type."); } } else { llvm_unreachable("unexpected type"); } StringRef AttrName = Attr.getAttrName()->getName(); if (PrevAccessQual == AttrName.ltrim("_")) { // Duplicated qualifiers S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) << AttrName << Attr.getRange(); } else { // Contradicting qualifiers S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); } S.Diag(TypedefTy->getDecl()->getBeginLoc(), diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; } else if (CurType->isPipeType()) { if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { QualType ElemType = CurType->getAs<PipeType>()->getElementType(); CurType = S.Context.getWritePipeType(ElemType); } } } static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, QualType &T, TypeAttrLocation TAL) { Declarator &D = State.getDeclarator(); // Handle the cases where address space should not be deduced. // // The pointee type of a pointer type is always deduced since a pointer always // points to some memory location which should has an address space. // // There are situations that at the point of certain declarations, the address // space may be unknown and better to be left as default. For example, when // defining a typedef or struct type, they are not associated with any // specific address space. Later on, they may be used with any address space // to declare a variable. // // The return value of a function is r-value, therefore should not have // address space. // // The void type does not occupy memory, therefore should not have address // space, except when it is used as a pointee type. // // Since LLVM assumes function type is in default address space, it should not // have address space. auto ChunkIndex = State.getCurrentChunkIndex(); bool IsPointee = ChunkIndex > 0 && (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer || D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference || D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer); // For pointers/references to arrays the next chunk is always an array // followed by any number of parentheses. if (!IsPointee && ChunkIndex > 1) { auto AdjustedCI = ChunkIndex - 1; if (D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Array) AdjustedCI--; // Skip over all parentheses. while (AdjustedCI > 0 && D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Paren) AdjustedCI--; if (D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Pointer || D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Reference) IsPointee = true; } bool IsFuncReturnType = ChunkIndex > 0 && D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function; bool IsFuncType = ChunkIndex < D.getNumTypeObjects() && D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function; if ( // Do not deduce addr space for function return type and function type, // otherwise it will fail some sema check. IsFuncReturnType || IsFuncType || // Do not deduce addr space for member types of struct, except the pointee // type of a pointer member type or static data members. (D.getContext() == DeclaratorContext::MemberContext && (!IsPointee && D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)) || // Do not deduce addr space of non-pointee in type alias because it // doesn't define any object. (D.getContext() == DeclaratorContext::AliasDeclContext && !IsPointee) || // Do not deduce addr space for types used to define a typedef and the // typedef itself, except the pointee type of a pointer type which is used // to define the typedef. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef && !IsPointee) || // Do not deduce addr space of the void type, e.g. in f(void), otherwise // it will fail some sema check. (T->isVoidType() && !IsPointee) || // Do not deduce addr spaces for dependent types because they might end // up instantiating to a type with an explicit address space qualifier. // Except for pointer or reference types because the addr space in // template argument can only belong to a pointee. (T->isDependentType() && !T->isPointerType() && !T->isReferenceType()) || // Do not deduce addr space of decltype because it will be taken from // its argument. T->isDecltypeType() || // OpenCL spec v2.0 s6.9.b: // The sampler type cannot be used with the __local and __global address // space qualifiers. // OpenCL spec v2.0 s6.13.14: // Samplers can also be declared as global constants in the program // source using the following syntax. // const sampler_t <sampler name> = <value> // In codegen, file-scope sampler type variable has special handing and // does not rely on address space qualifier. On the other hand, deducing // address space of const sampler file-scope variable as global address // space causes spurious diagnostic about __global address space // qualifier, therefore do not deduce address space of file-scope sampler // type variable. (D.getContext() == DeclaratorContext::FileContext && T->isSamplerT())) return; LangAS ImpAddr = LangAS::Default; // Put OpenCL automatic variable in private address space. // OpenCL v1.2 s6.5: // The default address space name for arguments to a function in a // program, or local variables of a function is __private. All function // arguments shall be in the __private address space. if (State.getSema().getLangOpts().OpenCLVersion <= 120 && !State.getSema().getLangOpts().OpenCLCPlusPlus) { ImpAddr = LangAS::opencl_private; } else { // If address space is not set, OpenCL 2.0 defines non private default // address spaces for some cases: // OpenCL 2.0, section 6.5: // The address space for a variable at program scope or a static variable // inside a function can either be __global or __constant, but defaults to // __global if not specified. // (...) // Pointers that are declared without pointing to a named address space // point to the generic address space. if (IsPointee) { ImpAddr = LangAS::opencl_generic; } else { if (D.getContext() == DeclaratorContext::TemplateArgContext) { // Do not deduce address space for non-pointee type in template arg. } else if (D.getContext() == DeclaratorContext::FileContext) { ImpAddr = LangAS::opencl_global; } else { if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) { ImpAddr = LangAS::opencl_global; } else { ImpAddr = LangAS::opencl_private; } } } } T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); } static void HandleLifetimeBoundAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr) { if (State.getDeclarator().isDeclarationOfFunction()) { CurType = State.getAttributedType( createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), CurType, CurType); } else { Attr.diagnoseAppertainsTo(State.getSema(), nullptr); } } static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, ParsedAttributesView &attrs) { // Scan through and apply attributes to this type where it makes sense. Some // attributes (such as __address_space__, __vector_size__, etc) apply to the // type, but others can be present in the type specifiers even though they // apply to the decl. Here we apply type attributes and ignore the rest. // This loop modifies the list pretty frequently, but we still need to make // sure we visit every element once. Copy the attributes list, and iterate // over that. ParsedAttributesView AttrsCopy{attrs}; state.setParsedNoDeref(false); for (ParsedAttr &attr : AttrsCopy) { // Skip attributes that were marked to be invalid. if (attr.isInvalid()) continue; if (attr.isCXX11Attribute()) { // [[gnu::...]] attributes are treated as declaration attributes, so may // not appertain to a DeclaratorChunk. If we handle them as type // attributes, accept them in that position and diagnose the GCC // incompatibility. if (attr.isGNUScope()) { bool IsTypeAttr = attr.isTypeAttr(); if (TAL == TAL_DeclChunk) { state.getSema().Diag(attr.getLoc(), IsTypeAttr ? diag::warn_gcc_ignores_type_attr : diag::warn_cxx11_gnu_attribute_on_type) << attr; if (!IsTypeAttr) continue; } } else if (TAL != TAL_DeclChunk && attr.getKind() != ParsedAttr::AT_AddressSpace) { // Otherwise, only consider type processing for a C++11 attribute if // it's actually been applied to a type. // We also allow C++11 address_space attributes to pass through. continue; } } // If this is an attribute we can handle, do so now, // otherwise, add it to the FnAttrs list for rechaining. switch (attr.getKind()) { default: // A C++11 attribute on a declarator chunk must appertain to a type. if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) << attr; attr.setUsedAsTypeAttr(); } break; case ParsedAttr::UnknownAttribute: if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) state.getSema().Diag(attr.getLoc(), diag::warn_unknown_attribute_ignored) << attr; break; case ParsedAttr::IgnoredAttribute: break; case ParsedAttr::AT_MayAlias: // FIXME: This attribute needs to actually be handled, but if we ignore // it it breaks large amounts of Linux software. attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_OpenCLPrivateAddressSpace: case ParsedAttr::AT_OpenCLGlobalAddressSpace: case ParsedAttr::AT_OpenCLLocalAddressSpace: case ParsedAttr::AT_OpenCLConstantAddressSpace: case ParsedAttr::AT_OpenCLGenericAddressSpace: case ParsedAttr::AT_AddressSpace: HandleAddressSpaceTypeAttribute(type, attr, state); attr.setUsedAsTypeAttr(); break; OBJC_POINTER_TYPE_ATTRS_CASELIST: if (!handleObjCPointerTypeAttr(state, attr, type)) distributeObjCPointerTypeAttr(state, attr, type); attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_VectorSize: HandleVectorSizeAttr(type, attr, state.getSema()); attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_ExtVectorType: HandleExtVectorTypeAttr(type, attr, state.getSema()); attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_NeonVectorType: HandleNeonVectorTypeAttr(type, attr, state.getSema(), VectorType::NeonVector); attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_NeonPolyVectorType: HandleNeonVectorTypeAttr(type, attr, state.getSema(), VectorType::NeonPolyVector); attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_OpenCLAccess: HandleOpenCLAccessAttr(type, attr, state.getSema()); attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_PointerAuth: HandlePtrAuthQualifier(type, attr, state.getSema()); attr.setUsedAsTypeAttr(); break; case ParsedAttr::AT_LifetimeBound: if (TAL == TAL_DeclChunk) HandleLifetimeBoundAttr(state, type, attr); break; case ParsedAttr::AT_NoDeref: { ASTContext &Ctx = state.getSema().Context; type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), type, type); attr.setUsedAsTypeAttr(); state.setParsedNoDeref(true); break; } MS_TYPE_ATTRS_CASELIST: if (!handleMSPointerTypeQualifierAttr(state, attr, type)) attr.setUsedAsTypeAttr(); break; NULLABILITY_TYPE_ATTRS_CASELIST: // Either add nullability here or try to distribute it. We // don't want to distribute the nullability specifier past any // dependent type, because that complicates the user model. if (type->canHaveNullability() || type->isDependentType() || type->isArrayType() || !distributeNullabilityTypeAttr(state, type, attr)) { unsigned endIndex; if (TAL == TAL_DeclChunk) endIndex = state.getCurrentChunkIndex(); else endIndex = state.getDeclarator().getNumTypeObjects(); bool allowOnArrayType = state.getDeclarator().isPrototypeContext() && !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); if (checkNullabilityTypeSpecifier( state, type, attr, allowOnArrayType)) { attr.setInvalid(); } attr.setUsedAsTypeAttr(); } break; case ParsedAttr::AT_ObjCKindOf: // '__kindof' must be part of the decl-specifiers. switch (TAL) { case TAL_DeclSpec: break; case TAL_DeclChunk: case TAL_DeclName: state.getSema().Diag(attr.getLoc(), diag::err_objc_kindof_wrong_position) << FixItHint::CreateRemoval(attr.getLoc()) << FixItHint::CreateInsertion( state.getDeclarator().getDeclSpec().getBeginLoc(), "__kindof "); break; } // Apply it regardless. if (checkObjCKindOfType(state, type, attr)) attr.setInvalid(); break; case ParsedAttr::AT_NoThrow: // Exception Specifications aren't generally supported in C mode throughout // clang, so revert to attribute-based handling for C. if (!state.getSema().getLangOpts().CPlusPlus) break; LLVM_FALLTHROUGH; FUNCTION_TYPE_ATTRS_CASELIST: attr.setUsedAsTypeAttr(); // Never process function type attributes as part of the // declaration-specifiers. if (TAL == TAL_DeclSpec) distributeFunctionTypeAttrFromDeclSpec(state, attr, type); // Otherwise, handle the possible delays. else if (!handleFunctionTypeAttr(state, attr, type)) distributeFunctionTypeAttr(state, attr, type); break; } // Handle attributes that are defined in a macro. We do not want this to be // applied to ObjC builtin attributes. if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && !type.getQualifiers().hasObjCLifetime() && !type.getQualifiers().hasObjCGCAttr() && attr.getKind() != ParsedAttr::AT_ObjCGC && attr.getKind() != ParsedAttr::AT_ObjCOwnership) { const IdentifierInfo *MacroII = attr.getMacroIdentifier(); type = state.getSema().Context.getMacroQualifiedType(type, MacroII); state.setExpansionLocForMacroQualifiedType( cast<MacroQualifiedType>(type.getTypePtr()), attr.getMacroExpansionLoc()); } } if (!state.getSema().getLangOpts().OpenCL || type.getAddressSpace() != LangAS::Default) return; deduceOpenCLImplicitAddrSpace(state, type, TAL); } void Sema::completeExprArrayBound(Expr *E) { if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { auto *Def = Var->getDefinition(); if (!Def) { SourceLocation PointOfInstantiation = E->getExprLoc(); runWithSufficientStackSpace(PointOfInstantiation, [&] { InstantiateVariableDefinition(PointOfInstantiation, Var); }); Def = Var->getDefinition(); // If we don't already have a point of instantiation, and we managed // to instantiate a definition, this is the point of instantiation. // Otherwise, we don't request an end-of-TU instantiation, so this is // not a point of instantiation. // FIXME: Is this really the right behavior? if (Var->getPointOfInstantiation().isInvalid() && Def) { assert(Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation"); Var->setTemplateSpecializationKind( Var->getTemplateSpecializationKind(), PointOfInstantiation); } } // Update the type to the definition's type both here and within the // expression. if (Def) { DRE->setDecl(Def); QualType T = Def->getType(); DRE->setType(T); // FIXME: Update the type on all intervening expressions. E->setType(T); } // We still go on to try to complete the type independently, as it // may also require instantiations or diagnostics if it remains // incomplete. } } } } /// Ensure that the type of the given expression is complete. /// /// This routine checks whether the expression \p E has a complete type. If the /// expression refers to an instantiable construct, that instantiation is /// performed as needed to complete its type. Furthermore /// Sema::RequireCompleteType is called for the expression's type (or in the /// case of a reference type, the referred-to type). /// /// \param E The expression whose type is required to be complete. /// \param Diagnoser The object that will emit a diagnostic if the type is /// incomplete. /// /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false /// otherwise. bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { QualType T = E->getType(); // Incomplete array types may be completed by the initializer attached to // their definitions. For static data members of class templates and for // variable templates, we need to instantiate the definition to get this // initializer and complete the type. if (T->isIncompleteArrayType()) { completeExprArrayBound(E); T = E->getType(); } // FIXME: Are there other cases which require instantiating something other // than the type to complete the type of an expression? return RequireCompleteType(E->getExprLoc(), T, Diagnoser); } bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { BoundTypeDiagnoser<> Diagnoser(DiagID); return RequireCompleteExprType(E, Diagnoser); } /// Ensure that the type T is a complete type. /// /// This routine checks whether the type @p T is complete in any /// context where a complete type is required. If @p T is a complete /// type, returns false. If @p T is a class template specialization, /// this routine then attempts to perform class template /// instantiation. If instantiation fails, or if @p T is incomplete /// and cannot be completed, issues the diagnostic @p diag (giving it /// the type @p T) and returns true. /// /// @param Loc The location in the source that the incomplete type /// diagnostic should refer to. /// /// @param T The type that this routine is examining for completeness. /// /// @returns @c true if @p T is incomplete and a diagnostic was emitted, /// @c false otherwise. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) return true; if (const TagType *Tag = T->getAs<TagType>()) { if (!Tag->getDecl()->isCompleteDefinitionRequired()) { Tag->getDecl()->setCompleteDefinitionRequired(); Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); } } return false; } bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; if (!Suggested) return false; // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext // and isolate from other C++ specific checks. StructuralEquivalenceContext Ctx( D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, StructuralEquivalenceKind::Default, false /*StrictTypeSpelling*/, true /*Complain*/, true /*ErrorOnTagTypeMismatch*/); return Ctx.IsEquivalent(D, Suggested); } /// Determine whether there is any declaration of \p D that was ever a /// definition (perhaps before module merging) and is currently visible. /// \param D The definition of the entity. /// \param Suggested Filled in with the declaration that should be made visible /// in order to provide a definition of this entity. /// \param OnlyNeedComplete If \c true, we only need the type to be complete, /// not defined. This only matters for enums with a fixed underlying /// type, since in all other cases, a type is complete if and only if it /// is defined. bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete) { // Easy case: if we don't have modules, all declarations are visible. if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) return true; // If this definition was instantiated from a template, map back to the // pattern from which it was instantiated. if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { // We're in the middle of defining it; this definition should be treated // as visible. return true; } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { if (auto *Pattern = RD->getTemplateInstantiationPattern()) RD = Pattern; D = RD->getDefinition(); } else if (auto *ED = dyn_cast<EnumDecl>(D)) { if (auto *Pattern = ED->getTemplateInstantiationPattern()) ED = Pattern; if (OnlyNeedComplete && ED->isFixed()) { // If the enum has a fixed underlying type, and we're only looking for a // complete type (not a definition), any visible declaration of it will // do. *Suggested = nullptr; for (auto *Redecl : ED->redecls()) { if (isVisible(Redecl)) return true; if (Redecl->isThisDeclarationADefinition() || (Redecl->isCanonicalDecl() && !*Suggested)) *Suggested = Redecl; } return false; } D = ED->getDefinition(); } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { if (auto *Pattern = FD->getTemplateInstantiationPattern()) FD = Pattern; D = FD->getDefinition(); } else if (auto *VD = dyn_cast<VarDecl>(D)) { if (auto *Pattern = VD->getTemplateInstantiationPattern()) VD = Pattern; D = VD->getDefinition(); } assert(D && "missing definition for pattern of instantiated definition"); *Suggested = D; auto DefinitionIsVisible = [&] { // The (primary) definition might be in a visible module. if (isVisible(D)) return true; // A visible module might have a merged definition instead. if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) : hasVisibleMergedDefinition(D)) { if (CodeSynthesisContexts.empty() && !getLangOpts().ModulesLocalVisibility) { // Cache the fact that this definition is implicitly visible because // there is a visible merged definition. D->setVisibleDespiteOwningModule(); } return true; } return false; }; if (DefinitionIsVisible()) return true; // The external source may have additional definitions of this entity that are // visible, so complete the redeclaration chain now and ask again. if (auto *Source = Context.getExternalSource()) { Source->CompleteRedeclChain(D); return DefinitionIsVisible(); } return false; } /// Locks in the inheritance model for the given class and all of its bases. static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { RD = RD->getMostRecentNonInjectedDecl(); if (!RD->hasAttr<MSInheritanceAttr>()) { MSInheritanceAttr::Spelling IM; switch (S.MSPointerToMemberRepresentationMethod) { case LangOptions::PPTMK_BestCase: IM = RD->calculateInheritanceModel(); break; case LangOptions::PPTMK_FullGeneralitySingleInheritance: IM = MSInheritanceAttr::Keyword_single_inheritance; break; case LangOptions::PPTMK_FullGeneralityMultipleInheritance: IM = MSInheritanceAttr::Keyword_multiple_inheritance; break; case LangOptions::PPTMK_FullGeneralityVirtualInheritance: IM = MSInheritanceAttr::Keyword_unspecified_inheritance; break; } SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() ? S.ImplicitMSInheritanceAttrLoc : RD->getSourceRange(); RD->addAttr(MSInheritanceAttr::CreateImplicit( S.getASTContext(), /*BestCase=*/S.MSPointerToMemberRepresentationMethod == LangOptions::PPTMK_BestCase, Loc, AttributeCommonInfo::AS_Microsoft, IM)); S.Consumer.AssignInheritanceModel(RD); } } /// The implementation of RequireCompleteType bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser *Diagnoser) { // FIXME: Add this assertion to make sure we always get instantiation points. // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); // FIXME: Add this assertion to help us flush out problems with // checking for dependent types and type-dependent expressions. // // assert(!T->isDependentType() && // "Can't ask whether a dependent type is complete"); if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { if (!MPTy->getClass()->isDependentType()) { if (getLangOpts().CompleteMemberPointers && !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), diag::err_memptr_incomplete)) return true; // We lock in the inheritance model once somebody has asked us to ensure // that a pointer-to-member type is complete. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); } } } NamedDecl *Def = nullptr; bool Incomplete = T->isIncompleteType(&Def); // Check that any necessary explicit specializations are visible. For an // enum, we just need the declaration, so don't check this. if (Def && !isa<EnumDecl>(Def)) checkSpecializationVisibility(Loc, Def); // If we have a complete type, we're done. if (!Incomplete) { // If we know about the definition but it is not visible, complain. NamedDecl *SuggestedDef = nullptr; if (Def && !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { // If the user is going to see an error here, recover by making the // definition visible. bool TreatAsComplete = Diagnoser && !isSFINAEContext(); if (Diagnoser && SuggestedDef) diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, /*Recover*/TreatAsComplete); return !TreatAsComplete; } else if (Def && !TemplateInstCallbacks.empty()) { CodeSynthesisContext TempInst; TempInst.Kind = CodeSynthesisContext::Memoization; TempInst.Template = Def; TempInst.Entity = Def; TempInst.PointOfInstantiation = Loc; atTemplateBegin(TemplateInstCallbacks, *this, TempInst); atTemplateEnd(TemplateInstCallbacks, *this, TempInst); } return false; } TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); // Give the external source a chance to provide a definition of the type. // This is kept separate from completing the redeclaration chain so that // external sources such as LLDB can avoid synthesizing a type definition // unless it's actually needed. if (Tag || IFace) { // Avoid diagnosing invalid decls as incomplete. if (Def->isInvalidDecl()) return true; // Give the external AST source a chance to complete the type. if (auto *Source = Context.getExternalSource()) { if (Tag && Tag->hasExternalLexicalStorage()) Source->CompleteType(Tag); if (IFace && IFace->hasExternalLexicalStorage()) Source->CompleteType(IFace); // If the external source completed the type, go through the motions // again to ensure we're allowed to use the completed type. if (!T->isIncompleteType()) return RequireCompleteTypeImpl(Loc, T, Diagnoser); } } // If we have a class template specialization or a class member of a // class template specialization, or an array with known size of such, // try to instantiate it. if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { bool Instantiated = false; bool Diagnosed = false; if (RD->isDependentContext()) { // Don't try to instantiate a dependent class (eg, a member template of // an instantiated class template specialization). // FIXME: Can this ever happen? } else if (auto *ClassTemplateSpec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { runWithSufficientStackSpace(Loc, [&] { Diagnosed = InstantiateClassTemplateSpecialization( Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, /*Complain=*/Diagnoser); }); Instantiated = true; } } else { CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); if (!RD->isBeingDefined() && Pattern) { MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); assert(MSI && "Missing member specialization information?"); // This record was instantiated from a class within a template. if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) { runWithSufficientStackSpace(Loc, [&] { Diagnosed = InstantiateClass(Loc, RD, Pattern, getTemplateInstantiationArgs(RD), TSK_ImplicitInstantiation, /*Complain=*/Diagnoser); }); Instantiated = true; } } } if (Instantiated) { // Instantiate* might have already complained that the template is not // defined, if we asked it to. if (Diagnoser && Diagnosed) return true; // If we instantiated a definition, check that it's usable, even if // instantiation produced an error, so that repeated calls to this // function give consistent answers. if (!T->isIncompleteType()) return RequireCompleteTypeImpl(Loc, T, Diagnoser); } } // FIXME: If we didn't instantiate a definition because of an explicit // specialization declaration, check that it's visible. if (!Diagnoser) return true; Diagnoser->diagnose(*this, Loc, T); // If the type was a forward declaration of a class/struct/union // type, produce a note. if (Tag && !Tag->isInvalidDecl()) Diag(Tag->getLocation(), Tag->isBeingDefined() ? diag::note_type_being_defined : diag::note_forward_declaration) << Context.getTagDeclType(Tag); // If the Objective-C class was a forward declaration, produce a note. if (IFace && !IFace->isInvalidDecl()) Diag(IFace->getLocation(), diag::note_forward_class); // If we have external information that we can use to suggest a fix, // produce a note. if (ExternalSource) ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); return true; } bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { BoundTypeDiagnoser<> Diagnoser(DiagID); return RequireCompleteType(Loc, T, Diagnoser); } /// Get diagnostic %select index for tag kind for /// literal type diagnostic message. /// WARNING: Indexes apply to particular diagnostics only! /// /// \returns diagnostic %select index. static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { switch (Tag) { case TTK_Struct: return 0; case TTK_Interface: return 1; case TTK_Class: return 2; default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); } } /// Ensure that the type T is a literal type. /// /// This routine checks whether the type @p T is a literal type. If @p T is an /// incomplete type, an attempt is made to complete it. If @p T is a literal /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving /// it the type @p T), along with notes explaining why the type is not a /// literal type, and returns true. /// /// @param Loc The location in the source that the non-literal type /// diagnostic should refer to. /// /// @param T The type that this routine is examining for literalness. /// /// @param Diagnoser Emits a diagnostic if T is not a literal type. /// /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, /// @c false otherwise. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { assert(!T->isDependentType() && "type should not be dependent"); QualType ElemType = Context.getBaseElementType(T); if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && T->isLiteralType(Context)) return false; Diagnoser.diagnose(*this, Loc, T); if (T->isVariableArrayType()) return true; const RecordType *RT = ElemType->getAs<RecordType>(); if (!RT) return true; const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); // A partially-defined class type can't be a literal type, because a literal // class type must have a trivial destructor (which can't be checked until // the class definition is complete). if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) return true; // [expr.prim.lambda]p3: // This class type is [not] a literal type. if (RD->isLambda() && !getLangOpts().CPlusPlus17) { Diag(RD->getLocation(), diag::note_non_literal_lambda); return true; } // If the class has virtual base classes, then it's not an aggregate, and // cannot have any constexpr constructors or a trivial default constructor, // so is non-literal. This is better to diagnose than the resulting absence // of constexpr constructors. if (RD->getNumVBases()) { Diag(RD->getLocation(), diag::note_non_literal_virtual_base) << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); for (const auto &I : RD->vbases()) Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) << I.getSourceRange(); } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && !RD->hasTrivialDefaultConstructor()) { Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; } else if (RD->hasNonLiteralTypeFieldsOrBases()) { for (const auto &I : RD->bases()) { if (!I.getType()->isLiteralType(Context)) { Diag(I.getBeginLoc(), diag::note_non_literal_base_class) << RD << I.getType() << I.getSourceRange(); return true; } } for (const auto *I : RD->fields()) { if (!I->getType()->isLiteralType(Context) || I->getType().isVolatileQualified()) { Diag(I->getLocation(), diag::note_non_literal_field) << RD << I << I->getType() << I->getType().isVolatileQualified(); return true; } } } else if (getLangOpts().CPlusPlus2a ? !RD->hasConstexprDestructor() : !RD->hasTrivialDestructor()) { // All fields and bases are of literal types, so have trivial or constexpr // destructors. If this class's destructor is non-trivial / non-constexpr, // it must be user-declared. CXXDestructorDecl *Dtor = RD->getDestructor(); assert(Dtor && "class has literal fields and bases but no dtor?"); if (!Dtor) return true; if (getLangOpts().CPlusPlus2a) { Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) << RD; } else { Diag(Dtor->getLocation(), Dtor->isUserProvided() ? diag::note_non_literal_user_provided_dtor : diag::note_non_literal_nontrivial_dtor) << RD; if (!Dtor->isUserProvided()) SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, /*Diagnose*/ true); } } return true; } bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { BoundTypeDiagnoser<> Diagnoser(DiagID); return RequireLiteralType(Loc, T, Diagnoser); } /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified /// by the nested-name-specifier contained in SS, and that is (re)declared by /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl) { if (T.isNull()) return T; NestedNameSpecifier *NNS; if (SS.isValid()) NNS = SS.getScopeRep(); else { if (Keyword == ETK_None) return T; NNS = nullptr; } return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); } QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { assert(!E->hasPlaceholderType() && "unexpected placeholder"); if (!getLangOpts().CPlusPlus && E->refersToBitField()) Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; if (!E->isTypeDependent()) { QualType T = E->getType(); if (const TagType *TT = T->getAs<TagType>()) DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); } return Context.getTypeOfExprType(E); } /// getDecltypeForExpr - Given an expr, will return the decltype for /// that expression, according to the rules in C++11 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. static QualType getDecltypeForExpr(Sema &S, Expr *E) { if (E->isTypeDependent()) return S.Context.DependentTy; // C++11 [dcl.type.simple]p4: // The type denoted by decltype(e) is defined as follows: // // - if e is an unparenthesized id-expression or an unparenthesized class // member access (5.2.5), decltype(e) is the type of the entity named // by e. If there is no such entity, or if e names a set of overloaded // functions, the program is ill-formed; // // We apply the same rules for Objective-C ivar and property references. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { const ValueDecl *VD = DRE->getDecl(); return VD->getType(); } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { if (const ValueDecl *VD = ME->getMemberDecl()) if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) return VD->getType(); } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { return IR->getDecl()->getType(); } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { if (PR->isExplicitProperty()) return PR->getExplicitProperty()->getType(); } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { return PE->getType(); } // C++11 [expr.lambda.prim]p18: // Every occurrence of decltype((x)) where x is a possibly // parenthesized id-expression that names an entity of automatic // storage duration is treated as if x were transformed into an // access to a corresponding data member of the closure type that // would have been declared if x were an odr-use of the denoted // entity. using namespace sema; if (S.getCurLambda()) { if (isa<ParenExpr>(E)) { if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); if (!T.isNull()) return S.Context.getLValueReferenceType(T); } } } } // C++11 [dcl.type.simple]p4: // [...] QualType T = E->getType(); switch (E->getValueKind()) { // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the // type of e; case VK_XValue: T = S.Context.getRValueReferenceType(T); break; // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the // type of e; case VK_LValue: T = S.Context.getLValueReferenceType(T); break; // - otherwise, decltype(e) is the type of e. case VK_RValue: break; } return T; } QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated) { assert(!E->hasPlaceholderType() && "unexpected placeholder"); if (AsUnevaluated && CodeSynthesisContexts.empty() && E->HasSideEffects(Context, false)) { // The expression operand for decltype is in an unevaluated expression // context, so side effects could result in unintended consequences. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); } return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); } QualType Sema::BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc) { switch (UKind) { case UnaryTransformType::EnumUnderlyingType: if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { Diag(Loc, diag::err_only_enums_have_underlying_types); return QualType(); } else { QualType Underlying = BaseType; if (!BaseType->isDependentType()) { // The enum could be incomplete if we're parsing its definition or // recovering from an error. NamedDecl *FwdDecl = nullptr; if (BaseType->isIncompleteType(&FwdDecl)) { Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; return QualType(); } EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); assert(ED && "EnumType has no EnumDecl"); DiagnoseUseOfDecl(ED, Loc); Underlying = ED->getIntegerType(); assert(!Underlying.isNull()); } return Context.getUnaryTransformType(BaseType, Underlying, UnaryTransformType::EnumUnderlyingType); } } llvm_unreachable("unknown unary transform type"); } QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { if (!T->isDependentType()) { // FIXME: It isn't entirely clear whether incomplete atomic types // are allowed or not; for simplicity, ban them for the moment. if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) return QualType(); int DisallowedKind = -1; if (T->isArrayType()) DisallowedKind = 1; else if (T->isFunctionType()) DisallowedKind = 2; else if (T->isReferenceType()) DisallowedKind = 3; else if (T->isAtomicType()) DisallowedKind = 4; else if (T.hasQualifiers()) DisallowedKind = 5; else if (!T.isTriviallyCopyableType(Context)) // Some other non-trivially-copyable type (probably a C++ class) DisallowedKind = 6; if (DisallowedKind != -1) { Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; return QualType(); } // FIXME: Do we need any handling for ARC here? } // Build the pointer type. return Context.getAtomicType(T); }
// Copyright (c) 2011-2013 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 "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); 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); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; 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; } 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::setModel(WalletModel *model) { this->model = model; } 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 CRYPTOCOINS</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("Cryptocoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your cryptocoins 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 Unlock: if(!model->setWalletLocked(false, oldpass)) { 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 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 2004-2005 (c) by Aitor Viana Sanchez, University of Alcala, Computer Engineering Department. For further information, please visit http://atc1.aut.uah.es This software is provided under the terms of the GNU General Public v2 Licence. A full copy of the GNU GPL is provided in the file COPYING found in the development root of ERCOS-RT. */ #include "edroombp_sys.h" extern "C" { #include <kernel/task.h> #include <kernel/time.h> #include <kernel/traps.h> }; /* Not necessary, we'll go right through it! */ // static pthread_key_t key; //****************************************************** //**************** Pr_Kernel ************************** //****************************************************** Pr_Kernel::Pr_Kernel() { } void Pr_Kernel::Start() { int current_tid = SYS_GetCurrentTid(); SYS_SetPriority(current_tid, EDROOMprioIDLE); } //****************************************************** //**************** Pr_Task **************************** //****************************************************** //**************** CONSTRUCTORS *********************** #ifdef _EDROOM_IS_DEBUG_ Pr_Task::Pr_Task(void *(*_taskCode)(void*), /* Task IP */ char *_p_name, /* Task name */ ROOMPriority _priority, /* task priority */ unsigned _stackSize):name(_p_name) /* stack size */ { #else Pr_Task::Pr_Task(void *(*_taskCode)(void*), /* Task IP */ ROOMPriority _priority, /* task priority */ unsigned _stackSize) /* stack size */ { #endif /* Stablish the task instruction pointer */ this->TaskIP = _taskCode; /* Init the task priorities */ priorityMsg = priorityTmp = _priority; taskID = SYS_TaskCreate(NULL, _stackSize, /* The thread stack size */ TaskFunction, /* The Instruction Pointer */ (void *)this, _priority); /* The thread priority */ } void *Pr_Task::TaskFunction(void *arg) { Pr_Task *mythis = (Pr_Task*)arg; // pthread_setspecific(key, (const void *)mythis); uint32 stackaddr, stacksize; uint32 *stackend; /* if(((1 << key) & ts_bitmap) == 0) return -1;*/ /* Get the caller stack parameters */ SYS_TaskGetStackParameters(&stackaddr, &stacksize); /* End stack address */ stackend = ((uint32*)stackaddr - stacksize); /* Init the thread specific storage area */ *(stackend) = (uint32)mythis; // *(stackend) = (uint32)mythis; // printf("Arranca tarea\n"); mythis->TaskIP(NULL); } void Pr_Task::SetPriority(ROOMPriority _priority) { priorityMsg = _priority; if (priorityTmp != priorityMsg) { priorityTmp = priorityMsg; ChangePriority(_priority); } } void Pr_Task::SetMaxPrioTmp(ROOMPriority _priority) { /* * We only change the priority if the new priority is greater than * (less value) the priorityTmp value */ if (_priority < priorityTmp) { priorityTmp = _priority; ChangePriority(_priority); } } void Pr_Task::SetMaxPrioMsg(ROOMPriority _priority) { if (_priority < priorityMsg) { priorityMsg = _priority; if (priorityMsg < priorityTmp) { priorityTmp = priorityMsg; ChangePriority(_priority); } } } void Pr_Task::RestorePrioMsg(void) { if (priorityTmp != priorityMsg) { priorityTmp = priorityMsg; ChangePriority(priorityMsg); } } ROOMPriority Pr_Task::GetTaskPrio() { return SYS_GetPriority(taskID); } void Pr_Task::ChangePriority(ROOMPriority _priority) { SYS_SetPriority(taskID, _priority); } //****************************************************** //**************** Pr_Time **************************** //****************************************************** //**************** CONSTRUCTORS *********************** Pr_Time::Pr_Time() { time.tv_sec = 0; time.tv_usec = 0; } Pr_Time::Pr_Time(Pr_Time &_time) { time.tv_usec = _time.time.tv_usec; time.tv_sec = _time.time.tv_sec; } Pr_Time::Pr_Time(float _seconds) { float secs = _seconds; time.tv_sec = time.tv_usec = 0; if(_seconds) { time.tv_sec = (uint32)secs; secs -= time.tv_sec; time.tv_usec = (unsigned long)(secs * 1000000); } } Pr_Time::Pr_Time(struct timeval _time) { uint32 usec; uint32 sec; sec = (uint32)(_time.tv_usec / 1000000); time.tv_sec = _time.tv_sec + sec; usec = _time.tv_usec - (sec * 1000000); time.tv_usec = usec; } //**************** MODIFIYING METHODS ********************** void Pr_Time::GetTime(void) { uint32 clicks; time.tv_sec = time.tv_usec = 0; clicks = OS_TimeGetTicks(); _ticks_to_timeval((&time),clicks); } //********** OPERATORS OVERLOAD ********************* Pr_Time& Pr_Time::operator+=(const Pr_Time &_time) { _timeval_add((&time), &(_time.time)); return *this; } Pr_Time& Pr_Time::operator-=(const Pr_Time &_time) { uint32 clicks1, clicks2; _timeval_to_ticks((&time), clicks1); _timeval_to_ticks((&_time.time), clicks2); clicks1 -= clicks2; _ticks_to_timeval((&time), clicks1); _timeval_normalize((&time)); return *this; } Pr_Time& Pr_Time::operator=(const Pr_Time &_time) { time.tv_usec = _time.time.tv_usec; time.tv_sec = _time.time.tv_sec; return *this; } int Pr_Time::operator==(const Pr_Time &_time) { return (_timeval_eq(&time, &(_time.time))); } int Pr_Time::operator!=(const Pr_Time &_time) { return (!_timeval_eq(&time, &(_time.time))); } int Pr_Time::operator>(const Pr_Time &_time) { return (_timeval_gt(&time, &(_time.time))); } int Pr_Time::operator<(const Pr_Time &_time) { return (_timeval_lt(&time, &(_time.time))); } int Pr_Time::operator>=(const Pr_Time &_time) { return (_timeval_ge(&time, &(_time.time))); } int Pr_Time::operator<=(const Pr_Time &_time) { return (_timeval_le(&time, &(_time.time))); } //******* CONVERSION METHODS TO STANDARD UNITS ****** float Pr_Time::Mints() const { clock_t nticks; nticks = time.tv_sec * CLICKS_PER_SEC; if (time.tv_usec) nticks = nticks + time.tv_usec * CLICKS_PER_USEC; return (float)(uint32)nticks / (CLICKS_PER_SEC * 60); } float Pr_Time::Secns() const { float aux; // struct timeval time1; // time1 = time; // _timeval_normalize((&time1)); aux = time.tv_sec + (float)time.tv_usec / 1000000; // aux = time1.tv_sec + (float)time1.tv_usec / 1000000; return (float)(aux); } float Pr_Time::Millis() const { float aux; aux = time.tv_sec * 1000 + (float)time.tv_usec / 1000; return(aux); } float Pr_Time::Micros() const { float aux; aux = time.tv_sec * 1000000 + time.tv_usec; return (float)(aux); } float Pr_Time::Ticks() const { float aux; aux = time.tv_sec * CLICKS_PER_SEC + time.tv_usec * CLICKS_PER_USEC; return (float)(aux); } void Pr_DelayIn(const Pr_Time &_interval) { uint32 clicks; _timeval_to_ticks((&_interval.time), clicks); SYS_Sleep(clicks); } void Pr_DelayAt( const Pr_Time &_time) { uint32 current, future; _timeval_to_ticks((&_time.time), future); current = OS_TimeGetTicks(); if (future > current) future -= current; else return; SYS_Sleep(future); } //******************************************************** //******************** Pr_Semaphore ******************** //******************************************************** Pr_Semaphore::Pr_Semaphore(unsigned int _value) { } //******************************************************** //******************** Pr_SemaphoreBin ***************** //******************************************************** #ifdef _EDROOM_IS_DEBUG_ Pr_SemaphoreBin::Pr_SemaphoreBin(char *p_name, uint32 _value) : name(p_name), Pr_Semaphore(_value) { SYS_SemInit(&sem, _value); } #else Pr_SemaphoreBin::Pr_SemaphoreBin(uint32 _value) : Pr_Semaphore(_value) { SYS_SemInit(&sem, _value); } #endif void Pr_SemaphoreBin::Signal() { SYS_SemPost(&sem); } void Pr_SemaphoreBin::Wait() { SYS_SemWait(&sem); } int Pr_SemaphoreBin::WaitCond() { int retval = 0; if (SYS_SemTryWait(&sem) == 0) retval = 1; else return retval; /* error, returna 0 */ return retval; /* OK, return 1 */ } bool Pr_SemaphoreBin::WaitTimed(const Pr_Time &_waittime) { bool retval; uint32 clicks; _timeval_to_ticks((&_waittime.time), clicks); retval = SYS_SemTimedWait(&sem, clicks); return (retval == 0); } //******************************************************** //******************** Pr_SemaphoreRec ***************** //******************************************************** #ifdef _EDROOM_IS_DEBUG_ Pr_SemaphoreRec::Pr_SemaphoreRec(char *p_name) : name(p_name) { SYS_MutexInit(&mutex, MUTEX_PRIO_INHERIT); } #else Pr_SemaphoreRec::Pr_SemaphoreRec() { SYS_MutexInit(&mutex, MUTEX_PRIO_INHERIT); } #endif void Pr_SemaphoreRec::Signal() { SYS_MutexUnLock(&mutex); } void Pr_SemaphoreRec::Wait() { SYS_MutexLock(&mutex); } int Pr_SemaphoreRec::WaitCond() { if (SYS_MutexTryLock(&mutex) == 0) return 1; else return 0; } void Pr_Send(Pr_Task &_task, void *_p_data) { _task.p_data = _p_data; _task.semReceive.Signal(); _task.semSend.Wait(); } void Pr_Receive(void * _p_data,unsigned _datalength) { uint8 taskSlot; Pr_Task *receiver; uint32 stackaddr, stacksize; uint32 *stackend; /* Get the caller stack parameters */ SYS_TaskGetStackParameters(&stackaddr, &stacksize); stackend = ((uint32*)stackaddr - stacksize); receiver = (Pr_Task *)*(stackend); receiver->semReceive.Wait(); uint8 *p_dataAux, *p_dataAuxReceiver; p_dataAux = (uint8 *)_p_data; p_dataAuxReceiver = (uint8 *)receiver->p_data; for (int i = 0; i < _datalength; ++i) *(p_dataAux + i) = *(p_dataAuxReceiver + i); receiver->semSend.Signal(); } //******************************************************** //******************** Pr_IRQManager ******************** //******************************************************** void Pr_IRQManager::Enable(uint32 IRQnum) { SYS_IntrUnlock(IRQnum); } void Pr_IRQManager::Disable(uint32 IRQnum) { SYS_IntrLock(IRQnum); } void Pr_IRQManager::Install(Pr_IRQHandler handler,uint32 IRQnum) { SYS_RegisterIRQ(IRQnum, handler); } void Pr_IRQManager::Restore(uint32 IRQnum) { SYS_RestoreIRQ(IRQnum); } void Pr_IRQManager::Force(uint32 IRQnum) { SYS_ForceIRQ(IRQnum); } //******************************************************** //******************** Pr_IRQManager ******************** //******************************************************** #ifdef _EDROOM_IS_DEBUG_ Pr_IRQEvent::Pr_IRQEvent(char * pname,unsigned char IRQ) : eventSem("Event Semaphore", 0), // init the semaphore name(pname) // the Event name { } #else Pr_IRQEvent::Pr_IRQEvent(unsigned char IRQ) : eventSem(0) // init the semaphore {} #endif void Pr_IRQEvent::Signal() { eventSem.Signal(); } void Pr_IRQEvent::Wait() { eventSem.Wait(); } bool Pr_IRQEvent::WaitTimed(Pr_Time _time) { return eventSem.WaitTimed(_time); } bool Pr_IRQEvent::WaitCond() { return eventSem.WaitCond(); }
#include <cassert> #include "Lab7.h" using namespace lab7; int main() { std::vector<int> v1; v1.push_back(1); v1.push_back(2); v1.push_back(3); std::vector<char> v2; v2.push_back('a'); v2.push_back('b'); v2.push_back('c'); std::vector<int> v3; v3.push_back(4); v3.push_back(5); v3.push_back(6); std::map<char, int> m1; m1['a'] = 1; m1['b'] = 2; m1['c'] = 3; std::map<char, int> m2; m2['d'] = 4; m2['e'] = 5; m2['f'] = 6; std::map<int, char> m = lab7::ConvertVectorsToMap(v1, v2); { std::map<int, char>::const_iterator it = m.begin(); assert(it->first == 1); assert(it->second == 'a'); it++; assert(it->first == 2); assert(it->second == 'b'); it++; assert(it->first == 3); assert(it->second == 'c'); } std::vector<char> keys = lab7::GetKeys(m1); { std::vector<char>::const_iterator it = keys.begin(); assert(*it == 'a'); it++; assert(*it == 'b'); it++; assert(*it == 'c'); } std::vector<int> values = lab7::GetValues(m1); { std::vector<int>::const_iterator it = values.begin(); assert(*it == 1); it++; assert(*it == 2); it++; assert(*it == 3); } std::vector<int> reversedV1 = lab7::Reverse(v1); { assert(reversedV1[0] == v1[2]); assert(reversedV1[1] == v1[1]); assert(reversedV1[2] == v1[0]); } std::vector<int> combinedVector = v1 + v3; { assert(combinedVector.size() == 6); assert(combinedVector[0] == 1); assert(combinedVector[1] == 2); assert(combinedVector[2] == 3); assert(combinedVector[3] == 4); assert(combinedVector[4] == 5); assert(combinedVector[5] == 6); } std::map<char, int> combinedMap = m1 + m2; { std::map<char, int>::const_iterator it = combinedMap.begin(); assert(combinedMap.size() == 6); assert(it->first == 'a'); assert(it->second == 1); it++; assert(it->first == 'b'); assert(it->second == 2); it++; assert(it->first == 'c'); assert(it->second == 3); it++; assert(it->first == 'd'); assert(it->second == 4); it++; assert(it->first == 'e'); assert(it->second == 5); it++; assert(it->first == 'f'); assert(it->second == 6); } std::cout << v1 << std::endl; std::cout << m1 << std::endl; std::vector<int> v4; v4.push_back(1); v4.push_back(2); v4.push_back(2); std::vector<int> v5; std::vector<int> v6 = v4 + v5; std::map<char, int> m4; m4['a'] = 1; m4['b'] = 2; m4['c'] = 3; std::map<char, int> m5; m5['a'] = 1; m5['b'] = 2; m5['c'] = 3; std::map<char, int> m6 = m4 + m5; return 0; }
#include <atomic> #include <iostream> #include "gtest/gtest.h" void atom() { // instantiation is guaranteed to to atomic std::atomic<int> ai(0); // all operation are atomic ai = 10; // LIMITED to read operation, between read and << // the value could be changed. // cout uses pass-by-value, no affect though. std::cout << ai << std::endl; ++ai; --ai; // atomic object can't be copied, for good reason: // in order to be atomic, compiler needs to read ai // and write i, both are atomic, failed. // auto i = ai; } void vol() { // volatile does not guarantee anything volatile int vi {1}; vi = 10; std::cout << vi << std::endl; ++vi; --vi; // volatile is used to tell compiler // special memory is used, usually memory-mapped I/O: // display, printer.. auto y = vi; y = vi; std::cout << &y<< std::endl; } void sequence() { // default atomic sequence consistency: // no code precedes a write of std::atomic may // be executed before it std::atomic<bool> flag(false); auto i = 42; flag = true; // i is assured to be 42 std::cout << i << std::endl; } TEST(AtomicVolatileTest, SomeTest) { atom(); vol(); } int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
/* * Copyright (c) 2019, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. */ #define WIFI 2 #if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \ (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID)) #error [NOT_SUPPORTED] No network configuration found for this target. #endif #ifndef MBED_CONF_APP_ECHO_SERVER_ADDR #error [NOT_SUPPORTED] Requires echo-server-discard-port parameter from mbed_app.json #endif #include "mbed.h" #include "greentea-client/test_env.h" #include "unity/unity.h" #include "utest.h" #include "utest/utest_stack_trace.h" #include "tls_tests.h" #if defined(MBEDTLS_SSL_CLI_C) || defined(DOXYGEN_ONLY) using namespace utest::v1; namespace { Timer tc_bucket; // Timer to limit a test cases run time } #if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED mbed_stats_socket_t tls_stats[MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT]; #endif char tls_global::rx_buffer[RX_BUFF_SIZE]; char tls_global::tx_buffer[TX_BUFF_SIZE]; const char *tls_global::cert = \ "-----BEGIN CERTIFICATE-----\n" "MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" "MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" "DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" "SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" "GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" "AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" "q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" "SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" "Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" "a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" "/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" "AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" "CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" "bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" "c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" "VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" "ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" "MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" "Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" "AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" "uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" "wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" "X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" "PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" "KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" "-----END CERTIFICATE-----\n"; void drop_bad_packets(TLSSocket &sock, int orig_timeout) { nsapi_error_t err; sock.set_timeout(0); while (true) { err = sock.recv(NULL, 0); if (err == NSAPI_ERROR_WOULD_BLOCK) { break; } } sock.set_timeout(orig_timeout); } static void _ifup() { NetworkInterface *net = NetworkInterface::get_default_instance(); nsapi_error_t err = net->connect(); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); printf("MBED: TLSClient IP address is '%s'\n", net->get_ip_address()); } static void _ifdown() { NetworkInterface::get_default_instance()->disconnect(); printf("MBED: ifdown\n"); } nsapi_error_t tlssocket_connect_to_srv(TLSSocket &sock, uint16_t port) { SocketAddress tls_addr; NetworkInterface::get_default_instance()->gethostbyname(MBED_CONF_APP_ECHO_SERVER_ADDR, &tls_addr); tls_addr.set_port(port); printf("MBED: Server '%s', port %d\n", tls_addr.get_ip_address(), tls_addr.get_port()); nsapi_error_t err = sock.set_root_ca_cert(tls_global::cert); if (err != NSAPI_ERROR_OK) { printf("Error from sock.set_root_ca_cert: %d\n", err); return err; } err = sock.open(NetworkInterface::get_default_instance()); if (err != NSAPI_ERROR_OK) { printf("Error from sock.open: %d\n", err); return err; } err = sock.connect(tls_addr); if (err != NSAPI_ERROR_OK) { printf("Error from sock.connect: %d\n", err); return err; } return NSAPI_ERROR_OK; } nsapi_error_t tlssocket_connect_to_echo_srv(TLSSocket &sock) { return tlssocket_connect_to_srv(sock, MBED_CONF_APP_ECHO_SERVER_PORT_TLS); } nsapi_error_t tlssocket_connect_to_discard_srv(TLSSocket &sock) { return tlssocket_connect_to_srv(sock, MBED_CONF_APP_ECHO_SERVER_DISCARD_PORT_TLS); } void fill_tx_buffer_ascii(char *buff, size_t len) { for (size_t i = 0; i < len; ++i) { buff[i] = (rand() % 43) + '0'; } } int split2half_rmng_tls_test_time() { return (tls_global::TESTS_TIMEOUT - tc_bucket.read()) / 2; } #if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED int fetch_stats() { return SocketStats::mbed_stats_socket_get_each(&tls_stats[0], MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT); } #endif // Test setup utest::v1::status_t greentea_setup(const size_t number_of_cases) { GREENTEA_SETUP(tls_global::TESTS_TIMEOUT, "default_auto"); _ifup(); tc_bucket.start(); return greentea_test_setup_handler(number_of_cases); } void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure) { tc_bucket.stop(); _ifdown(); return greentea_test_teardown_handler(passed, failed, failure); } Case cases[] = { Case("TLSSOCKET_ECHOTEST", TLSSOCKET_ECHOTEST), Case("TLSSOCKET_ECHOTEST_NONBLOCK", TLSSOCKET_ECHOTEST_NONBLOCK), Case("TLSSOCKET_CONNECT_INVALID", TLSSOCKET_CONNECT_INVALID), Case("TLSSOCKET_ECHOTEST_BURST", TLSSOCKET_ECHOTEST_BURST), Case("TLSSOCKET_ECHOTEST_BURST_NONBLOCK", TLSSOCKET_ECHOTEST_BURST_NONBLOCK), Case("TLSSOCKET_RECV_TIMEOUT", TLSSOCKET_RECV_TIMEOUT), Case("TLSSOCKET_ENDPOINT_CLOSE", TLSSOCKET_ENDPOINT_CLOSE), Case("TLSSOCKET_HANDSHAKE_INVALID", TLSSOCKET_HANDSHAKE_INVALID), Case("TLSSOCKET_OPEN_TWICE", TLSSOCKET_OPEN_TWICE), Case("TLSSOCKET_OPEN_LIMIT", TLSSOCKET_OPEN_LIMIT), Case("TLSSOCKET_OPEN_DESTRUCT", TLSSOCKET_OPEN_DESTRUCT), Case("TLSSOCKET_SEND_UNCONNECTED", TLSSOCKET_SEND_UNCONNECTED), Case("TLSSOCKET_SEND_CLOSED", TLSSOCKET_SEND_CLOSED), Case("TLSSOCKET_SEND_REPEAT", TLSSOCKET_SEND_REPEAT), Case("TLSSOCKET_SEND_TIMEOUT", TLSSOCKET_SEND_TIMEOUT), Case("TLSSOCKET_NO_CERT", TLSSOCKET_NO_CERT), // Temporarily removing this test, as TLS library consumes too much memory // and we see frequent memory allocation failures on architectures with less // RAM such as DISCO_L475VG_IOT1A and NUCLEO_F207ZG (both have 128 kB RAM) // This test also fails for IAR, due to wrong heap configuration in the linker // script - see https://github.com/ARMmbed/mbed-os/issues/8306 // Case("TLSSOCKET_SIMULTANEOUS", TLSSOCKET_SIMULTANEOUS) }; Specification specification(greentea_setup, cases, greentea_teardown, greentea_continue_handlers); int retval; void run_test(void) { retval = !Harness::run(specification); } static unsigned char stack_mem[8192]; int main() { Thread *th = new Thread(osPriorityNormal, 8192, stack_mem, "tls_gt_thread"); th->start(callback(run_test)); th->join(); return retval; } #else #error [NOT_SUPPORTED] This device does not support SSL library #endif // defined(MBEDTLS_SSL_CLI_C) || defined(DOXYGEN_ONLY)
/*++ Module Name: theory_str_mc.cpp Abstract: Model Construction for String Theory Plugin Author: Murphy Berzish and Yunhui Zheng Revision History: --*/ #include "ast/ast_smt2_pp.h" #include "smt/smt_context.h" #include "smt/theory_str.h" #include "smt/smt_model_generator.h" #include "ast/ast_pp.h" #include "ast/ast_ll_pp.h" #include<list> #include<algorithm> #include "smt/theory_seq_empty.h" #include "smt/theory_arith.h" #include "ast/ast_util.h" #include "ast/rewriter/seq_rewriter.h" #include "ast/rewriter/expr_replacer.h" #include "smt_kernel.h" #include "model/model_smt2_pp.h" namespace smt { /* * Use the current model in the arithmetic solver to get the length of a term. * Returns true if this could be done, placing result in 'termLen', or false otherwise. * Works like get_len_value() except uses arithmetic solver model instead of EQCs. */ bool theory_str::fixed_length_get_len_value(expr * e, rational & val) { ast_manager & m = get_manager(); rational val1; expr_ref len(m), len_val(m); expr* e1 = nullptr, *e2 = nullptr; expr_ref_vector todo(m); todo.push_back(e); val.reset(); while (!todo.empty()) { expr* c = todo.back(); todo.pop_back(); zstring tmp; if (u.str.is_concat(c, e1, e2)) { todo.push_back(e1); todo.push_back(e2); } else if (u.str.is_string(c, tmp)) { unsigned int sl = tmp.length(); val += rational(sl); } else { len = mk_strlen(c); arith_value v(get_manager()); v.init(&get_context()); if (v.get_value(len, val1)) { val += val1; } else { return false; } } } return val.is_int(); } bool theory_str::fixed_length_reduce_suffix(smt::kernel & subsolver, expr_ref f, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); expr * full = nullptr; expr * suff = nullptr; VERIFY(u.str.is_suffix(f, suff, full)); expr_ref haystack(full, m); expr_ref needle(suff, m); ptr_vector<expr> full_chars, suff_chars; if (!fixed_length_reduce_string_term(subsolver, haystack, full_chars, cex) || !fixed_length_reduce_string_term(subsolver, needle, suff_chars, cex)) { return false; } if (suff_chars.size() == 0) { // all strings endwith the empty one return true; } if (full_chars.size() == 0 && suff_chars.size() > 0) { // the empty string doesn't "endwith" any non-empty string cex = m.mk_or(m.mk_not(f), ctx.mk_eq_atom(mk_strlen(suff), mk_int(0)), m_autil.mk_ge(mk_strlen(full), mk_int(0))); th_rewriter m_rw(m); m_rw(cex); return false; } if (full_chars.size() < suff_chars.size()) { // a string can't endwith a longer one // X startswith Y -> len(X) >= len(Y) expr_ref minus_one(m_autil.mk_numeral(rational::minus_one(), true), m); expr_ref zero(m_autil.mk_numeral(rational::zero(), true), m); expr_ref lens(m_autil.mk_add(mk_strlen(full), m_autil.mk_mul(minus_one, mk_strlen(suff))), m); cex = m.mk_or(m.mk_not(f), m_autil.mk_ge(lens, zero)); th_rewriter m_rw(m); m_rw(cex); return false; } expr_ref_vector branch(sub_m); for (unsigned j = 0; j < suff_chars.size(); ++j) { // full[j] == suff[j] expr_ref cLHS(full_chars.get(full_chars.size() - j - 1), sub_m); expr_ref cRHS(suff_chars.get(suff_chars.size() - j - 1), sub_m); expr_ref _e(sub_m.mk_eq(cLHS, cRHS), sub_m); branch.push_back(_e); } expr_ref final_diseq(mk_and(branch), sub_m); fixed_length_assumptions.push_back(final_diseq); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(final_diseq, std::make_tuple(PFUN, f, f)); return true; } bool theory_str::fixed_length_reduce_negative_suffix(smt::kernel & subsolver, expr_ref f, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); expr * full = nullptr; expr * suff = nullptr; VERIFY(u.str.is_suffix(f, suff, full)); expr_ref haystack(full, m); expr_ref needle(suff, m); ptr_vector<expr> full_chars, suff_chars; if (!fixed_length_reduce_string_term(subsolver, haystack, full_chars, cex) || !fixed_length_reduce_string_term(subsolver, needle, suff_chars, cex)) { return false; } if (suff_chars.size() == 0) { // all strings endwith the empty one cex = m.mk_or(m.mk_not(f), m.mk_not(ctx.mk_eq_atom(mk_strlen(suff), mk_int(0)))); th_rewriter m_rw(m); m_rw(cex); return false; } if (full_chars.size() == 0 && suff_chars.size() > 0) { // the empty string doesn't "endwith" any non-empty string return true; } if (full_chars.size() < suff_chars.size()) { // a string can't endwith a longer one // X startswith Y -> len(X) >= len(Y) return true; } expr_ref_vector branch(sub_m); for (unsigned j = 0; j < suff_chars.size(); ++j) { // full[j] == suff[j] expr_ref cLHS(full_chars.get(full_chars.size() - j - 1), sub_m); expr_ref cRHS(suff_chars.get(suff_chars.size() - j - 1), sub_m); expr_ref _e(sub_m.mk_eq(cLHS, cRHS), sub_m); branch.push_back(_e); } expr_ref final_diseq(mk_not(sub_m, mk_and(branch)), sub_m); fixed_length_assumptions.push_back(final_diseq); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(final_diseq, std::make_tuple(NFUN, f, f)); return true; } bool theory_str::fixed_length_reduce_prefix(smt::kernel & subsolver, expr_ref f, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); expr * full = nullptr; expr * pref = nullptr; VERIFY(u.str.is_prefix(f, pref, full)); expr_ref haystack(full, m); expr_ref needle(pref, m); ptr_vector<expr> full_chars, pref_chars; if (!fixed_length_reduce_string_term(subsolver, haystack, full_chars, cex) || !fixed_length_reduce_string_term(subsolver, needle, pref_chars, cex)) { return false; } if (pref_chars.size() == 0) { // all strings startwith the empty one return true; } if (full_chars.size() == 0 && pref_chars.size() > 0) { // the empty string doesn't "stratwith" any non-empty string cex = m.mk_or(m.mk_not(f), ctx.mk_eq_atom(mk_strlen(pref), mk_int(0)), m_autil.mk_ge(mk_strlen(full), mk_int(0))); th_rewriter m_rw(m); m_rw(cex); return false; } if (full_chars.size() < pref_chars.size()) { // a string can't startwith a longer one // X startswith Y -> len(X) >= len(Y) expr_ref minus_one(m_autil.mk_numeral(rational::minus_one(), true), m); expr_ref zero(m_autil.mk_numeral(rational::zero(), true), m); expr_ref lens(m_autil.mk_add(mk_strlen(full), m_autil.mk_mul(minus_one, mk_strlen(pref))), m); cex = m.mk_or(m.mk_not(f), m_autil.mk_ge(lens, zero)); th_rewriter m_rw(m); m_rw(cex); return false; } expr_ref_vector branch(m); for (unsigned j = 0; j < pref_chars.size(); ++j) { // full[j] == pref[j] expr_ref cLHS(full_chars.get(j), sub_m); expr_ref cRHS(pref_chars.get(j), sub_m); expr_ref _e(sub_m.mk_eq(cLHS, cRHS), sub_m); branch.push_back(_e); } expr_ref final_diseq(mk_and(branch), sub_m); fixed_length_assumptions.push_back(final_diseq); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(final_diseq, std::make_tuple(PFUN, f, f)); return true; } bool theory_str::fixed_length_reduce_negative_prefix(smt::kernel & subsolver, expr_ref f, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); expr * pref = nullptr, *full = nullptr; VERIFY(u.str.is_prefix(f, pref, full)); expr_ref haystack(full, m); expr_ref needle(pref, m); ptr_vector<expr> full_chars, pref_chars; if (!fixed_length_reduce_string_term(subsolver, haystack, full_chars, cex) || !fixed_length_reduce_string_term(subsolver, needle, pref_chars, cex)) { return false; } if (pref_chars.size() == 0) { // all strings startwith the empty one cex = m.mk_or(m.mk_not(f), m.mk_not(ctx.mk_eq_atom(mk_strlen(pref), mk_int(0)))); th_rewriter m_rw(m); m_rw(cex); return false; } if (full_chars.size() == 0 && pref_chars.size() > 0) { // the empty string doesn't "stratwith" any non-empty string return true; } if (full_chars.size() < pref_chars.size()) { // a string can't startwith a longer one // X startswith Y -> len(X) >= len(Y) return true; } expr_ref_vector branch(m); for (unsigned j = 0; j < pref_chars.size(); ++j) { // full[j] == pref[j] expr_ref cLHS(full_chars.get(j), sub_m); expr_ref cRHS(pref_chars.get(j), sub_m); expr_ref _e(sub_m.mk_eq(cLHS, cRHS), sub_m); branch.push_back(_e); } expr_ref final_diseq(mk_not(sub_m, mk_and(branch)), sub_m); fixed_length_assumptions.push_back(final_diseq); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(final_diseq, std::make_tuple(NFUN, f, f)); return true; } bool theory_str::fixed_length_reduce_contains(smt::kernel & subsolver, expr_ref f, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); expr * full = nullptr; expr * small = nullptr; VERIFY(u.str.is_contains(f, full, small)); expr_ref haystack(full, m); expr_ref needle(small, m); ptr_vector<expr> haystack_chars, needle_chars; if (!fixed_length_reduce_string_term(subsolver, haystack, haystack_chars, cex) || !fixed_length_reduce_string_term(subsolver, needle, needle_chars, cex)) { return false; } if (needle_chars.size() == 0) { // all strings "contain" the empty one return true; } if (haystack_chars.size() == 0 && needle_chars.size() > 0) { // the empty string doesn't "contain" any non-empty string cex = m.mk_or(m.mk_not(f), ctx.mk_eq_atom(mk_strlen(needle), mk_int(0)), m_autil.mk_ge(mk_strlen(haystack), mk_int(0))); th_rewriter m_rw(m); m_rw(cex); return false; } if (needle_chars.size() > haystack_chars.size()) { // a string can't contain a longer one // X contains Y -> len(X) >= len(Y) expr_ref minus_one(m_autil.mk_numeral(rational::minus_one(), true), m); expr_ref zero(m_autil.mk_numeral(rational::zero(), true), m); expr_ref lens(m_autil.mk_add(mk_strlen(haystack), m_autil.mk_mul(minus_one, mk_strlen(needle))), m); cex = m.mk_or(m.mk_not(f), m_autil.mk_ge(lens, zero)); th_rewriter m_rw(m); m_rw(cex); return false; } // find all positions at which `needle` could occur in `haystack` expr_ref_vector branches(m); for (unsigned i = 0; i <= (haystack_chars.size() - needle_chars.size()); ++i) { // i defines the offset into haystack_chars expr_ref_vector branch(m); for (unsigned j = 0; j < needle_chars.size(); ++j) { // needle[j] == haystack[i+j] ENSURE(i+j < haystack_chars.size()); expr_ref cLHS(needle_chars.get(j), sub_m); expr_ref cRHS(haystack_chars.get(i+j), sub_m); expr_ref _e(sub_m.mk_eq(cLHS, cRHS), sub_m); branch.push_back(_e); } branches.push_back(mk_and(branch)); } expr_ref final_diseq(mk_or(branches), sub_m); fixed_length_assumptions.push_back(final_diseq); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(final_diseq, std::make_tuple(PFUN, f, f)); return true; } bool theory_str::fixed_length_reduce_negative_contains(smt::kernel & subsolver, expr_ref f, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); expr * small = nullptr, *full = nullptr; VERIFY(u.str.is_contains(f, full, small)); expr_ref haystack(full, m); expr_ref needle(small, m); ptr_vector<expr> haystack_chars, needle_chars; if (!fixed_length_reduce_string_term(subsolver, haystack, haystack_chars, cex) || !fixed_length_reduce_string_term(subsolver, needle, needle_chars, cex)) { return false; } if (needle_chars.size() == 0) { // all strings "contain" the empty one cex = m.mk_or(m.mk_not(f), m.mk_not(ctx.mk_eq_atom(mk_strlen(needle), mk_int(0)))); ctx.get_rewriter()(cex); return false; } if (haystack_chars.size() == 0 && needle_chars.size() > 0) { // the empty string doesn't "contain" any non-empty string return true; } if (needle_chars.size() > haystack_chars.size()) { // a string can't contain a longer one // X contains Y -> len(X) >= len(Y) return true; } // find all positions at which `needle` could occur in `haystack` expr_ref_vector branches(m); for (unsigned i = 0; i <= (haystack_chars.size() - needle_chars.size()); ++i) { // i defines the offset into haystack_chars expr_ref_vector branch(m); for (unsigned j = 0; j < needle_chars.size(); ++j) { // needle[j] == haystack[i+j] ENSURE(i+j < haystack_chars.size()); expr_ref cLHS(needle_chars.get(j), sub_m); expr_ref cRHS(haystack_chars.get(i+j), sub_m); expr_ref _e(sub_m.mk_eq(cLHS, cRHS), sub_m); branch.push_back(_e); } branches.push_back(mk_and(branch)); } expr_ref final_diseq(mk_not(sub_m, mk_or(branches)), sub_m); fixed_length_assumptions.push_back(final_diseq); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(final_diseq, std::make_tuple(NFUN, f, f)); return true; } static inline void add_next(u_map<expr*>& next, expr_ref_vector& trail, unsigned idx, expr* cond, ast_manager & m) { expr* acc; if (!m.is_true(cond) && next.find(idx, acc)) { expr* args[2] = { cond, acc }; cond = mk_or(m, 2, args); } trail.push_back(cond); next.insert(idx, cond); } bool theory_str::fixed_length_reduce_regex_membership(smt::kernel & subsolver, expr_ref f, expr_ref & cex, bool polarity) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); context & sub_ctx = subsolver.get_context(); expr * str = nullptr, *re = nullptr; VERIFY(u.str.is_in_re(f, str, re)); // TODO reuse some of the automaton framework from theory_str_regex eautomaton * aut = m_mk_aut(re); aut->compress(); ptr_vector<expr> str_chars; if (!fixed_length_reduce_string_term(subsolver, str, str_chars, cex)) { return false; } if (str_chars.empty()) { // check 0-length solution bool zero_solution = false; unsigned initial_state = aut->init(); if (aut->is_final_state(initial_state)) { zero_solution = true; } else { unsigned_vector eps_states; aut->get_epsilon_closure(initial_state, eps_states); for (unsigned state : eps_states) { if (aut->is_final_state(state)) { zero_solution = true; break; } } } if (!zero_solution && polarity) { TRACE("str_fl", tout << "contradiction: regex has no zero-length solutions, but our string must be a solution" << std::endl;); cex = m.mk_or(m.mk_not(f), m.mk_not(ctx.mk_eq_atom(mk_strlen(str), mk_int(0)))); ctx.get_rewriter()(cex); return false; } else if (zero_solution && !polarity) { TRACE("str_fl", tout << "contradiction: regex has zero-length solutions, but our string must not be a solution" << std::endl;); cex = m.mk_or(f, m.mk_not(ctx.mk_eq_atom(mk_strlen(str), mk_int(0)))); ctx.get_rewriter()(cex); return false; } else { TRACE("str_fl", tout << "regex constraint satisfied without asserting constraints to subsolver" << std::endl;); return true; } } else { expr_ref_vector trail(m); u_map<expr*> maps[2]; bool select_map = false; expr_ref cond(m); eautomaton::moves mvs; maps[0].insert(aut->init(), m.mk_true()); // is_accepted(a, aut) & some state in frontier is final. for (auto& ch : str_chars) { u_map<expr*>& frontier = maps[select_map]; u_map<expr*>& next = maps[!select_map]; select_map = !select_map; next.reset(); u_map<expr*>::iterator it = frontier.begin(), end = frontier.end(); for (; it != end; ++it) { mvs.reset(); unsigned state = it->m_key; expr* acc = it->m_value; aut->get_moves_from(state, mvs, false); for (eautomaton::move& mv : mvs) { SASSERT(mv.t()); if (mv.t()->is_char() && m.is_value(mv.t()->get_char()) && m.is_value(ch)) { if (mv.t()->get_char() == ch) { add_next(next, trail, mv.dst(), acc, sub_m); } else { continue; } } else { cond = mv.t()->accept(ch); if (m.is_false(cond)) { continue; } if (m.is_true(cond)) { add_next(next, trail, mv.dst(), acc, sub_m); continue; } expr* args[2] = { cond, acc }; cond = mk_and(m, 2, args); add_next(next, trail, mv.dst(), cond, sub_m); } } } } u_map<expr*> const& frontier = maps[select_map]; expr_ref_vector ors(sub_m); for (auto const& kv : frontier) { unsigned_vector states; bool has_final = false; aut->get_epsilon_closure(kv.m_key, states); for (unsigned i = 0; i < states.size() && !has_final; ++i) { has_final = aut->is_final_state(states[i]); } if (has_final) { ors.push_back(kv.m_value); } } expr_ref result(mk_or(ors), sub_m); sub_ctx.get_rewriter()(result); TRACE("str_fl", tout << "regex path constraint: " << mk_pp(result, sub_m) << std::endl;); if (sub_m.is_false(result)) { // There are no solutions of that length in the automaton. // If the membership constraint is true, we assert a conflict clause. // If the membership constraint is false, we ignore the constraint. if (polarity) { // Decompose `str` into its components if it is a concatenation of terms. // This fixes cases where the length of S in (S in RE) might be correct // if the lengths of components of S are assigned in a different way. expr_ref_vector str_terms(m); expr_ref_vector str_terms_eq_len(m); str_terms.push_back(str); while (!str_terms.empty()) { expr* str_term = str_terms.back(); str_terms.pop_back(); expr* arg0; expr* arg1; if (u.str.is_concat(str_term, arg0, arg1)) { str_terms.push_back(arg0); str_terms.push_back(arg1); } else { rational termLen; if (fixed_length_get_len_value(str_term, termLen)) { str_terms_eq_len.push_back(ctx.mk_eq_atom(mk_strlen(str_term), mk_int(termLen))); } else { // this is strange, since we knew the length of `str` in order to get here cex = expr_ref(m_autil.mk_ge(mk_strlen(str_term), mk_int(0)), m); return false; } } } cex = m.mk_or(m.mk_not(f), m.mk_not(mk_and(str_terms_eq_len))); ctx.get_rewriter()(cex); return false; } else { TRACE("str_fl", tout << "regex constraint satisfied without asserting constraints to subsolver" << std::endl;); return true; } } else { if (polarity) { fixed_length_assumptions.push_back(result); fixed_length_lesson.insert(result, std::make_tuple(PFUN, f, f)); } else { fixed_length_assumptions.push_back(sub_m.mk_not(result)); fixed_length_lesson.insert(sub_m.mk_not(result), std::make_tuple(NFUN, f, f)); } return true; } } } /* * Expressions in the vector eqc_chars exist only in the subsolver. * If this method returns false, a conflict clause is returned in cex; * this conflict clause exists in the main solver. */ bool theory_str::fixed_length_reduce_string_term(smt::kernel & subsolver, expr * term, ptr_vector<expr> & eqc_chars, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); bv_util bv(m); sort * bv8_sort = bv.mk_sort(8); expr * arg0; expr * arg1; expr * arg2; zstring strConst; if (u.str.is_string(term, strConst)) { for (unsigned i = 0; i < strConst.length(); ++i) { expr_ref chTerm(bitvector_character_constants.get(strConst[i]), m); eqc_chars.push_back(chTerm); } } else if (to_app(term)->get_num_args() == 0 && !u.str.is_string(term)) { // this is a variable; get its length and create/reuse character terms if (!var_to_char_subterm_map.contains(term)) { rational varLen_value; bool var_hasLen = fixed_length_get_len_value(term, varLen_value); if (!var_hasLen || varLen_value.is_neg()) { TRACE("str_fl", tout << "variable " << mk_pp(term, m) << " has no length assignment or impossible length assignment - asserting conflict axiom" << std::endl;); cex = expr_ref(m_autil.mk_ge(mk_strlen(term), mk_int(0)), m); return false; } TRACE("str_fl", tout << "creating character terms for variable " << mk_pp(term, m) << ", length = " << varLen_value << std::endl;); ptr_vector<expr> new_chars; for (rational i = rational::zero(); i < varLen_value; ++i) { // TODO we can probably name these better for the sake of debugging expr_ref ch(mk_fresh_const("char", bv8_sort), m); new_chars.push_back(ch); fixed_length_subterm_trail.push_back(ch); } var_to_char_subterm_map.insert(term, new_chars); fixed_length_used_len_terms.insert(term, varLen_value); } var_to_char_subterm_map.find(term, eqc_chars); } else if (u.str.is_concat(term, arg0, arg1)) { expr_ref first(arg0, sub_m); expr_ref second(arg1, sub_m); ptr_vector<expr> chars0, chars1; if (!fixed_length_reduce_string_term(subsolver, first, chars0, cex) || !fixed_length_reduce_string_term(subsolver, second, chars1, cex)) { return false; } eqc_chars.append(chars0); eqc_chars.append(chars1); } else if (u.str.is_extract(term, arg0, arg1, arg2)) { // (str.substr Base Pos Len) expr_ref first(arg0, sub_m); expr_ref second(arg1, sub_m); expr_ref third(arg2, sub_m); ptr_vector<expr> base_chars; if (!fixed_length_reduce_string_term(subsolver, first, base_chars, cex)) { return false; } arith_value v(m); v.init(&get_context()); rational pos, len; bool pos_exists = v.get_value(arg1, pos); bool len_exists = v.get_value(arg2, len); if (!pos_exists) { cex = expr_ref(m.mk_or(m_autil.mk_ge(arg1, mk_int(0)), m_autil.mk_le(arg1, mk_int(0))), m); return false; } if (!len_exists) { cex = expr_ref(m.mk_or(m_autil.mk_ge(arg2, mk_int(0)), m_autil.mk_le(arg2, mk_int(0))), m); return false; } TRACE("str_fl", tout << "reduce substring term: base=" << mk_pp(term, m) << " (length="<<base_chars.size()<<"), pos=" << pos.to_string() << ", len=" << len.to_string() << std::endl;); // Case 1: pos < 0 or pos >= strlen(base) or len < 0 // ==> (Substr ...) = "" if (pos.is_neg() || pos >= rational(base_chars.size()) || len.is_neg()) { eqc_chars.reset(); return true; } else if (!pos.is_unsigned() || !len.is_unsigned()) { return false; } else { unsigned _pos = pos.get_unsigned(); unsigned _len = len.get_unsigned(); if (_pos + _len < _pos) return false; if (_pos + _len >= base_chars.size()) { // take as many characters as possible up to the end of base_chars for (unsigned i = _pos; i < base_chars.size(); ++i) { eqc_chars.push_back(base_chars.get(i)); } } else { for (unsigned i = _pos; i < _pos + _len; ++i) { eqc_chars.push_back(base_chars.get(i)); } } } } else if (u.str.is_at(term, arg0, arg1)) { // (str.at Base Pos) expr_ref base(arg0, sub_m); expr_ref pos(arg1, sub_m); ptr_vector<expr> base_chars; if (!fixed_length_reduce_string_term(subsolver, base, base_chars, cex)) { return false; } arith_value v(m); v.init(&get_context()); rational pos_value; bool pos_exists = v.get_value(pos, pos_value); if (!pos_exists) { cex = m.mk_or(m_autil.mk_ge(pos, mk_int(0)), m_autil.mk_le(pos, mk_int(0))); return false; } TRACE("str_fl", tout << "reduce str.at: base=" << mk_pp(base, m) << ", pos=" << pos_value.to_string() << std::endl;); if (pos_value.is_neg() || pos_value >= rational(base_chars.size())) { // return the empty string eqc_chars.reset(); } else if (!pos_value.is_unsigned()) { return false; } else { eqc_chars.push_back(base_chars.get(pos_value.get_unsigned())); } return true; } else if (u.str.is_itos(term, arg0)) { expr_ref i(arg0, m); arith_value v(m); v.init(&get_context()); rational iValue; bool iValue_exists = v.get_value(i, iValue); if (!iValue_exists) { cex = expr_ref(m.mk_or(m_autil.mk_ge(arg0, mk_int(0)), m_autil.mk_le(arg0, mk_int(0))), m); return false; } rational termLen; bool termLen_exists = v.get_value(mk_strlen(term), termLen); if(!termLen_exists) { cex = expr_ref(m.mk_or(m_autil.mk_ge(mk_strlen(term), mk_int(0)), m_autil.mk_le(mk_strlen(term), mk_int(0))), m); return false; } TRACE("str_fl", tout << "reduce int.to.str: n=" << iValue << std::endl;); if (iValue.is_neg()) { if (!termLen.is_zero()) { // conflict cex = expr_ref(m.mk_not(m.mk_and(m_autil.mk_le(arg0, mk_int(-1)), m.mk_not(mk_strlen(term)))), m); return false; } // return the empty string eqc_chars.reset(); return true; } else { if (termLen != iValue.get_num_decimal()) { // conflict cex = expr_ref(m.mk_not(m.mk_and(get_context().mk_eq_atom(mk_strlen(term), mk_int(termLen)), get_context().mk_eq_atom(arg0, mk_int(iValue)))), m); return false; } // convert iValue to a constant zstring iValue_str(iValue.to_string()); for (unsigned idx = 0; idx < iValue_str.length(); ++idx) { expr_ref chTerm(bitvector_character_constants.get(iValue_str[idx]), sub_m); eqc_chars.push_back(chTerm); } return true; } } else { TRACE("str_fl", tout << "string term " << mk_pp(term, m) << " handled as uninterpreted function" << std::endl;); if (!uninterpreted_to_char_subterm_map.contains(term)) { rational ufLen_value; bool uf_hasLen = fixed_length_get_len_value(term, ufLen_value); if (!uf_hasLen || ufLen_value.is_neg()) { TRACE("str_fl", tout << "uninterpreted function " << mk_pp(term, m) << " has no length assignment or impossible length assignment - asserting conflict axiom" << std::endl;); cex = expr_ref(m_autil.mk_ge(mk_strlen(term), mk_int(0)), m); return false; } TRACE("str_fl", tout << "creating character terms for uninterpreted function " << mk_pp(term, m) << ", length = " << ufLen_value << std::endl;); ptr_vector<expr> new_chars; for (rational i = rational::zero(); i < ufLen_value; ++i) { expr_ref ch(mk_fresh_const("char", bv8_sort), m); new_chars.push_back(ch); fixed_length_subterm_trail.push_back(ch); } uninterpreted_to_char_subterm_map.insert(term, new_chars); fixed_length_used_len_terms.insert(term, ufLen_value); } uninterpreted_to_char_subterm_map.find(term, eqc_chars); } return true; } bool theory_str::fixed_length_reduce_eq(smt::kernel & subsolver, expr_ref lhs, expr_ref rhs, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); ptr_vector<expr> lhs_chars, rhs_chars; if (!fixed_length_reduce_string_term(subsolver, lhs, lhs_chars, cex) || !fixed_length_reduce_string_term(subsolver, rhs, rhs_chars, cex)) { return false; } if (lhs_chars.size() != rhs_chars.size()) { TRACE("str_fl", tout << "length information inconsistent: " << mk_pp(lhs, m) << " has " << lhs_chars.size() << " chars, " << mk_pp(rhs, m) << " has " << rhs_chars.size() << " chars" << std::endl;); // equal strings ought to have equal lengths cex = m.mk_or(m.mk_not(ctx.mk_eq_atom(lhs, rhs)), ctx.mk_eq_atom(mk_strlen(lhs), mk_strlen(rhs))); return false; } for (unsigned i = 0; i < lhs_chars.size(); ++i) { expr_ref cLHS(lhs_chars.get(i), sub_m); expr_ref cRHS(rhs_chars.get(i), sub_m); expr_ref _e(sub_m.mk_eq(cLHS, cRHS), sub_m); fixed_length_assumptions.push_back(_e); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(_e, std::make_tuple(rational(i), lhs, rhs)); } return true; } bool theory_str::fixed_length_reduce_diseq(smt::kernel & subsolver, expr_ref lhs, expr_ref rhs, expr_ref & cex) { ast_manager & m = get_manager(); ast_manager & sub_m = subsolver.m(); // we do generation before this check to make sure that // variables which only appear in disequalities show up in the model rational lhsLen, rhsLen; bool lhsLen_exists = fixed_length_get_len_value(lhs, lhsLen); bool rhsLen_exists = fixed_length_get_len_value(rhs, rhsLen); if (!lhsLen_exists) { cex = m_autil.mk_ge(mk_strlen(lhs), mk_int(0)); return false; } if (!rhsLen_exists) { cex = m_autil.mk_ge(mk_strlen(rhs), mk_int(0)); return false; } ptr_vector<expr> lhs_chars, rhs_chars; if (!fixed_length_reduce_string_term(subsolver, lhs, lhs_chars, cex) || !fixed_length_reduce_string_term(subsolver, rhs, rhs_chars, cex)) { return false; } if (lhsLen != rhsLen) { TRACE("str", tout << "skip disequality: len(lhs) = " << lhsLen << ", len(rhs) = " << rhsLen << std::endl;); return true; } SASSERT(lhs_chars.size() == rhs_chars.size()); expr_ref_vector diseqs(m); for (unsigned i = 0; i < lhs_chars.size(); ++i) { expr_ref cLHS(lhs_chars.get(i), sub_m); expr_ref cRHS(rhs_chars.get(i), sub_m); diseqs.push_back(sub_m.mk_not(sub_m.mk_eq(cLHS, cRHS))); } expr_ref final_diseq(mk_or(diseqs), sub_m); fixed_length_assumptions.push_back(final_diseq); TRACE("str_fl", tout << "inserting into fixed_lesson" <<std::endl;); fixed_length_lesson.insert(final_diseq, std::make_tuple(NEQ, lhs, rhs)); return true; } lbool theory_str::fixed_length_model_construction(expr_ref_vector formulas, expr_ref_vector &precondition, expr_ref_vector& free_variables, obj_map<expr, zstring> &model, expr_ref_vector &cex) { ast_manager & m = get_manager(); if (bitvector_character_constants.empty()) { bv_util bv(m); sort * bv8_sort = bv.mk_sort(8); for (unsigned i = 0; i < 256; ++i) { rational ch(i); expr_ref chTerm(bv.mk_numeral(ch, bv8_sort), m); bitvector_character_constants.push_back(chTerm); fixed_length_subterm_trail.push_back(chTerm); } } TRACE("str", ast_manager & m = get_manager(); tout << "dumping all formulas:" << std::endl; for (expr_ref_vector::iterator i = formulas.begin(); i != formulas.end(); ++i) { expr * ex = *i; tout << mk_pp(ex, m) << (ctx.is_relevant(ex) ? "" : " (NOT REL)") << std::endl; } ); fixed_length_subterm_trail.reset(); fixed_length_used_len_terms.reset(); fixed_length_assumptions.reset(); var_to_char_subterm_map.reset(); uninterpreted_to_char_subterm_map.reset(); fixed_length_lesson.reset(); // All reduced Boolean formulas in the current assignment expr_ref_vector fixed_length_reduced_boolean_formulas(m); // Boolean formulas on which to apply abstraction refinement. expr_ref_vector abstracted_boolean_formulas(m); smt_params subsolver_params; smt::kernel subsolver(m, subsolver_params); subsolver.set_logic(symbol("QF_BV")); sort * str_sort = u.str.mk_string_sort(); sort * bool_sort = m.mk_bool_sort(); for (expr * var : free_variables) { TRACE("str_fl", tout << "initialize free variable " << mk_pp(var, m) << std::endl;); rational var_lenVal; if (!fixed_length_get_len_value(var, var_lenVal)) { TRACE("str_fl", tout << "free variable " << mk_pp(var, m) << " has no length assignment" << std::endl;); expr_ref var_len_assertion(m_autil.mk_ge(mk_strlen(var), mk_int(0)), m); assert_axiom(var_len_assertion); add_persisted_axiom(var_len_assertion); return l_undef; } ptr_vector<expr> var_chars; expr_ref str_counterexample(m); if (!fixed_length_reduce_string_term(subsolver, var, var_chars, str_counterexample)) { TRACE("str_fl", tout << "free variable " << mk_pp(var, m) << " caused a conflict; asserting and continuing" << std::endl;); assert_axiom(str_counterexample); return l_undef; } } for (expr * f : formulas) { if (!get_context().is_relevant(f)) { expr * subformula = nullptr; if (m.is_not(f, subformula)) { if (!get_context().is_relevant(subformula)) { TRACE("str_fl", tout << "skip reducing formula " << mk_pp(f, m) << ", not relevant (and neither is its subformula)" << std::endl;); continue; } else { TRACE("str_fl", tout << "considering formula " << mk_pp(f, m) << ", its subformula is relevant but it is not" << std::endl;); } } else { TRACE("str_fl", tout << "skip reducing formula " << mk_pp(f, m) << ", not relevant" << std::endl;); continue; } } // reduce string formulas only. ignore others sort * fSort = m.get_sort(f); if (fSort == bool_sort && !is_quantifier(f)) { // extracted terms expr * subterm; expr * lhs; expr * rhs; if (m.is_eq(f, lhs, rhs)) { sort * lhs_sort = m.get_sort(lhs); if (lhs_sort == str_sort) { TRACE("str_fl", tout << "reduce string equality: " << mk_pp(lhs, m) << " == " << mk_pp(rhs, m) << std::endl;); expr_ref cex(m); expr_ref left(lhs, m); expr_ref right(rhs, m); if (!fixed_length_reduce_eq(subsolver, left, right, cex)) { // missing a side condition. assert it and return unknown assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } else { TRACE("str_fl", tout << "skip reducing formula " << mk_pp(f, m) << ", not an equality over strings" << std::endl;); } } else if (u.str.is_in_re(f)) { TRACE("str_fl", tout << "reduce regex membership: " << mk_pp(f, m) << std::endl;); expr_ref cex_clause(m); expr_ref re(f, m); if (!fixed_length_reduce_regex_membership(subsolver, re, cex_clause, true)) { assert_axiom(cex_clause); add_persisted_axiom(cex_clause); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } else if (u.str.is_contains(f)) { // TODO in some cases (e.g. len(haystack) is only slightly greater than len(needle)) // we might be okay to assert the full disjunction because there are very few disjuncts if (m_params.m_FixedLengthRefinement) { TRACE("str_fl", tout << "abstracting out positive contains: " << mk_pp(f, m) << std::endl;); abstracted_boolean_formulas.push_back(f); } else { TRACE("str_fl", tout << "reduce positive contains: " << mk_pp(f, m) << std::endl;); expr_ref cex(m); expr_ref cont(f, m); if (!fixed_length_reduce_contains(subsolver, cont, cex)) { assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } } else if (u.str.is_prefix(f)) { TRACE("str_fl", tout << "reduce positive prefix: " << mk_pp(f, m) << std::endl;); expr_ref cex(m); expr_ref pref(f, m); if (!fixed_length_reduce_prefix(subsolver, pref, cex)) { assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } else if (u.str.is_suffix(f)) { TRACE("str_fl", tout << "reduce positive suffix: " << mk_pp(f, m) << std::endl;); expr_ref cex(m); expr_ref suf(f, m); if (!fixed_length_reduce_suffix(subsolver, suf, cex)) { assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); }else if (m.is_not(f, subterm)) { // if subterm is a string formula such as an equality, reduce it as a disequality if (m.is_eq(subterm, lhs, rhs)) { sort * lhs_sort = m.get_sort(lhs); if (lhs_sort == str_sort) { TRACE("str_fl", tout << "reduce string disequality: " << mk_pp(lhs, m) << " != " << mk_pp(rhs, m) << std::endl;); expr_ref cex(m); expr_ref left(lhs, m); expr_ref right(rhs, m); if (!fixed_length_reduce_diseq(subsolver, left, right, cex)) { // missing a side condition. assert it and return unknown assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } } else if (u.str.is_in_re(subterm)) { TRACE("str_fl", tout << "reduce negative regex membership: " << mk_pp(f, m) << std::endl;); expr_ref cex_clause(m); expr_ref re(subterm, m); if (!fixed_length_reduce_regex_membership(subsolver, re, cex_clause, false)) { assert_axiom(cex_clause); add_persisted_axiom(cex_clause); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } else if (u.str.is_contains(subterm)) { TRACE("str_fl", tout << "reduce negative contains: " << mk_pp(subterm, m) << std::endl;); expr_ref cex(m); expr_ref cont(subterm, m); if (!fixed_length_reduce_negative_contains(subsolver, cont, cex)) { assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } else if (u.str.is_prefix(subterm)) { TRACE("str_fl", tout << "reduce negative prefix: " << mk_pp(subterm, m) << std::endl;); expr_ref cex(m); expr_ref pref(subterm, m); if (!fixed_length_reduce_negative_prefix(subsolver, pref, cex)) { assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } else if (u.str.is_suffix(subterm)) { TRACE("str_fl", tout << "reduce negative suffix: " << mk_pp(subterm, m) << std::endl;); expr_ref cex(m); expr_ref suf(subterm, m); if (!fixed_length_reduce_negative_suffix(subsolver, suf, cex)) { assert_axiom(cex); add_persisted_axiom(cex); return l_undef; } fixed_length_reduced_boolean_formulas.push_back(f); } else { TRACE("str_fl", tout << "skip reducing formula " << mk_pp(f, m) << ", not a boolean formula we handle" << std::endl;); } } else { TRACE("str_fl", tout << "skip reducing formula " << mk_pp(f, m) << ", not a boolean formula we handle" << std::endl;); continue; } } else { TRACE("str_fl", tout << "skip reducing formula " << mk_pp(f, m) << ", not relevant to strings" << std::endl;); continue; } } // Check consistency of all string-integer conversion terms wrt. integer theory before we solve, // possibly generating additional constraints for the bit-vector solver. { arith_value v(get_manager()); v.init(&get_context()); for (auto e : string_int_conversion_terms) { TRACE("str_fl", tout << "pre-run check str-int term " << mk_pp(e, get_manager()) << std::endl;); expr* _arg; if (u.str.is_stoi(e, _arg)) { expr_ref arg(_arg, m); rational slen; if (!fixed_length_get_len_value(arg, slen)) { expr_ref stoi_cex(m_autil.mk_ge(mk_strlen(arg), mk_int(0)), m); assert_axiom(stoi_cex); add_persisted_axiom(stoi_cex); return l_undef; } TRACE("str_fl", tout << "length of term is " << slen << std::endl;); rational ival; if (v.get_value(e, ival)) { TRACE("str_fl", tout << "integer theory assigns " << ival << " to " << mk_pp(e, get_manager()) << std::endl;); // if ival is non-negative, because we know the length of arg, we can add a character constraint for arg if (ival.is_nonneg()) { zstring ival_str(ival.to_string()); zstring padding; for (rational i = rational::zero(); i < slen - rational(ival_str.length()); ++i) { padding = padding + zstring("0"); } zstring arg_val = padding + ival_str; expr_ref stoi_cex(m); expr_ref arg_char_expr(mk_string(arg_val), m); // Add (e == ival) as a precondition. precondition.push_back(m.mk_eq(e, mk_int(ival))); // Assert (arg == arg_chars) in the subsolver. if (!fixed_length_reduce_eq(subsolver, arg, arg_char_expr, stoi_cex)) { assert_axiom(stoi_cex); add_persisted_axiom(stoi_cex); return l_undef; } } } else { TRACE("str_fl", tout << "integer theory has no assignment for " << mk_pp(e, get_manager()) << std::endl;); // consistency needs to be checked after the string is assigned } } else if (u.str.is_itos(e, _arg)) { expr_ref arg(_arg, m); rational slen; if (!fixed_length_get_len_value(e, slen)) { expr_ref stoi_cex(m_autil.mk_ge(mk_strlen(e), mk_int(0)), m); assert_axiom(stoi_cex); add_persisted_axiom(stoi_cex); return l_undef; } TRACE("str_fl", tout << "length of term is " << slen << std::endl;); rational ival; if (v.get_value(arg, ival)) { TRACE("str_fl", tout << "integer theory assigns " << ival << " to " << mk_pp(arg, get_manager()) << std::endl;); zstring ival_str; if (ival.is_neg()) { // e must be the empty string, i.e. have length 0 ival_str = zstring(""); } else { // e must be equal to the string representation of ival ival_str = zstring(ival.to_string()); } // Add (arg == ival) as a precondition. precondition.push_back(m.mk_eq(arg, mk_int(ival))); // Assert (e == ival_str) in the subsolver. expr_ref itos_cex(m); expr_ref _e(e, m); expr_ref arg_char_expr(mk_string(ival_str), m); if (!fixed_length_reduce_eq(subsolver, _e, arg_char_expr, itos_cex)) { assert_axiom(itos_cex); add_persisted_axiom(itos_cex); return l_undef; } } else { TRACE("str_fl", tout << "integer theory has no assignment for " << mk_pp(arg, get_manager()) << std::endl;); // consistency needs to be checked after the string is assigned } } } } for (auto e : fixed_length_used_len_terms) { expr * var = &e.get_key(); rational val = e.get_value(); precondition.push_back(m.mk_eq(u.str.mk_length(var), mk_int(val))); } TRACE("str_fl", tout << "formulas asserted to bitvector subsolver:" << std::endl; for (auto e : fixed_length_assumptions) { tout << mk_pp(e, subsolver.m()) << std::endl; } tout << "variable to character mappings:" << std::endl; for (auto &entry : var_to_char_subterm_map) { tout << mk_pp(entry.m_key, get_manager()) << ":"; for (auto e : entry.m_value) { tout << " " << mk_pp(e, subsolver.m()); } tout << std::endl; } tout << "reduced boolean formulas:" << std::endl; for (auto e : fixed_length_reduced_boolean_formulas) { tout << mk_pp(e, m) << std::endl; } ); TRACE("str_fl", tout << "calling subsolver" << std::endl;); lbool subproblem_status = subsolver.check(fixed_length_assumptions); if (subproblem_status == l_true) { bv_util bv(m); TRACE("str_fl", tout << "subsolver found SAT; reconstructing model" << std::endl;); model_ref subModel; subsolver.get_model(subModel); expr_substitution subst(m); //model_smt2_pp(std::cout, m, *subModel, 2); for (auto entry : var_to_char_subterm_map) { svector<unsigned> assignment; expr * var = entry.m_key; ptr_vector<expr> char_subterms(entry.m_value); for (expr * chExpr : char_subterms) { expr_ref chAssignment(subModel->get_const_interp(to_app(chExpr)->get_decl()), m); rational n; if (chAssignment != nullptr && bv.is_numeral(chAssignment, n) && n.is_unsigned()) { assignment.push_back(n.get_unsigned()); } else { assignment.push_back((unsigned)'?'); } } zstring strValue(assignment.size(), assignment.c_ptr()); model.insert(var, strValue); subst.insert(var, mk_string(strValue)); } TRACE("str_fl", for (auto entry : model) { tout << mk_pp(entry.m_key, m) << " = " << entry.m_value << std::endl; } ); for (auto entry : uninterpreted_to_char_subterm_map) { svector<unsigned> assignment; expr * var = entry.m_key; ptr_vector<expr> char_subterms(entry.m_value); for (expr * chExpr : char_subterms) { expr_ref chAssignment(subModel->get_const_interp(to_app(chExpr)->get_decl()), m); rational n; if (chAssignment != nullptr && bv.is_numeral(chAssignment, n) && n.is_unsigned()) { assignment.push_back(n.get_unsigned()); } else { assignment.push_back((unsigned)'?'); } } zstring strValue(assignment.size(), assignment.c_ptr()); model.insert(var, strValue); subst.insert(var, mk_string(strValue)); } // Check consistency of string-integer conversion terms after the search. { scoped_ptr<expr_replacer> replacer = mk_default_expr_replacer(m, false); replacer->set_substitution(&subst); th_rewriter rw(m); arith_value v(get_manager()); v.init(&get_context()); for (auto e : string_int_conversion_terms) { TRACE("str_fl", tout << "post-run check str-int term " << mk_pp(e, get_manager()) << std::endl;); expr* _arg; if (u.str.is_stoi(e, _arg)) { expr_ref arg(_arg, m); rational ival; if (v.get_value(e, ival)) { expr_ref arg_subst(arg, m); (*replacer)(arg, arg_subst); rw(arg_subst); TRACE("str_fl", tout << "ival = " << ival << ", string arg evaluates to " << mk_pp(arg_subst, m) << std::endl;); symbol arg_str; if (u.str.is_string(arg_subst, arg_str)) { zstring arg_zstr(arg_str.bare_str()); rational arg_value; if (string_integer_conversion_valid(arg_zstr, arg_value)) { if (ival != arg_value) { // contradiction expr_ref cex(m.mk_not(m.mk_and(ctx.mk_eq_atom(arg, mk_string(arg_zstr)), ctx.mk_eq_atom(e, mk_int(ival)))), m); assert_axiom(cex); return l_undef; } } else { if (!ival.is_minus_one()) { expr_ref cex(m.mk_not(m.mk_and(ctx.mk_eq_atom(arg, mk_string(arg_zstr)), ctx.mk_eq_atom(e, mk_int(ival)))), m); assert_axiom(cex); return l_undef; } } } } } else if (u.str.is_itos(e, _arg)) { expr_ref arg(_arg, m); rational ival; if (v.get_value(arg, ival)) { expr_ref e_subst(e, m); (*replacer)(e, e_subst); rw(e_subst); TRACE("str_fl", tout << "ival = " << ival << ", string arg evaluates to " << mk_pp(e_subst, m) << std::endl;); symbol e_str; if (u.str.is_string(e_subst, e_str)) { zstring e_zstr(e_str.bare_str()); // if arg is negative, e must be empty // if arg is non-negative, e must be valid AND cannot contain leading zeroes if (ival.is_neg()) { if (!e_zstr.empty()) { // contradiction expr_ref cex(ctx.mk_eq_atom(m_autil.mk_le(arg, mk_int(-1)), ctx.mk_eq_atom(e, mk_string(""))), m); assert_axiom(cex); return l_undef; } } else { rational e_value; if (string_integer_conversion_valid(e_zstr, e_value)) { // e contains leading zeroes if its first character is 0 but converted to something other than 0 if (e_zstr[0] == '0' && !e_value.is_zero()) { // contradiction expr_ref cex(m.mk_not(m.mk_and(ctx.mk_eq_atom(arg, mk_int(ival)), ctx.mk_eq_atom(e, mk_string(e_zstr)))), m); assert_axiom(cex); return l_undef; } } else { // contradiction expr_ref cex(m.mk_not(m.mk_and(ctx.mk_eq_atom(arg, mk_int(ival)), ctx.mk_eq_atom(e, mk_string(e_zstr)))), m); assert_axiom(cex); return l_undef; } } } } } } } // TODO insert length values into substitution table as well? if (m_params.m_FixedLengthRefinement) { scoped_ptr<expr_replacer> replacer = mk_default_expr_replacer(m, false); replacer->set_substitution(&subst); th_rewriter rw(m); if (!abstracted_boolean_formulas.empty()) { for (auto f : abstracted_boolean_formulas) { TRACE("str_fl", tout << "refinement of boolean formula: " << mk_pp(f, m) << std::endl;); expr_ref f_new(m); (*replacer)(f, f_new); rw(f_new); TRACE("str_fl", tout << "after substitution and simplification, evaluates to: " << mk_pp(f_new, m) << std::endl;); // now there are three cases, depending on what f_new evaluates to: // true -> OK, do nothing // false -> refine abstraction by generating conflict clause // anything else -> error, probably our substitution was incomplete if (m.is_true(f_new)) { // do nothing } else if (m.is_false(f_new)) { expr * needle = nullptr, *haystack = nullptr; if (u.str.is_contains(f, haystack, needle)) { expr_ref haystack_assignment(m); expr_ref needle_assignment(m); (*replacer)(haystack, haystack_assignment); (*replacer)(needle, needle_assignment); cex.push_back(f); cex.push_back(ctx.mk_eq_atom(haystack, haystack_assignment)); cex.push_back(ctx.mk_eq_atom(needle, needle_assignment)); return l_false; } else { TRACE("str_fl", tout << "error: unhandled refinement term " << mk_pp(f, m) << std::endl;); NOT_IMPLEMENTED_YET(); } } else { NOT_IMPLEMENTED_YET(); } } } } return l_true; } else if (subproblem_status == l_false) { if (m_params.m_FixedLengthNaiveCounterexamples) { TRACE("str_fl", tout << "subsolver found UNSAT; constructing length counterexample" << std::endl;); for (auto e : fixed_length_used_len_terms) { expr * var = &e.get_key(); rational val = e.get_value(); cex.push_back(m.mk_eq(u.str.mk_length(var), mk_int(val))); } for (auto e : fixed_length_reduced_boolean_formulas) { cex.push_back(e); } return l_false; } else { TRACE("str_fl", tout << "subsolver found UNSAT; reconstructing unsat core" << std::endl;); TRACE("str_fl", tout << "unsat core has size " << subsolver.get_unsat_core_size() << std::endl;); bool negate_pre = false; for (unsigned i = 0; i < subsolver.get_unsat_core_size(); ++i) { TRACE("str", tout << "entry " << i << " = " << mk_pp(subsolver.get_unsat_core_expr(i), m) << std::endl;); rational index; expr* lhs; expr* rhs; TRACE("str_fl", tout << fixed_length_lesson.size() << std::endl;); std::tie(index, lhs, rhs) = fixed_length_lesson.find(subsolver.get_unsat_core_expr(i)); TRACE("str_fl", tout << "lesson: " << mk_pp(lhs, m) << " == " << mk_pp(rhs, m) << " at index " << index << std::endl;); cex.push_back(refine(lhs, rhs, index)); if (index < rational(0)) { negate_pre = true; } } if (negate_pre || subsolver.get_unsat_core_size() == 0){ for (auto ex : precondition) { cex.push_back(ex); } } return l_false; } } else { // l_undef TRACE("str_fl", tout << "WARNING: subsolver found UNKNOWN" << std::endl;); return l_undef; } } }; // namespace smt
// Copyright (c) 2011-2013 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 "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Lukercoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { #if QT_VERSION < 0x050000 formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); #else formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address)); #endif } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed!"), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->deleteLater(); updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::setAddress(const QString &address) { SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setVisible((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Bitcoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
// license:BSD-3-Clause // copyright-holders:Olivier Galibert // Block device on vector<uint8_t> #include "fsblk_vec.h" #include "strformat.h" #include <algorithm> #include <stdexcept> const uint8_t *fsblk_vec_t::blk_t::rodata() { return m_data; } uint8_t *fsblk_vec_t::blk_t::data() { return m_data; } void fsblk_vec_t::blk_t::drop_weak_references() { } uint32_t fsblk_vec_t::block_count() const { return m_data.size() / m_block_size; } fsblk_t::block_t fsblk_vec_t::get(uint32_t id) { if(id >= block_count()) throw std::out_of_range(util::string_format("Block number overflow: requiring block %d on device of size %d (%d bytes, block size %d)", id, block_count(), m_data.size(), m_block_size)); return block_t(new blk_t(m_data.data() + m_block_size*id, m_block_size)); } void fsblk_vec_t::fill(uint8_t data) { std::fill(m_data.begin(), m_data.end(), data); }
/** * @file <argos3/plugins/simulator/entities/wifi_equipped_entity.cpp> * * @author Carlo Pinciroli - <ilpincy@gmail.com> */ #include "wifi_equipped_entity.h" #include <argos3/core/simulator/space/space.h> namespace argos { /****************************************/ /****************************************/ CWiFiEquippedEntity::CWiFiEquippedEntity(CComposableEntity* pc_parent) : CEntity(pc_parent) {} /****************************************/ /****************************************/ CWiFiEquippedEntity::CWiFiEquippedEntity(CComposableEntity* pc_parent, const std::string& str_id) : CEntity(pc_parent, str_id) {} /****************************************/ /****************************************/ REGISTER_STANDARD_SPACE_OPERATIONS_ON_ENTITY(CWiFiEquippedEntity); /****************************************/ /****************************************/ }
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdesigner_dockwidget_p.h" #include "layoutinfo_p.h" #include <QtDesigner/QDesignerFormWindowInterface> #include <QtDesigner/QDesignerFormEditorInterface> #include <QtDesigner/QDesignerContainerExtension> #include <QtDesigner/QExtensionManager> #include <QtDesigner/QDesignerFormWindowCursorInterface> #include <QtWidgets/QMainWindow> #include <QtWidgets/QLayout> QT_BEGIN_NAMESPACE QDesignerDockWidget::QDesignerDockWidget(QWidget *parent) : QDockWidget(parent) { } QDesignerDockWidget::~QDesignerDockWidget() { } bool QDesignerDockWidget::docked() const { return qobject_cast<QMainWindow*>(parentWidget()) != 0; } void QDesignerDockWidget::setDocked(bool b) { if (QMainWindow *mainWindow = findMainWindow()) { QDesignerFormEditorInterface *core = formWindow()->core(); QDesignerContainerExtension *c; c = qt_extension<QDesignerContainerExtension*>(core->extensionManager(), mainWindow); if (b && !docked()) { // Dock it // ### undo/redo stack setParent(0); c->addWidget(this); formWindow()->selectWidget(this, formWindow()->cursor()->isWidgetSelected(this)); } else if (!b && docked()) { // Undock it for (int i = 0; i < c->count(); ++i) { if (c->widget(i) == this) { c->remove(i); break; } } // #### restore the position setParent(mainWindow->centralWidget()); show(); formWindow()->selectWidget(this, formWindow()->cursor()->isWidgetSelected(this)); } } } Qt::DockWidgetArea QDesignerDockWidget::dockWidgetArea() const { if (QMainWindow *mainWindow = qobject_cast<QMainWindow*>(parentWidget())) return mainWindow->dockWidgetArea(const_cast<QDesignerDockWidget*>(this)); return Qt::LeftDockWidgetArea; } void QDesignerDockWidget::setDockWidgetArea(Qt::DockWidgetArea dockWidgetArea) { if (QMainWindow *mainWindow = qobject_cast<QMainWindow*>(parentWidget())) { if ((dockWidgetArea != Qt::NoDockWidgetArea) && isAreaAllowed(dockWidgetArea)) { mainWindow->addDockWidget(dockWidgetArea, this); } } } bool QDesignerDockWidget::inMainWindow() const { QMainWindow *mw = findMainWindow(); if (mw && !mw->centralWidget()->layout()) { if (mw == parentWidget()) return true; if (mw->centralWidget() == parentWidget()) return true; } return false; } QDesignerFormWindowInterface *QDesignerDockWidget::formWindow() const { return QDesignerFormWindowInterface::findFormWindow(const_cast<QDesignerDockWidget*>(this)); } QMainWindow *QDesignerDockWidget::findMainWindow() const { if (QDesignerFormWindowInterface *fw = formWindow()) return qobject_cast<QMainWindow*>(fw->mainContainer()); return 0; } QT_END_NAMESPACE
/** * @file * @brief Quick sort algorithm * * Implementation Details - * Quick Sort is a divide and conquer algorithm. It picks and element as * pivot and partition the given array around the picked pivot. There * are many different versions of quickSort that pick pivot in different * ways. * * 1. Always pick the first element as pivot * 2. Always pick the last element as pivot (implemented below) * 3. Pick a random element as pivot * 4. Pick median as pivot * * The key process in quickSort is partition(). Target of partition is, * given an array and an element x(say) of array as pivot, put x at it's * correct position in sorted array and put all smaller elements (samller * than x) before x, and put all greater elements (greater than x) after * x. All this should be done in linear time * */ #include <cstdlib> #include <iostream> namespace sorting { /** * This function takes last element as pivot, places * the pivot element at its correct position in sorted * array, and places all smaller (smaller than pivot) * to left of pivot and all greater elements to right * of pivot * */ int partition(int arr[], int low, int high) { int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return (i + 1); } /** * The main function that implements QuickSort * arr[] --> Array to be sorted, * low --> Starting index, * high --> Ending index */ void quickSort(int arr[], int low, int high) { if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); } } } // namespace sorting using sorting::quickSort; // prints the array after sorting void show(int arr[], int size) { for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } /** Driver program to test above functions */ int main() { int size; std::cout << "\nEnter the number of elements : "; std::cin >> size; int *arr = new int[size]; std::cout << "\nEnter the unsorted elements : "; for (int i = 0; i < size; ++i) { std::cout << "\n"; std::cin >> arr[i]; } quickSort(arr, 0, size); std::cout << "Sorted array\n"; show(arr, size); delete[] arr; return 0; }
/* Copyright 2016 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/kernels/cast_op_impl.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; std::function<void(OpKernelContext*, const Tensor&, Tensor*)> GetCpuCastFromInt16(DataType dst_dtype) { CURRY_TYPES3(CAST_CASE, CPUDevice, int16); return nullptr; } #if GOOGLE_CUDA std::function<void(OpKernelContext*, const Tensor&, Tensor*)> GetGpuCastFromInt16(DataType dst_dtype) { CURRY_TYPES3(CAST_CASE, GPUDevice, int16); return nullptr; } #endif // GOOGLE_CUDA #ifdef TENSORFLOW_USE_SYCL typedef Eigen::SyclDevice SYCLDevice; std::function<void(OpKernelContext*, const Tensor&, Tensor*)> GetSyclCastFromInt16(DataType dst_dtype) { CURRY_TYPES3(CAST_CASE, SYCLDevice, int16); return nullptr; } #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. 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 "luci/Pass/TransformMinMaxToRelu6Pass.h" #include <luci/IR/CircleNodes.h> #include <gtest/gtest.h> namespace { /** * Minimum-Maximum pattern graph * * [CircleInput] [CircleConst] * \ / * [CircleMinimum] [CircleConst] * | / * [CircleMaximum] * | * [CircleOutput] */ struct MinMaxGraph { loco::Graph _g; luci::CircleInput *_input = nullptr; luci::CircleMinimum *_mini = nullptr; luci::CircleConst *_mini_const = nullptr; luci::CircleMaximum *_maxi = nullptr; luci::CircleConst *_maxi_const = nullptr; luci::CircleOutput *_output = nullptr; }; class TransformMinMaxToRelu6PassTest : public ::testing::Test { protected: virtual void SetUp() { const int N = 1; const int H = 4; const int W = 4; const int C = 3; // graph input and output auto graph_input = _min_max_g._g.inputs()->create(); auto graph_output = _min_max_g._g.outputs()->create(); // CircleInput _min_max_g._input = _min_max_g._g.nodes()->create<luci::CircleInput>(); _min_max_g._input->index(graph_input->index()); _min_max_g._input->shape({N, H, W, C}); _min_max_g._input->dtype(loco::DataType::FLOAT32); // CircleConst _min_max_g._mini_const = _min_max_g._g.nodes()->create<luci::CircleConst>(); _min_max_g._mini_const->shape({}); // scalar _min_max_g._mini_const->dtype(loco::DataType::FLOAT32); _min_max_g._mini_const->size<loco::DataType::FLOAT32>(1); _min_max_g._mini_const->at<loco::DataType::FLOAT32>(0) = 6.; // CircleMinimum _min_max_g._mini = _min_max_g._g.nodes()->create<luci::CircleMinimum>(); _min_max_g._mini->x(_min_max_g._input); _min_max_g._mini->y(_min_max_g._mini_const); _min_max_g._mini->shape({N, H, W, C}); _min_max_g._mini->dtype(loco::DataType::FLOAT32); // CircleConst _min_max_g._maxi_const = _min_max_g._g.nodes()->create<luci::CircleConst>(); _min_max_g._mini_const->shape({}); // scalar _min_max_g._maxi_const->dtype(loco::DataType::FLOAT32); _min_max_g._maxi_const->size<loco::DataType::FLOAT32>(1); _min_max_g._maxi_const->at<loco::DataType::FLOAT32>(0) = 0.; // CircleMaximum _min_max_g._maxi = _min_max_g._g.nodes()->create<luci::CircleMaximum>(); _min_max_g._maxi->x(_min_max_g._mini); _min_max_g._maxi->y(_min_max_g._maxi_const); _min_max_g._maxi->shape({N, H, W, C}); _min_max_g._maxi->dtype(loco::DataType::FLOAT32); // CircleOutput _min_max_g._output = _min_max_g._g.nodes()->create<luci::CircleOutput>(); _min_max_g._output->index(graph_output->index()); _min_max_g._output->from(_min_max_g._maxi); _min_max_g._output->shape({N, H, W, C}); _min_max_g._output->dtype(loco::DataType::FLOAT32); } protected: luci::TransformMinMaxToRelu6Pass _pass; MinMaxGraph _min_max_g; }; } // namespace TEST_F(TransformMinMaxToRelu6PassTest, name) { auto const name = _pass.name(); ASSERT_NE(nullptr, name); } /** * Optimized graph looks like below. * * [CircleInput] * | * [CircleRelu6] * | * [CircleOutput] */ TEST_F(TransformMinMaxToRelu6PassTest, simple_test) { auto ret = _pass.run(&_min_max_g._g); EXPECT_TRUE(ret); auto relu6 = dynamic_cast<luci::CircleRelu6 *>(_min_max_g._output->from()); EXPECT_NE(nullptr, relu6); auto input = dynamic_cast<luci::CircleInput *>(relu6->features()); EXPECT_NE(nullptr, input); } TEST_F(TransformMinMaxToRelu6PassTest, wrong_condition_NEG) { _min_max_g._maxi_const->at<loco::DataType::FLOAT32>(0) = 2.; auto ret = _pass.run(&_min_max_g._g); EXPECT_FALSE(ret); }
#include <iostream> using namespace std; int main() { int N,a[10001],f[10001]; while(1) { cin >> N; if(N == 0) { break; } for(int i = 1;i <= N;i++) { cin >> a[i]; } f[1] = a[1]; for(int k = 2;k <= N; k++) { if(f[k-1] + a[k] >= a[k]) { f[k] = f[k-1] + a[k]; }else { f[k] = a[k]; } } int fmax = -2147483647; for(int l = 1;l <= N;l++) { if(fmax < f[l]) { fmax = f[l]; } } if(fmax >= 0) { cout << "The maximum winning streak is " << fmax << "." << endl; }else { cout << "Losing streak." << endl; } } return 0; }
/** Defines an "objective specification" object and the classes used to read and load it. */ #include "convar.h" #include "asw_mission_text_database.h" #include "KeyValues.h" #include "filesystem.h" #include "vstdlib/random.h" #include "vprof.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" CUtlSymbolTable CASW_MissionTextDB::s_SymTab( 128, 128, true ); CUtlSymbolMsnTxt CASW_MissionTextSpec::SymbolForMissionFilename( const char *pMissionFilename, bool bCreateIfNotFound ) { if ( pMissionFilename == NULL || pMissionFilename[0] == 0 ) { return UTL_INVAL_SYMBOL; } else { char buf[256]; V_FileBase( pMissionFilename, buf, 255 ); return bCreateIfNotFound ? SymTab().AddString( pMissionFilename ) : SymTab().Find( pMissionFilename ) ; } } inline const char *FindStrSubkey( KeyValues * RESTRICT pKV, const char *pKeyName ) { KeyValues * RESTRICT pSubKey = pKV->FindKey( pKeyName ); return pSubKey ? pSubKey->GetString() : NULL; } /* "objectivetext" { "entityname" "foo" "missionfile" "mission_frotz.txt" "shortdesc" "Recover the alien sandwich." "longdesc" "Delicious, tender and moist: a perfect balance between starch and protein. Somewhere within the base lies this paragon among lunchmeats, and it is your sacred task to retrieve it." } */ void CASW_MissionTextDB::LoadKeyValuesFile( const char *pFilename ) { KeyValues * RESTRICT pKeyValuesSource = new KeyValues( pFilename ); KeyValues::AutoDelete raii( pKeyValuesSource ); // deletes the keyvalues at end of scope if ( !pKeyValuesSource->LoadFromFile( g_pFullFileSystem, pFilename, "GAME" ) ) { //AssertMsg1( false, "Could not open key values file %s", pFilename ); Warning( "Could not open key values file %s\n", pFilename ); return; } int numAdded = 0 ; for ( KeyValues *RESTRICT pEntry = pKeyValuesSource ; pEntry != NULL ; pEntry = pEntry->GetNextKey() ) { if ( Q_stricmp( pEntry->GetName(), "objectivetext" ) == 0 ) { const char *pEntName = FindStrSubkey( pEntry, "entityname" ); if ( !pEntName ) { Warning( "A mission text block did not specify an entityname!\n%s\n", pEntry->GetString() ); continue; } const char *pShortDesc = FindStrSubkey( pEntry, "shortdesc" ); if ( !pShortDesc ) { Warning( "A mission text block did not specify a short description!\n%s\n", pEntry->GetString() ); continue; } const char *pLongDesc = FindStrSubkey( pEntry, "longdesc" ); if ( !pLongDesc ) { Warning( "A mission text block did not specify a long description!\n%s\n", pEntry->GetString() ); // substitute the short desc pLongDesc = pShortDesc; } const char *pMissionFilename = FindStrSubkey( pEntry, "missionfile" ); // insert AddSpec( pShortDesc, pLongDesc, pEntName, pMissionFilename ); ++numAdded; } else { Warning( "Keyvalues file contained unknown key type %s\n", pEntry->GetName() ); } } Msg( "%d mission descriptions loaded from %s\n", numAdded, pFilename ); } void CASW_MissionTextDB::Reset() { m_missionSpecs.RemoveAll(); } void CASW_MissionTextDB::AddSpec( const char *pszShortDescription, const char *pszSLongDescription, const char *pszObjectiveEntityName, const char *pszMissionFilename ) { // assert mandatory fields Assert( pszShortDescription && pszSLongDescription ); Assert( pszObjectiveEntityName ); int nextInsertId = m_missionSpecs.AddToTail(); m_missionSpecs[ nextInsertId ].Init( pszShortDescription, pszSLongDescription, pszObjectiveEntityName, pszMissionFilename, nextInsertId ); }; const CASW_MissionTextSpec * CASW_MissionTextDB::Find( const char *pObjectiveEntityName, const char *pMissionFilename /*= NULL */ ) { // simple algorithm. walk through building a vector of possible matches. then sort by match quality. return the best. // in the future this will actually use a data structure. if ( pObjectiveEntityName == NULL ) return NULL; // the type for our local vector below struct MatchTuple { const CASW_MissionTextSpec *pSpec; int score; MatchTuple( const CASW_MissionTextSpec * pSpec_, int score_ ) : pSpec(pSpec_), score(score_) {}; }; CUtlVector<MatchTuple> matches( Count() >> 2, Count() >> 2 ); CUtlSymbolMsnTxt nEntName = SymTab().Find( pObjectiveEntityName ); CUtlSymbolMsnTxt nMissionName = CASW_MissionTextSpec::SymbolForMissionFilename( pMissionFilename, false ); if ( !nEntName.IsValid() ) { Warning( "No mission text specifier mentions an entity named %s\n", pObjectiveEntityName ); return NULL; } // march forward looking for matches. compute a score for each match. const int N = m_missionSpecs.Count(); for ( int i = 0 ; i < N ; ++i ) { const CASW_MissionTextSpec *pSpec = &m_missionSpecs[i]; int matchscore = 0; // test mandatory field if ( pSpec->m_nObjectiveEntityName == nEntName ) { // score optional fields. // compare each field in the spec against the query. // if the field in the spec is defined, then a match adds one to // score, but a mismatch disqualifies the entry. // if the field in the spec is undefined, then it matches everything, // but does not add to score. if ( pSpec->m_nMissionFilename.IsValid() ) { matchscore = pSpec->m_nMissionFilename == nMissionName ? 2 : 0; } else { matchscore = 1; } } if ( matchscore > 0 ) { // best possible score, return immediately if ( matchscore == 2 ) { // (refactor this block if we want to choose randomly from many possibilities) return pSpec; } else { matches.AddToTail( MatchTuple(pSpec, matchscore) ); } } } if ( matches.Count() == 0 ) return NULL; // nothing found // in theory we should sort this list to push the best matches to the beginning, // but right now the only possible score is 1, so return an arbitrary element return matches[0].pSpec; } CASW_MissionTextSpec * CASW_MissionTextDB::GetSpecById( CASW_MissionTextSpec::ID_t nId ) { AssertMsg2( nId < m_missionSpecs.Count(), "Tried to look up invalid mission text ID %d / %d\n", nId, m_missionSpecs.Count() ); return nId < m_missionSpecs.Count() ? &m_missionSpecs[ nId ] : NULL; } const char * CASW_MissionTextDB::GetShortDescriptionByID( unsigned int id ) { CASW_MissionTextSpec * RESTRICT pSpec = GetSpecById( id ); return pSpec ? pSpec->GetShortDescription() : NULL; } const char * CASW_MissionTextDB::GetLongDescriptionByID( unsigned int id ) { CASW_MissionTextSpec * RESTRICT pSpec = GetSpecById( id ); return pSpec ? pSpec->GetLongDescription() : NULL; } IASW_Mission_Text_Database::ID_t CASW_MissionTextDB::FindMissionTextID( const char *pEntityName, const char *pMissionName ) { const CASW_MissionTextSpec *pSpec = Find( pEntityName, pMissionName ); return pSpec ? pSpec->m_nId : IASW_Mission_Text_Database::INVALID_INDEX ; } #ifdef ENABLE_MISSION_TEXT_DB_DEBUG_FUNCTIONS CASW_MissionTextDB g_MissionTextDB; void CC_ASW_TestMissionText_f( const CCommand &args ) { if ( args.ArgC() < 2 ) { Msg("Usage: asw_test_mission_text_q <entity name> [mission name]"); return; } const char *pEntName = args[1]; const char *pMissName = args.ArgC() >= 3 ? args[2] : NULL; const CASW_MissionTextSpec *pSpec = g_MissionTextDB.Find( pEntName, pMissName ); if ( pSpec ) { Msg( "\"%s\"\n", pSpec->GetShortDescription() ); } else { Warning( "Not found.\n" ); } } static ConCommand asw_test_mission_text_q("asw_test_mission_text_q", CC_ASW_TestMissionText_f, 0 ); void CC_ASW_TestMissionTextLoad_f( const CCommand &args ) { if ( args.ArgC() < 2 ) { Msg("Usage: asw_test_mission_text_load [filename]"); return; } g_MissionTextDB.LoadKeyValuesFile( args[1] ); } static ConCommand asw_test_mission_text_load("asw_test_mission_text_load", CC_ASW_TestMissionTextLoad_f, 0 ); void CC_ASW_TestMissionTextReset_f( const CCommand &args ) { g_MissionTextDB.Reset(); } static ConCommand asw_test_mission_text_reset("asw_test_mission_text_reset", CC_ASW_TestMissionTextReset_f, 0 ); #endif
#include "Ecologico.h" #include "Ser.h" #include "Jogo.h" #include "Edificio.h" Ecologico::Ecologico(string n, int cm, int cf,int idCar) : Caracteristica(n, cm, cf, idCar) { } Ecologico::~Ecologico() { } void Ecologico::fazEfeito(int p, Ser * s, Jogo *jogo) { if (jogo->getMundo().at(p - 1)->getEdifico() != nullptr) { if (s->getBandeira() != jogo->getMundo().at(p - 1)->getEdifico()->getBandeira()) jogo->getMundo().at(p - 1)->getEdifico()->setSaude(jogo->getMundo().at(p - 1)->getEdifico()->getSaude() - s->getAtaque()); } if (jogo->getMundo().at(p + 1)->getEdifico() != nullptr) { if (s->getBandeira() != jogo->getMundo().at(p + 1)->getEdifico()->getBandeira()) jogo->getMundo().at(p + 1)->getEdifico()->setSaude(jogo->getMundo().at(p + 1)->getEdifico()->getSaude() - s->getAtaque()); } }
/* * LevelFinest.h * * Created on: 10.01.2015 * Author: Michael */ #ifndef LEVELFINEST_H_ #define LEVELFINEST_H_ #include "Level.hpp" namespace NetworKit { /** * @ingroup numerics */ template<class Matrix> class LevelFinest : public Level<Matrix> { public: LevelFinest() : Level<Matrix>(LevelType::FINEST) {} LevelFinest(const Matrix& A) : Level<Matrix>(LevelType::FINEST, A) {} }; } /* namespace NetworKit */ #endif /* LEVELFINEST_H_ */
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //============================================================================= #include "pch_serverbrowser.h" // expose the server browser interfaces CServerBrowser g_ServerBrowserSingleton; EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CServerBrowser, IServerBrowser, SERVERBROWSER_INTERFACE_VERSION, g_ServerBrowserSingleton); EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CServerBrowser, IVGuiModule, "VGuiModuleServerBrowser001", g_ServerBrowserSingleton); // the interface loaded by PlatformMenu.vdf // singleton accessor CServerBrowser &ServerBrowser() { return g_ServerBrowserSingleton; } IRunGameEngine *g_pRunGameEngine = NULL; static CSteamAPIContext g_SteamAPIContext; CSteamAPIContext *steamapicontext = &g_SteamAPIContext; IEngineReplay *g_pEngineReplay = NULL; ConVar sb_firstopentime( "sb_firstopentime", "0", FCVAR_DEVELOPMENTONLY, "Indicates the time the server browser was first opened." ); ConVar sb_numtimesopened( "sb_numtimesopened", "0", FCVAR_DEVELOPMENTONLY, "Indicates the number of times the server browser was opened this session." ); // the original author of this code felt strdup was not acceptible. inline char *CloneString( const char *str ) { char *cloneStr = new char [ strlen(str)+1 ]; strcpy( cloneStr, str ); return cloneStr; } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CServerBrowser::CServerBrowser() { } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CServerBrowser::~CServerBrowser() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CServerBrowser::CreateDialog() { if (!m_hInternetDlg.Get()) { m_hInternetDlg = new CServerBrowserDialog(NULL); // SetParent() call below fills this in m_hInternetDlg->Initialize(); } } //----------------------------------------------------------------------------- // Purpose: links to vgui and engine interfaces //----------------------------------------------------------------------------- bool CServerBrowser::Initialize(CreateInterfaceFn *factorylist, int factoryCount) { ConnectTier1Libraries( factorylist, factoryCount ); ConVar_Register(); ConnectTier2Libraries( factorylist, factoryCount ); ConnectTier3Libraries( factorylist, factoryCount ); g_pRunGameEngine = NULL; for ( int i = 0; i < factoryCount; ++i ) { if ( !g_pEngineReplay ) { g_pEngineReplay = ( IEngineReplay * )factorylist[ i ]( ENGINE_REPLAY_INTERFACE_VERSION, NULL ); } } SteamAPI_InitSafe(); SteamAPI_SetTryCatchCallbacks( false ); // We don't use exceptions, so tell steam not to use try/catch in callback handlers steamapicontext->Init(); for (int i = 0; i < factoryCount; i++) { if (!g_pRunGameEngine) { g_pRunGameEngine = (IRunGameEngine *)(factorylist[i])(RUNGAMEENGINE_INTERFACE_VERSION, NULL); } } // load the vgui interfaces #if defined( STEAM ) || defined( HL1 ) if ( !vgui::VGuiControls_Init("ServerBrowser", factorylist, factoryCount) ) #else if ( !vgui::VGui_InitInterfacesList("ServerBrowser", factorylist, factoryCount) ) #endif return false; // load localization file g_pVGuiLocalize->AddFile( "servers/serverbrowser_%language%.txt" ); return true; } //----------------------------------------------------------------------------- // Purpose: links to other modules interfaces (tracker) //----------------------------------------------------------------------------- bool CServerBrowser::PostInitialize(CreateInterfaceFn *modules, int factoryCount) { // find the interfaces we need for (int i = 0; i < factoryCount; i++) { if (!g_pRunGameEngine) { g_pRunGameEngine = (IRunGameEngine *)(modules[i])(RUNGAMEENGINE_INTERFACE_VERSION, NULL); } } CreateDialog(); m_hInternetDlg->SetVisible(false); return g_pRunGameEngine; } //----------------------------------------------------------------------------- // Purpose: true if the user can't play a game due to VAC banning //----------------------------------------------------------------------------- bool CServerBrowser::IsVACBannedFromGame( int nAppID ) { return false; } //----------------------------------------------------------------------------- // Purpose: Marks that the tool/game loading us intends to feed us workshop information //----------------------------------------------------------------------------- void CServerBrowser::SetWorkshopEnabled( bool bManaged ) { m_bWorkshopEnabled = bManaged; } //----------------------------------------------------------------------------- // Purpose: Add a mapname to our known user-subscribed workshop maps list //----------------------------------------------------------------------------- void CServerBrowser::AddWorkshopSubscribedMap( const char *pszMapName ) { CUtlString strMap( pszMapName ); if ( !IsWorkshopSubscribedMap( strMap ) ) { m_vecWorkshopSubscribedMaps.AddToTail( strMap ); } } //----------------------------------------------------------------------------- // Purpose: remove a mapname to our known user-subscribed workshop maps list //----------------------------------------------------------------------------- void CServerBrowser::RemoveWorkshopSubscribedMap( const char *pszMapName ) { m_vecWorkshopSubscribedMaps.FindAndFastRemove( CUtlString( pszMapName ) ); } //----------------------------------------------------------------------------- // Purpose: Well, is it? //----------------------------------------------------------------------------- bool CServerBrowser::IsWorkshopEnabled() { return m_bWorkshopEnabled; } //----------------------------------------------------------------------------- // Purpose: Check if this map is in our subscribed list //----------------------------------------------------------------------------- bool CServerBrowser::IsWorkshopSubscribedMap( const char *pszMapName ) { return m_vecWorkshopSubscribedMaps.HasElement( CUtlString( pszMapName ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CServerBrowser::IsValid() { return ( g_pRunGameEngine ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CServerBrowser::Activate() { static bool firstTimeOpening = true; if ( firstTimeOpening ) { m_hInternetDlg->LoadUserData(); // reload the user data the first time the dialog is made visible, helps with the lag between module load and // steamui getting Deactivate() call firstTimeOpening = false; } int numTimesOpened = sb_numtimesopened.GetInt() + 1; sb_numtimesopened.SetValue( numTimesOpened ); if ( numTimesOpened == 1 ) { time_t aclock; time( &aclock ); sb_firstopentime.SetValue( (int) aclock ); } Open(); return true; } //----------------------------------------------------------------------------- // Purpose: called when the server browser gets used in the game //----------------------------------------------------------------------------- void CServerBrowser::Deactivate() { if (m_hInternetDlg.Get()) { m_hInternetDlg->SaveUserData(); } } //----------------------------------------------------------------------------- // Purpose: called when the server browser is no longer being used in the game //----------------------------------------------------------------------------- void CServerBrowser::Reactivate() { if (m_hInternetDlg.Get()) { m_hInternetDlg->LoadUserData(); if (m_hInternetDlg->IsVisible()) { m_hInternetDlg->RefreshCurrentPage(); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CServerBrowser::Open() { m_hInternetDlg->Open(); } //----------------------------------------------------------------------------- // Purpose: returns direct handle to main server browser dialog //----------------------------------------------------------------------------- vgui::VPANEL CServerBrowser::GetPanel() { return m_hInternetDlg.Get() ? m_hInternetDlg->GetVPanel() : NULL; } //----------------------------------------------------------------------------- // Purpose: sets the parent panel of the main module panel //----------------------------------------------------------------------------- void CServerBrowser::SetParent(vgui::VPANEL parent) { if (m_hInternetDlg.Get()) { m_hInternetDlg->SetParent(parent); } } //----------------------------------------------------------------------------- // Purpose: Closes down the server browser for good //----------------------------------------------------------------------------- void CServerBrowser::Shutdown() { if (m_hInternetDlg.Get()) { m_hInternetDlg->Close(); m_hInternetDlg->MarkForDeletion(); } #if defined( STEAM ) vgui::VGuiControls_Shutdown(); #endif DisconnectTier3Libraries(); DisconnectTier2Libraries(); ConVar_Unregister(); DisconnectTier1Libraries(); } //----------------------------------------------------------------------------- // Purpose: opens a game info dialog to watch the specified server; associated with the friend 'userName' //----------------------------------------------------------------------------- bool CServerBrowser::OpenGameInfoDialog( uint64 ulSteamIDFriend, const char *pszConnectCode ) { #if !defined( _X360 ) // X360TBD: SteamFriends() if ( m_hInternetDlg.Get() ) { // activate an already-existing dialog CDialogGameInfo *pDialogGameInfo = m_hInternetDlg->GetDialogGameInfoForFriend( ulSteamIDFriend ); if ( pDialogGameInfo ) { pDialogGameInfo->Activate(); return true; } // none yet, create a new dialog FriendGameInfo_t friendGameInfo; if ( steamapicontext->SteamFriends()->GetFriendGamePlayed( ulSteamIDFriend, &friendGameInfo ) ) { uint16 usConnPort = friendGameInfo.m_usGamePort; if ( friendGameInfo.m_usQueryPort < QUERY_PORT_ERROR ) usConnPort = friendGameInfo.m_usQueryPort; CDialogGameInfo *pDialogGameInfo = m_hInternetDlg->OpenGameInfoDialog( friendGameInfo.m_unGameIP, friendGameInfo.m_usGamePort, usConnPort, pszConnectCode ); pDialogGameInfo->SetFriend( ulSteamIDFriend ); return true; } } #endif return false; } //----------------------------------------------------------------------------- // Purpose: joins a specified game - game info dialog will only be opened if the server is fully or passworded //----------------------------------------------------------------------------- bool CServerBrowser::JoinGame( uint64 ulSteamIDFriend, const char *pszConnectCode ) { if ( OpenGameInfoDialog( ulSteamIDFriend, pszConnectCode ) ) { CDialogGameInfo *pDialogGameInfo = m_hInternetDlg->GetDialogGameInfoForFriend( ulSteamIDFriend ); pDialogGameInfo->Connect(); } return false; } //----------------------------------------------------------------------------- // Purpose: joins a game by IP/Port //----------------------------------------------------------------------------- bool CServerBrowser::JoinGame( uint32 unGameIP, uint16 usGamePort, const char *pszConnectCode ) { m_hInternetDlg->JoinGame( unGameIP, usGamePort, pszConnectCode ); return true; } //----------------------------------------------------------------------------- // Purpose: forces the game info dialog closed //----------------------------------------------------------------------------- void CServerBrowser::CloseGameInfoDialog( uint64 ulSteamIDFriend ) { CDialogGameInfo *pDialogGameInfo = m_hInternetDlg->GetDialogGameInfoForFriend( ulSteamIDFriend ); if ( pDialogGameInfo ) { pDialogGameInfo->Close(); } } //----------------------------------------------------------------------------- // Purpose: closes all the game info dialogs //----------------------------------------------------------------------------- void CServerBrowser::CloseAllGameInfoDialogs() { if ( m_hInternetDlg.Get() ) { m_hInternetDlg->CloseAllGameInfoDialogs(); } } CUtlVector< gametypes_t > g_GameTypes; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void LoadGameTypes( void ) { if ( g_GameTypes.Count() > 0 ) return; #define GAMETYPES_FILE "servers/ServerBrowserGameTypes.txt" KeyValues * kv = new KeyValues( GAMETYPES_FILE ); if ( !kv->LoadFromFile( g_pFullFileSystem, GAMETYPES_FILE, "MOD" ) ) { kv->deleteThis(); return; } g_GameTypes.RemoveAll(); for ( KeyValues *pData = kv->GetFirstSubKey(); pData != NULL; pData = pData->GetNextKey() ) { gametypes_t gametype; gametype.pPrefix = CloneString( pData->GetString( "prefix", "" ) ); gametype.pGametypeName = CloneString( pData->GetString( "name", "" ) ); g_GameTypes.AddToTail( gametype ); } kv->deleteThis(); } const char *GetGameTypeName( const char *pMapName ) { LoadGameTypes(); for ( int i = 0; i < g_GameTypes.Count(); i++ ) { int iLength = strlen( g_GameTypes[i].pPrefix ); if ( !Q_strncmp( pMapName, g_GameTypes[i].pPrefix, iLength ) ) { return g_GameTypes[i].pGametypeName; } } return ""; } //----------------------------------------------------------------------------- // Purpose of comments like these: none //----------------------------------------------------------------------------- const char *CServerBrowser::GetMapFriendlyNameAndGameType( const char *pszMapName, char *szFriendlyMapName, int cchFriendlyName ) { // Make sure game types are loaded LoadGameTypes(); // Scan list const char *pszFriendlyGameTypeName = ""; for ( int i = 0; i < g_GameTypes.Count(); i++ ) { int iLength = strlen( g_GameTypes[i].pPrefix ); if ( !Q_strnicmp( pszMapName, g_GameTypes[i].pPrefix, iLength ) ) { pszMapName += iLength; pszFriendlyGameTypeName = g_GameTypes[i].pGametypeName; break; } } // See how many characters from the name to copy. // Start by assuming we'll copy the whole thing. // (After any prefix we just skipped) int l = V_strlen( pszMapName ); const char *pszFinal = Q_stristr( pszMapName, "_final" ); if ( pszFinal ) { // truncate the _final (or _final1) part of the filename if it's at the end of the name const char *pszNextChar = pszFinal + Q_strlen( "_final" ); if ( ( *pszNextChar == '\0' ) || ( ( *pszNextChar == '1' ) && ( *(pszNextChar+1) == '\0' ) ) ) { l = pszFinal - pszMapName; } } // Safety check against buffer size if ( l >= cchFriendlyName ) { Assert( !"Map name too long for buffer!" ); l = cchFriendlyName-1; } // Copy friendly portion of name only V_memcpy( szFriendlyMapName, pszMapName, l ); // It's like the Alamo. We never forget. szFriendlyMapName[l] = '\0'; // Result should be the friendly game type name return pszFriendlyGameTypeName; }
/*****************************************************************************/ /* SFileVerify.cpp Copyright (c) Ladislav Zezula 2010 */ /*---------------------------------------------------------------------------*/ /* MPQ files and MPQ archives verification. */ /* */ /* The MPQ signature verification has been written by Jean-Francois Roy */ /* <bahamut@macstorm.org> and Justin Olbrantz (Quantam). */ /* The MPQ public keys have been created by MPQKit, using OpenSSL library. */ /* */ /*---------------------------------------------------------------------------*/ /* Date Ver Who Comment */ /* -------- ---- --- ------- */ /* 04.05.10 1.00 Lad The first version of SFileVerify.cpp */ /*****************************************************************************/ #define __STORMLIB_SELF__ #include "StormLib.h" #include "StormCommon.h" //----------------------------------------------------------------------------- // Local defines #define SIGNATURE_TYPE_NONE 0 #define SIGNATURE_TYPE_WEAK 1 #define SIGNATURE_TYPE_STRONG 2 #define MPQ_DIGEST_UNIT_SIZE 0x10000 typedef struct _MPQ_SIGNATURE_INFO { ULONGLONG BeginMpqData; // File offset where the hashing starts ULONGLONG BeginExclude; // Begin of the excluded area (used for (signature) file) ULONGLONG EndExclude; // End of the excluded area (used for (signature) file) ULONGLONG EndMpqData; // File offset where the hashing ends ULONGLONG EndOfFile; // Size of the entire file BYTE Signature[MPQ_STRONG_SIGNATURE_SIZE + 0x10]; DWORD cbSignatureSize; // Length of the signature int nSignatureType; // See SIGNATURE_TYPE_XXX } MPQ_SIGNATURE_INFO, *PMPQ_SIGNATURE_INFO; //----------------------------------------------------------------------------- // Known Blizzard public keys // Created by Jean-Francois Roy using OpenSSL static const char * szBlizzardWeakPublicKey = "-----BEGIN PUBLIC KEY-----" "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJJidwS/uILMBSO5DLGsBFknIXWWjQJe" "2kfdfEk3G/j66w4KkhZ1V61Rt4zLaMVCYpDun7FLwRjkMDSepO1q2DcCAwEAAQ==" "-----END PUBLIC KEY-----"; static const char * szBlizzardStrongPublicKey = "-----BEGIN PUBLIC KEY-----" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsQZ+ziT2h8h+J/iMQpgd" "tH1HaJzOBE3agjU4yMPcrixaPOZoA4t8bwfey7qczfWywocYo3pleytFF+IuD4HD" "Fl9OXN1SFyupSgMx1EGZlgbFAomnbq9MQJyMqQtMhRAjFgg4TndS7YNb+JMSAEKp" "kXNqY28n/EVBHD5TsMuVCL579gIenbr61dI92DDEdy790IzIG0VKWLh/KOTcTJfm" "Ds/7HQTkGouVW+WUsfekuqNQo7ND9DBnhLjLjptxeFE2AZqYcA1ao3S9LN3GL1tW" "lVXFIX9c7fWqaVTQlZ2oNsI/ARVApOK3grNgqvwH6YoVYVXjNJEo5sQJsPsdV/hk" "dwIDAQAB" "-----END PUBLIC KEY-----"; static const char * szWarcraft3MapPublicKey = "-----BEGIN PUBLIC KEY-----" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1BwklUUQ3UvjizOBRoF5" "yyOVc7KD+oGOQH5i6eUk1yfs0luCC70kNucNrfqhmviywVtahRse1JtXCPrx2bd3" "iN8Dx91fbkxjYIOGTsjYoHKTp0BbaFkJih776fcHgnFSb+7mJcDuJVvJOXxEH6w0" "1vo6VtujCqj1arqbyoal+xtAaczF3us5cOEp45sR1zAWTn1+7omN7VWV4QqJPaDS" "gBSESc0l1grO0i1VUSumayk7yBKIkb+LBvcG6WnYZHCi7VdLmaxER5m8oZfER66b" "heHoiSQIZf9PAY6Guw2DT5BTc54j/AaLQAKf2qcRSgQLVo5kQaddF3rCpsXoB/74" "6QIDAQAB" "-----END PUBLIC KEY-----"; static const char * szWowPatchPublicKey = "-----BEGIN PUBLIC KEY-----" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwOsMV0LagAWPEtEQM6b9" "6FHFkUyGbbyda2/Dfc9dyl21E9QvX+Yw7qKRMAKPzA2TlQQLZKvXpnKXF/YIK5xa" "5uwg9CEHCEAYolLG4xn0FUOE0E/0PuuytI0p0ICe6rk00PifZzTr8na2wI/l/GnQ" "bvnIVF1ck6cslATpQJ5JJVMXzoFlUABS19WESw4MXuJAS3AbMhxNWdEhVv7eO51c" "yGjRLy9QjogZODZTY0fSEksgBqQxNCoYVJYI/sF5K2flDsGqrIp0OdJ6teJlzg1Y" "UjYnb6bKjlidXoHEXI2TgA/mD6O3XFIt08I9s3crOCTgICq7cgX35qrZiIVWZdRv" "TwIDAQAB" "-----END PUBLIC KEY-----"; static const char * szWowSurveyPublicKey = "-----BEGIN PUBLIC KEY-----" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnIt1DR6nRyyKsy2qahHe" "MKLtacatn/KxieHcwH87wLBxKy+jZ0gycTmJ7SaTdBAEMDs/V5IPIXEtoqYnid2c" "63TmfGDU92oc3Ph1PWUZ2PWxBhT06HYxRdbrgHw9/I29pNPi/607x+lzPORITOgU" "BR6MR8au8HsQP4bn4vkJNgnSgojh48/XQOB/cAln7As1neP61NmVimoLR4Bwi3zt" "zfgrZaUpyeNCUrOYJmH09YIjbBySTtXOUidoPHjFrMsCWpr6xs8xbETbs7MJFL6a" "vcUfTT67qfIZ9RsuKfnXJTIrV0kwDSjjuNXiPTmWAehSsiHIsrUXX5RNcwsSjClr" "nQIDAQAB" "-----END PUBLIC KEY-----"; static const char * szStarcraft2MapPublicKey = "-----BEGIN PUBLIC KEY-----" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmk4GT8zb+ICC25a17KZB" "q/ygKGJ2VSO6IT5PGHJlm1KfnHBA4B6SH3xMlJ4c6eG2k7QevZv+FOhjsAHubyWq" "2VKqWbrIFKv2ILc2RfMn8J9EDVRxvcxh6slRrVL69D0w1tfVGjMiKq2Fym5yGoRT" "E7CRgDqbAbXP9LBsCNWHiJLwfxMGzHbk8pIl9oia5pvM7ofZamSHchxlpy6xa4GJ" "7xKN01YCNvklTL1D7uol3wkwcHc7vrF8QwuJizuA5bSg4poEGtH62BZOYi+UL/z0" "31YK+k9CbQyM0X0pJoJoYz1TK+Y5J7vBnXCZtfcTYQ/ZzN6UcxTa57dJaiOlCh9z" "nQIDAQAB" "-----END PUBLIC KEY-----"; //----------------------------------------------------------------------------- // Local functions static void memrev(unsigned char *buf, size_t count) { unsigned char *r; for (r = buf + count - 1; buf < r; buf++, r--) { *buf ^= *r; *r ^= *buf; *buf ^= *r; } } static bool is_valid_md5(void * pvMd5) { LPDWORD Md5 = (LPDWORD)pvMd5; return (Md5[0] | Md5[1] | Md5[2] | Md5[3]) ? true : false; } static bool decode_base64_key(const char * szKeyBase64, rsa_key * key) { unsigned char decoded_key[0x200]; const char * szBase64Begin; const char * szBase64End; unsigned long decoded_length = sizeof(decoded_key); unsigned long length; // Find out the begin of the BASE64 data szBase64Begin = szKeyBase64 + strlen("-----BEGIN PUBLIC KEY-----"); szBase64End = szBase64Begin + strlen(szBase64Begin) - strlen("-----END PUBLIC KEY-----"); if(szBase64End[0] != '-') return false; // decode the base64 string length = (unsigned long)(szBase64End - szBase64Begin); if(base64_decode((unsigned char *)szBase64Begin, length, decoded_key, &decoded_length) != CRYPT_OK) return false; // Create RSA key if(rsa_import(decoded_key, decoded_length, key) != CRYPT_OK) return false; return true; } static void GetPlainAnsiFileName( const TCHAR * szFileName, char * szPlainName) { const TCHAR * szPlainNameT = GetPlainFileNameT(szFileName); // Convert the plain name to ANSI while(*szPlainNameT != 0) *szPlainName++ = (char)*szPlainNameT++; *szPlainName = 0; } // Calculate begin and end of the MPQ archive static void CalculateArchiveRange( TMPQArchive * ha, PMPQ_SIGNATURE_INFO pSI) { ULONGLONG TempPos = 0; char szMapHeader[0x200]; // Get the MPQ begin pSI->BeginMpqData = ha->MpqPos; // Warcraft III maps are signed from the map header to the end if(FileStream_Read(ha->pStream, &TempPos, szMapHeader, sizeof(szMapHeader))) { // Is it a map header ? if(szMapHeader[0] == 'H' && szMapHeader[1] == 'M' && szMapHeader[2] == '3' && szMapHeader[3] == 'W') { // We will have to hash since the map header pSI->BeginMpqData = 0; } } // Get the MPQ data end. This is stored in our MPQ header, // and it's been already prepared by SFileOpenArchive, pSI->EndMpqData = ha->MpqPos + ha->pHeader->ArchiveSize64; // Get the size of the entire file FileStream_GetSize(ha->pStream, &pSI->EndOfFile); } static bool QueryMpqSignatureInfo( TMPQArchive * ha, PMPQ_SIGNATURE_INFO pSI) { ULONGLONG ExtraBytes; TMPQFile * hf; HANDLE hFile; DWORD dwFileSize; // Calculate the range of the MPQ CalculateArchiveRange(ha, pSI); // If there is "(signature)" file in the MPQ, it has a weak signature if(SFileOpenFileEx((HANDLE)ha, SIGNATURE_NAME, SFILE_OPEN_BASE_FILE, &hFile)) { // Get the content of the signature SFileReadFile(hFile, pSI->Signature, sizeof(pSI->Signature), &pSI->cbSignatureSize, NULL); // Verify the size of the signature hf = (TMPQFile *)hFile; // We have to exclude the signature file from the digest pSI->BeginExclude = ha->MpqPos + hf->pFileEntry->ByteOffset; pSI->EndExclude = pSI->BeginExclude + hf->pFileEntry->dwCmpSize; dwFileSize = hf->dwDataSize; // Close the file SFileCloseFile(hFile); pSI->nSignatureType = SIGNATURE_TYPE_WEAK; return (dwFileSize == (MPQ_WEAK_SIGNATURE_SIZE + 8)) ? true : false; } // If there is extra bytes beyond the end of the archive, // it's the strong signature ExtraBytes = pSI->EndOfFile - pSI->EndMpqData; if(ExtraBytes >= (MPQ_STRONG_SIGNATURE_SIZE + 4)) { // Read the strong signature if(!FileStream_Read(ha->pStream, &pSI->EndMpqData, pSI->Signature, (MPQ_STRONG_SIGNATURE_SIZE + 4))) return false; // Check the signature header "NGIS" if(pSI->Signature[0] != 'N' || pSI->Signature[1] != 'G' || pSI->Signature[2] != 'I' || pSI->Signature[3] != 'S') return false; pSI->nSignatureType = SIGNATURE_TYPE_STRONG; return true; } // Succeeded, but no known signature found return true; } static bool CalculateMpqHashMd5( TMPQArchive * ha, PMPQ_SIGNATURE_INFO pSI, LPBYTE pMd5Digest) { hash_state md5_state; ULONGLONG BeginBuffer; ULONGLONG EndBuffer; LPBYTE pbDigestBuffer = NULL; // Allocate buffer for creating the MPQ digest. pbDigestBuffer = STORM_ALLOC(BYTE, MPQ_DIGEST_UNIT_SIZE); if(pbDigestBuffer == NULL) return false; // Initialize the MD5 hash state md5_init(&md5_state); // Set the byte offset of begin of the data BeginBuffer = pSI->BeginMpqData; // Create the digest for(;;) { ULONGLONG BytesRemaining; LPBYTE pbSigBegin = NULL; LPBYTE pbSigEnd = NULL; DWORD dwToRead = MPQ_DIGEST_UNIT_SIZE; // Check the number of bytes remaining BytesRemaining = pSI->EndMpqData - BeginBuffer; if(BytesRemaining < MPQ_DIGEST_UNIT_SIZE) dwToRead = (DWORD)BytesRemaining; if(dwToRead == 0) break; // Read the next chunk if(!FileStream_Read(ha->pStream, &BeginBuffer, pbDigestBuffer, dwToRead)) { STORM_FREE(pbDigestBuffer); return false; } // Move the current byte offset EndBuffer = BeginBuffer + dwToRead; // Check if the signature is within the loaded digest if(BeginBuffer <= pSI->BeginExclude && pSI->BeginExclude < EndBuffer) pbSigBegin = pbDigestBuffer + (size_t)(pSI->BeginExclude - BeginBuffer); if(BeginBuffer <= pSI->EndExclude && pSI->EndExclude < EndBuffer) pbSigEnd = pbDigestBuffer + (size_t)(pSI->EndExclude - BeginBuffer); // Zero the part that belongs to the signature if(pbSigBegin != NULL || pbSigEnd != NULL) { if(pbSigBegin == NULL) pbSigBegin = pbDigestBuffer; if(pbSigEnd == NULL) pbSigEnd = pbDigestBuffer + dwToRead; memset(pbSigBegin, 0, (pbSigEnd - pbSigBegin)); } // Pass the buffer to the hashing function md5_process(&md5_state, pbDigestBuffer, dwToRead); // Move pointers BeginBuffer += dwToRead; } // Finalize the MD5 hash md5_done(&md5_state, pMd5Digest); STORM_FREE(pbDigestBuffer); return true; } static void AddTailToSha1( hash_state * psha1_state, const char * szTail) { unsigned char * pbTail = (unsigned char *)szTail; unsigned char szUpperCase[0x200]; unsigned long nLength = 0; // Convert the tail to uppercase // Note that we don't need to terminate the string with zero while(*pbTail != 0) { szUpperCase[nLength++] = AsciiToUpperTable[*pbTail++]; } // Append the tail to the SHA1 sha1_process(psha1_state, szUpperCase, nLength); } static bool CalculateMpqHashSha1( TMPQArchive * ha, PMPQ_SIGNATURE_INFO pSI, unsigned char * sha1_tail0, unsigned char * sha1_tail1, unsigned char * sha1_tail2) { ULONGLONG BeginBuffer; hash_state sha1_state_temp; hash_state sha1_state; LPBYTE pbDigestBuffer = NULL; char szPlainName[MAX_PATH]; // Allocate buffer for creating the MPQ digest. pbDigestBuffer = STORM_ALLOC(BYTE, MPQ_DIGEST_UNIT_SIZE); if(pbDigestBuffer == NULL) return false; // Initialize SHA1 state structure sha1_init(&sha1_state); // Calculate begin of data to be hashed BeginBuffer = pSI->BeginMpqData; // Create the digest for(;;) { ULONGLONG BytesRemaining; DWORD dwToRead = MPQ_DIGEST_UNIT_SIZE; // Check the number of bytes remaining BytesRemaining = pSI->EndMpqData - BeginBuffer; if(BytesRemaining < MPQ_DIGEST_UNIT_SIZE) dwToRead = (DWORD)BytesRemaining; if(dwToRead == 0) break; // Read the next chunk if(!FileStream_Read(ha->pStream, &BeginBuffer, pbDigestBuffer, dwToRead)) { STORM_FREE(pbDigestBuffer); return false; } // Pass the buffer to the hashing function sha1_process(&sha1_state, pbDigestBuffer, dwToRead); // Move pointers BeginBuffer += dwToRead; } // Add all three known tails and generate three hashes memcpy(&sha1_state_temp, &sha1_state, sizeof(hash_state)); sha1_done(&sha1_state_temp, sha1_tail0); memcpy(&sha1_state_temp, &sha1_state, sizeof(hash_state)); GetPlainAnsiFileName(FileStream_GetFileName(ha->pStream), szPlainName); AddTailToSha1(&sha1_state_temp, szPlainName); sha1_done(&sha1_state_temp, sha1_tail1); memcpy(&sha1_state_temp, &sha1_state, sizeof(hash_state)); AddTailToSha1(&sha1_state_temp, "ARCHIVE"); sha1_done(&sha1_state_temp, sha1_tail2); // Finalize the MD5 hash STORM_FREE(pbDigestBuffer); return true; } static int VerifyRawMpqData( TMPQArchive * ha, ULONGLONG ByteOffset, DWORD dwDataSize) { ULONGLONG DataOffset = ha->MpqPos + ByteOffset; LPBYTE pbDataChunk; LPBYTE pbMD5Array1; // Calculated MD5 array LPBYTE pbMD5Array2; // MD5 array loaded from the MPQ DWORD dwBytesInChunk; DWORD dwChunkCount; DWORD dwChunkSize = ha->pHeader->dwRawChunkSize; DWORD dwMD5Size; int nError = ERROR_SUCCESS; // Don't verify zero-sized blocks if(dwDataSize == 0) return ERROR_SUCCESS; // Get the number of data chunks to calculate MD5 assert(dwChunkSize != 0); dwChunkCount = ((dwDataSize - 1) / dwChunkSize) + 1; dwMD5Size = dwChunkCount * MD5_DIGEST_SIZE; // Allocate space for data chunk and for the MD5 array pbDataChunk = STORM_ALLOC(BYTE, dwChunkSize); if(pbDataChunk == NULL) return ERROR_NOT_ENOUGH_MEMORY; // Allocate space for MD5 array pbMD5Array1 = STORM_ALLOC(BYTE, dwMD5Size); pbMD5Array2 = STORM_ALLOC(BYTE, dwMD5Size); if(pbMD5Array1 == NULL || pbMD5Array2 == NULL) nError = ERROR_NOT_ENOUGH_MEMORY; // Calculate MD5 of each data chunk if(nError == ERROR_SUCCESS) { LPBYTE pbMD5 = pbMD5Array1; for(DWORD i = 0; i < dwChunkCount; i++) { // Get the number of bytes in the chunk dwBytesInChunk = STORMLIB_MIN(dwChunkSize, dwDataSize); // Read the data chunk if(!FileStream_Read(ha->pStream, &DataOffset, pbDataChunk, dwBytesInChunk)) { nError = ERROR_FILE_CORRUPT; break; } // Calculate MD5 CalculateDataBlockHash(pbDataChunk, dwBytesInChunk, pbMD5); // Move pointers and offsets DataOffset += dwBytesInChunk; dwDataSize -= dwBytesInChunk; pbMD5 += MD5_DIGEST_SIZE; } } // Read the MD5 array if(nError == ERROR_SUCCESS) { // Read the array of MD5 if(!FileStream_Read(ha->pStream, &DataOffset, pbMD5Array2, dwMD5Size)) nError = GetLastError(); } // Compare the array of MD5 if(nError == ERROR_SUCCESS) { // Compare the MD5 if(memcmp(pbMD5Array1, pbMD5Array2, dwMD5Size)) nError = ERROR_FILE_CORRUPT; } // Free memory and return result if(pbMD5Array2 != NULL) STORM_FREE(pbMD5Array2); if(pbMD5Array1 != NULL) STORM_FREE(pbMD5Array1); if(pbDataChunk != NULL) STORM_FREE(pbDataChunk); return nError; } static DWORD VerifyWeakSignature( TMPQArchive * ha, PMPQ_SIGNATURE_INFO pSI) { BYTE RevSignature[MPQ_WEAK_SIGNATURE_SIZE]; BYTE Md5Digest[MD5_DIGEST_SIZE]; rsa_key key; int hash_idx = find_hash("md5"); int result = 0; // Calculate hash of the entire archive, skipping the (signature) file if(!CalculateMpqHashMd5(ha, pSI, Md5Digest)) return ERROR_VERIFY_FAILED; // Import the Blizzard key in OpenSSL format if(!decode_base64_key(szBlizzardWeakPublicKey, &key)) return ERROR_VERIFY_FAILED; // Verify the signature memcpy(RevSignature, &pSI->Signature[8], MPQ_WEAK_SIGNATURE_SIZE); memrev(RevSignature, MPQ_WEAK_SIGNATURE_SIZE); rsa_verify_hash_ex(RevSignature, MPQ_WEAK_SIGNATURE_SIZE, Md5Digest, sizeof(Md5Digest), LTC_LTC_PKCS_1_V1_5, hash_idx, 0, &result, &key); rsa_free(&key); // Return the result return result ? ERROR_WEAK_SIGNATURE_OK : ERROR_WEAK_SIGNATURE_ERROR; } static DWORD VerifyStrongSignatureWithKey( unsigned char * reversed_signature, unsigned char * padded_digest, const char * szPublicKey) { rsa_key key; int result = 0; // Import the Blizzard key in OpenSSL format if(!decode_base64_key(szPublicKey, &key)) { assert(false); return ERROR_VERIFY_FAILED; } // Verify the signature if(rsa_verify_simple(reversed_signature, MPQ_STRONG_SIGNATURE_SIZE, padded_digest, MPQ_STRONG_SIGNATURE_SIZE, &result, &key) != CRYPT_OK) return ERROR_VERIFY_FAILED; // Free the key and return result rsa_free(&key); return result ? ERROR_STRONG_SIGNATURE_OK : ERROR_STRONG_SIGNATURE_ERROR; } static DWORD VerifyStrongSignature( TMPQArchive * ha, PMPQ_SIGNATURE_INFO pSI) { unsigned char reversed_signature[MPQ_STRONG_SIGNATURE_SIZE]; unsigned char Sha1Digest_tail0[SHA1_DIGEST_SIZE]; unsigned char Sha1Digest_tail1[SHA1_DIGEST_SIZE]; unsigned char Sha1Digest_tail2[SHA1_DIGEST_SIZE]; unsigned char padded_digest[MPQ_STRONG_SIGNATURE_SIZE]; DWORD dwResult; size_t digest_offset; // Calculate SHA1 hash of the archive if(!CalculateMpqHashSha1(ha, pSI, Sha1Digest_tail0, Sha1Digest_tail1, Sha1Digest_tail2)) return ERROR_VERIFY_FAILED; // Prepare the signature for decryption memcpy(reversed_signature, &pSI->Signature[4], MPQ_STRONG_SIGNATURE_SIZE); memrev(reversed_signature, MPQ_STRONG_SIGNATURE_SIZE); // Prepare the padded digest for comparison digest_offset = sizeof(padded_digest) - SHA1_DIGEST_SIZE; memset(padded_digest, 0xbb, digest_offset); padded_digest[0] = 0x0b; // Try Blizzard Strong public key with no SHA1 tail memcpy(padded_digest + digest_offset, Sha1Digest_tail0, SHA1_DIGEST_SIZE); memrev(padded_digest + digest_offset, SHA1_DIGEST_SIZE); dwResult = VerifyStrongSignatureWithKey(reversed_signature, padded_digest, szBlizzardStrongPublicKey); if(dwResult == ERROR_STRONG_SIGNATURE_OK) return dwResult; // Try War 3 map public key with plain file name as SHA1 tail memcpy(padded_digest + digest_offset, Sha1Digest_tail1, SHA1_DIGEST_SIZE); memrev(padded_digest + digest_offset, SHA1_DIGEST_SIZE); dwResult = VerifyStrongSignatureWithKey(reversed_signature, padded_digest, szWarcraft3MapPublicKey); if(dwResult == ERROR_STRONG_SIGNATURE_OK) return dwResult; // Try WoW-TBC public key with "ARCHIVE" as SHA1 tail memcpy(padded_digest + digest_offset, Sha1Digest_tail2, SHA1_DIGEST_SIZE); memrev(padded_digest + digest_offset, SHA1_DIGEST_SIZE); dwResult = VerifyStrongSignatureWithKey(reversed_signature, padded_digest, szWowPatchPublicKey); if(dwResult == ERROR_STRONG_SIGNATURE_OK) return dwResult; // Try Survey public key with no SHA1 tail memcpy(padded_digest + digest_offset, Sha1Digest_tail0, SHA1_DIGEST_SIZE); memrev(padded_digest + digest_offset, SHA1_DIGEST_SIZE); dwResult = VerifyStrongSignatureWithKey(reversed_signature, padded_digest, szWowSurveyPublicKey); if(dwResult == ERROR_STRONG_SIGNATURE_OK) return dwResult; // Try Starcraft II public key with no SHA1 tail memcpy(padded_digest + digest_offset, Sha1Digest_tail0, SHA1_DIGEST_SIZE); memrev(padded_digest + digest_offset, SHA1_DIGEST_SIZE); dwResult = VerifyStrongSignatureWithKey(reversed_signature, padded_digest, szStarcraft2MapPublicKey); if(dwResult == ERROR_STRONG_SIGNATURE_OK) return dwResult; return ERROR_STRONG_SIGNATURE_ERROR; } static DWORD VerifyFile( HANDLE hMpq, const char * szFileName, LPDWORD pdwCrc32, char * pMD5, DWORD dwFlags) { hash_state md5_state; unsigned char * pFileMd5; unsigned char md5[MD5_DIGEST_SIZE]; TFileEntry * pFileEntry; TMPQFile * hf; BYTE Buffer[0x1000]; HANDLE hFile = NULL; DWORD dwVerifyResult = 0; DWORD dwTotalBytes = 0; DWORD dwBytesRead; DWORD dwCrc32 = 0; // // Note: When the MPQ is patched, it will // automatically check the patched version of the file // // If we have to verify raw data MD5, do it before file open if(dwFlags & SFILE_VERIFY_RAW_MD5) { TMPQArchive * ha = (TMPQArchive *)hMpq; // Parse the base MPQ and all patches while(ha != NULL) { // Does the archive have support for raw MD5? if(ha->pHeader->dwRawChunkSize != 0) { // The file has raw MD5 if the archive supports it dwVerifyResult |= VERIFY_FILE_HAS_RAW_MD5; // Find file entry for the file pFileEntry = GetFileEntryLocale(ha, szFileName, lcFileLocale); if(pFileEntry != NULL) { // If the file's raw MD5 doesn't match, don't bother with more checks if(VerifyRawMpqData(ha, pFileEntry->ByteOffset, pFileEntry->dwCmpSize) != ERROR_SUCCESS) return dwVerifyResult | VERIFY_FILE_RAW_MD5_ERROR; } } // Move to the next patch ha = ha->haPatch; } } // Attempt to open the file if(SFileOpenFileEx(hMpq, szFileName, SFILE_OPEN_FROM_MPQ, &hFile)) { // Get the file size hf = (TMPQFile *)hFile; pFileEntry = hf->pFileEntry; dwTotalBytes = SFileGetFileSize(hFile, NULL); // Initialize the CRC32 and MD5 contexts md5_init(&md5_state); dwCrc32 = crc32(0, Z_NULL, 0); // Also turn on sector checksum verification if(dwFlags & SFILE_VERIFY_SECTOR_CRC) hf->bCheckSectorCRCs = true; // Go through entire file and update both CRC32 and MD5 for(;;) { // Read data from file SFileReadFile(hFile, Buffer, sizeof(Buffer), &dwBytesRead, NULL); if(dwBytesRead == 0) { if(GetLastError() == ERROR_CHECKSUM_ERROR) dwVerifyResult |= VERIFY_FILE_SECTOR_CRC_ERROR; break; } // Update CRC32 value if(dwFlags & SFILE_VERIFY_FILE_CRC) dwCrc32 = crc32(dwCrc32, Buffer, dwBytesRead); // Update MD5 value if(dwFlags & SFILE_VERIFY_FILE_MD5) md5_process(&md5_state, Buffer, dwBytesRead); // Decrement the total size dwTotalBytes -= dwBytesRead; } // If the file has sector checksums, indicate it in the flags if(dwFlags & SFILE_VERIFY_SECTOR_CRC) { if((hf->pFileEntry->dwFlags & MPQ_FILE_SECTOR_CRC) && hf->SectorChksums != NULL && hf->SectorChksums[0] != 0) dwVerifyResult |= VERIFY_FILE_HAS_SECTOR_CRC; } // Check if the entire file has been read // No point in checking CRC32 and MD5 if not // Skip checksum checks if the file has patches if(dwTotalBytes == 0) { // Check CRC32 and MD5 only if there is no patches if(hf->hfPatchFile == NULL) { // Check if the CRC32 matches. if(dwFlags & SFILE_VERIFY_FILE_CRC) { // Only check the CRC32 if it is valid if(pFileEntry->dwCrc32 != 0) { dwVerifyResult |= VERIFY_FILE_HAS_CHECKSUM; if(dwCrc32 != pFileEntry->dwCrc32) dwVerifyResult |= VERIFY_FILE_CHECKSUM_ERROR; } } // Check if MD5 matches if(dwFlags & SFILE_VERIFY_FILE_MD5) { // Patch files have their MD5 saved in the patch info pFileMd5 = (hf->pPatchInfo != NULL) ? hf->pPatchInfo->md5 : pFileEntry->md5; md5_done(&md5_state, md5); // Only check the MD5 if it is valid if(is_valid_md5(pFileMd5)) { dwVerifyResult |= VERIFY_FILE_HAS_MD5; if(memcmp(md5, pFileMd5, MD5_DIGEST_SIZE)) dwVerifyResult |= VERIFY_FILE_MD5_ERROR; } } } else { // Patched files are MD5-checked automatically dwVerifyResult |= VERIFY_FILE_HAS_MD5; } } else { dwVerifyResult |= VERIFY_READ_ERROR; } SFileCloseFile(hFile); } else { // Remember that the file couldn't be open dwVerifyResult |= VERIFY_OPEN_ERROR; } // If the caller required CRC32 and/or MD5, give it to him if(pdwCrc32 != NULL) *pdwCrc32 = dwCrc32; if(pMD5 != NULL) memcpy(pMD5, md5, MD5_DIGEST_SIZE); return dwVerifyResult; } //----------------------------------------------------------------------------- // Public (exported) functions bool WINAPI SFileGetFileChecksums(HANDLE hMpq, const char * szFileName, LPDWORD pdwCrc32, char * pMD5) { DWORD dwVerifyResult; DWORD dwVerifyFlags = 0; if(pdwCrc32 != NULL) dwVerifyFlags |= SFILE_VERIFY_FILE_CRC; if(pMD5 != NULL) dwVerifyFlags |= SFILE_VERIFY_FILE_MD5; dwVerifyResult = VerifyFile(hMpq, szFileName, pdwCrc32, pMD5, dwVerifyFlags); // If verification failed, return zero if(dwVerifyResult & VERIFY_FILE_ERROR_MASK) { SetLastError(ERROR_FILE_CORRUPT); return false; } return true; } DWORD WINAPI SFileVerifyFile(HANDLE hMpq, const char * szFileName, DWORD dwFlags) { return VerifyFile(hMpq, szFileName, NULL, NULL, dwFlags); } // Verifies raw data of the archive Only works for MPQs version 4 or newer int WINAPI SFileVerifyRawData(HANDLE hMpq, DWORD dwWhatToVerify, const char * szFileName) { TMPQArchive * ha = (TMPQArchive *)hMpq; TFileEntry * pFileEntry; TMPQHeader * pHeader; // Verify input parameters if(!IsValidMpqHandle(ha)) return ERROR_INVALID_PARAMETER; pHeader = ha->pHeader; // If the archive doesn't have raw data MD5, report it as OK if(pHeader->dwRawChunkSize == 0) return ERROR_SUCCESS; // If we have to verify MPQ header, do it switch(dwWhatToVerify) { case SFILE_VERIFY_MPQ_HEADER: // Only if the header is of version 4 or newer if(pHeader->dwHeaderSize >= (MPQ_HEADER_SIZE_V4 - MD5_DIGEST_SIZE)) return VerifyRawMpqData(ha, 0, MPQ_HEADER_SIZE_V4 - MD5_DIGEST_SIZE); return ERROR_SUCCESS; case SFILE_VERIFY_HET_TABLE: // Only if we have HET table if(pHeader->HetTablePos64 && pHeader->HetTableSize64) return VerifyRawMpqData(ha, pHeader->HetTablePos64, (DWORD)pHeader->HetTableSize64); return ERROR_SUCCESS; case SFILE_VERIFY_BET_TABLE: // Only if we have BET table if(pHeader->BetTablePos64 && pHeader->BetTableSize64) return VerifyRawMpqData(ha, pHeader->BetTablePos64, (DWORD)pHeader->BetTableSize64); return ERROR_SUCCESS; case SFILE_VERIFY_HASH_TABLE: // Hash table is not protected by MD5 return ERROR_SUCCESS; case SFILE_VERIFY_BLOCK_TABLE: // Block table is not protected by MD5 return ERROR_SUCCESS; case SFILE_VERIFY_HIBLOCK_TABLE: // It is unknown if the hi-block table is protected my MD5 or not. return ERROR_SUCCESS; case SFILE_VERIFY_FILE: // Verify parameters if(szFileName == NULL || *szFileName == 0) return ERROR_INVALID_PARAMETER; // Get the offset of a file pFileEntry = GetFileEntryLocale(ha, szFileName, lcFileLocale); if(pFileEntry == NULL) return ERROR_FILE_NOT_FOUND; return VerifyRawMpqData(ha, pFileEntry->ByteOffset, pFileEntry->dwCmpSize); } return ERROR_INVALID_PARAMETER; } // Verifies the archive against the signature DWORD WINAPI SFileVerifyArchive(HANDLE hMpq) { MPQ_SIGNATURE_INFO si; TMPQArchive * ha = (TMPQArchive *)hMpq; // Verify input parameters if(!IsValidMpqHandle(ha)) return ERROR_VERIFY_FAILED; // Get the MPQ signature and signature type memset(&si, 0, sizeof(MPQ_SIGNATURE_INFO)); if(!QueryMpqSignatureInfo(ha, &si)) return ERROR_VERIFY_FAILED; // Verify the signature switch(si.nSignatureType) { case SIGNATURE_TYPE_NONE: return ERROR_NO_SIGNATURE; case SIGNATURE_TYPE_WEAK: return VerifyWeakSignature(ha, &si); case SIGNATURE_TYPE_STRONG: return VerifyStrongSignature(ha, &si); } return ERROR_VERIFY_FAILED; }
#include "llvm/Support/BlockFrequency.h" #include "llvm/Support/BranchProbability.h" #include "llvm/Support/DataTypes.h" #include "gtest/gtest.h" #include <climits> using namespace llvm; namespace { TEST(BlockFrequencyTest, OneToZero) { BlockFrequency Freq(1); BranchProbability Prob(UINT32_MAX - 1, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 0u); } TEST(BlockFrequencyTest, OneToOne) { BlockFrequency Freq(1); BranchProbability Prob(UINT32_MAX, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 1u); } TEST(BlockFrequencyTest, ThreeToOne) { BlockFrequency Freq(3); BranchProbability Prob(3000000, 9000000); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 1u); } TEST(BlockFrequencyTest, MaxToHalfMax) { BlockFrequency Freq(UINT64_MAX); BranchProbability Prob(UINT32_MAX / 2, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 9223372034707292159ULL); } TEST(BlockFrequencyTest, BigToBig) { const uint64_t Big = 387246523487234346LL; const uint32_t P = 123456789; BlockFrequency Freq(Big); BranchProbability Prob(P, P); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), Big); } TEST(BlockFrequencyTest, MaxToMax) { BlockFrequency Freq(UINT64_MAX); BranchProbability Prob(UINT32_MAX, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), UINT64_MAX); } TEST(BlockFrequencyTest, ProbabilityCompare) { BranchProbability A(4, 5); BranchProbability B(4U << 29, 5U << 29); BranchProbability C(3, 4); EXPECT_TRUE(A == B); EXPECT_FALSE(A != B); EXPECT_FALSE(A < B); EXPECT_FALSE(A > B); EXPECT_TRUE(A <= B); EXPECT_TRUE(A >= B); EXPECT_FALSE(B == C); EXPECT_TRUE(B != C); EXPECT_FALSE(B < C); EXPECT_TRUE(B > C); EXPECT_FALSE(B <= C); EXPECT_TRUE(B >= C); BranchProbability BigZero(0, UINT32_MAX); BranchProbability BigOne(UINT32_MAX, UINT32_MAX); EXPECT_FALSE(BigZero == BigOne); EXPECT_TRUE(BigZero != BigOne); EXPECT_TRUE(BigZero < BigOne); EXPECT_FALSE(BigZero > BigOne); EXPECT_TRUE(BigZero <= BigOne); EXPECT_FALSE(BigZero >= BigOne); } }
#include "viruspch.h" #include "resource.h" #include "vrsscan.h" #include "util.h" #include "virusmn.h" #include "virusfct.h" // virumn.cpp -- autmatic registration and unregistration // LONG g_cDllRef = 0; // per-instance CRITICAL_SECTION g_cs = {0}; // per-instance HINSTANCE g_hinst = NULL; TCHAR g_szTitle[SMALL_BUF]; OBJECTINFO g_ObjectInfo[] = { { NULL, &CLSID_VirusScan, NULL, OI_COCREATEABLE, "VirusScan", MAKEINTRESOURCE(IDS_VIRUSCHECK), NULL, NULL, VERSION_0, 0, 0 }, { NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, 0, 0, 0 }, } ; STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppv) { if((riid == IID_IClassFactory) || (riid == IID_IUnknown)) { const OBJECTINFO *pcls; for (pcls = g_ObjectInfo; pcls->pclsid; pcls++) { if(rclsid == *pcls->pclsid) { *ppv = pcls->cf; ((IUnknown *)*ppv)->AddRef(); return NOERROR; } } } *ppv = NULL; return CLASS_E_CLASSNOTAVAILABLE; } STDAPI DllCanUnloadNow(void) { if (g_cDllRef) return S_FALSE; return S_OK; } void InitClassFactories() { pcf = new CVirusFactory(); g_ObjectInfo[0].cf = (void *)pcf; } void DeleteClassFactories() { delete pcf; } STDAPI_(BOOL) DllMain(HANDLE hDll, DWORD dwReason, void *lpReserved) { switch(dwReason) { case DLL_PROCESS_ATTACH: g_hinst = (HINSTANCE)hDll; g_hHeap = GetProcessHeap(); InitializeCriticalSection(&g_cs); DisableThreadLibraryCalls(g_hinst); InitClassFactories(); LoadSz(IDS_TITLE, g_szTitle, ARRAYSIZE(g_szTitle)); break; case DLL_PROCESS_DETACH: DeleteCriticalSection(&g_cs); DeleteClassFactories(); break; default: break; } return TRUE; } void DllAddRef(void) { InterlockedIncrement(&g_cDllRef); } void DllRelease(void) { InterlockedDecrement(&g_cDllRef); } // // UnregisterObject removes all registration stuff for this object // Note: it blows away all other registry entries below ours -- likely not a problem. // BOOL UnregisterObject(const OBJECTINFO *poi) { TCHAR szScratch[MAX_PATH]; HKEY hk; StringFromGuid(poi->pclsid, szScratch); RegOpenK(HKEY_CLASSES_ROOT, TEXT("CLSID"), &hk); DeleteKeyAndSubKeys(hk, szScratch); RegCloseKey(hk); if (poi->nObjectType != OI_COCREATEABLE) { DeleteKeyAndSubKeys(HKEY_CLASSES_ROOT, poi->pszName); wsprintf(szScratch, "%s.%d", poi->pszName, poi->lVersion); DeleteKeyAndSubKeys(HKEY_CLASSES_ROOT, szScratch); } return TRUE; } // // RegisterObject registers OI_COCREATEABLE, OI_AUTOMATION, OI_CONTROL // BOOL RegisterObject(const OBJECTINFO *poi) { BOOL bRet = FALSE; TCHAR szGuidStr[GUID_STR_LEN]; TCHAR szScratch[MAX_PATH]; TCHAR szFriendlyName[50]; LPTSTR pszFriendlyName = szFriendlyName; TCHAR szPath[MAX_PATH]; DWORD dwDummy; HKEY hkCLSID = NULL; HKEY hkNAME = NULL; HKEY hkCURVER = NULL; HKEY hkSub = NULL; HKEY hkSub2 = NULL; // set up fixed strings StringFromGuid(poi->pclsid, szGuidStr); if (HIWORD(poi->pszFriendlyName)) pszFriendlyName = poi->pszFriendlyName; else if (!LoadString(g_hinst, LOWORD(poi->pszFriendlyName), szFriendlyName, sizeof(szFriendlyName))) goto CleanUp; if (!GetModuleFileName(g_hinst, szPath, sizeof(szPath))) goto CleanUp; // clean out old info // UnregisterObject(poi); // OI_COCREATEABLE, OI_AUTOMATION, OI_CONTROL // // HKEY_CLASSES_ROOT\CLSID\<CLSID> = <friendly name> // HKEY_CLASSES_ROOT\CLSID\<CLSID>\InprocServer32 = <path> // HKEY_CLASSES_ROOT\CLSID\<CLSID>\InprocServer32\ThreadingModel = Apartment // wsprintf(szScratch, TEXT("CLSID\\%s"), szGuidStr); RegCreate(HKEY_CLASSES_ROOT, szScratch, &hkCLSID); RegSetStr(hkCLSID, pszFriendlyName); RegCreate(hkCLSID, TEXT("InprocServer32"), &hkSub); RegSetStr(hkSub, szPath); RegSetStrValue(hkSub, TEXT("ThreadingModel"), TEXT("Apartment")); RegCloseK(hkSub); if (poi->nObjectType != OI_COCREATEABLE) { TCHAR szCurVer[MAX_PATH]; wsprintf(szCurVer, "%s.%d", poi->pszName, poi->lVersion); // OI_AUTOMATION, OI_CONTROL // // HKEY_CLASSES_ROOT\<static name> = <friendly name> // HKEY_CLASSES_ROOT\<static name>\CLSID = <CLSID> // HKEY_CLASSES_ROOT\<static name>\CurVer = <static name>.<VersionNumber> // // HKEY_CLASSES_ROOT\<static name>.<VersionNumber> = <friendly name> // HKEY_CLASSES_ROOT\<static name>.<VersionNumber>\CLSID = <CLSID> // // HKEY_CLASSES_ROOT\CLSID\<CLSID>\TypeLib = <LibidOfTypeLibrary> // HKEY_CLASSES_ROOT\CLSID\<CLSID>\ProgID = <static name>.<VersionNumber> // HKEY_CLASSES_ROOT\CLSID\<CLSID>\VersionIndependentProgID = <static name> // RegCreate(HKEY_CLASSES_ROOT, poi->pszName, &hkNAME); RegSetStr(hkNAME, pszFriendlyName); RegCreate(hkNAME, TEXT("CLSID"), &hkSub); RegSetStr(hkSub, szGuidStr); RegCloseK(hkSub); RegCreate(hkNAME, TEXT("CurVer"), &hkSub); RegSetStr(hkSub, szCurVer); RegCloseK(hkSub); RegCreate(HKEY_CLASSES_ROOT, szCurVer, &hkCURVER); RegSetStr(hkCURVER, pszFriendlyName); RegCreate(hkCURVER, TEXT("CLSID"), &hkSub); RegSetStr(hkSub, szGuidStr); RegCloseK(hkSub); RegCreate(hkCLSID, TEXT("TypeLib"), &hkSub); // StringFromGuid(&LIBID_SHDocVw, szScratch); RegSetStr(hkSub, szScratch); RegCloseK(hkSub); RegCreate(hkCLSID, TEXT("ProgID"), &hkSub); RegSetStr(hkSub, szCurVer); RegCloseK(hkSub); RegCreate(hkCLSID, TEXT("VersionIndependentProgID"), &hkSub); RegSetStr(hkSub, poi->pszName); RegCloseK(hkSub); if (poi->nObjectType == OI_AUTOMATION) { // REVIEW: do we need these? Sweeper's OI_AUTOMATION does NOT set them // // HKEY_CLASSES_ROOT\CLSID\<CLSID>\Programmable // RegCreate(hkCLSID, TEXT("Programmable"), &hkSub); RegCloseK(hkSub); } if (poi->nObjectType == OI_CONTROL) { // HKEY_CLASSES_ROOT\CLSID\<CLSID>\Control // HKEY_CLASSES_ROOT\CLSID\<CLSID>\MiscStatus = 0 // HKEY_CLASSES_ROOT\CLSID\<CLSID>\MiscStatus\1 = <MISCSTATUSBITS> // HKEY_CLASSES_ROOT\CLSID\<CLSID>\ToolboxBitmap32 = <PATH TO BMP> // HKEY_CLASSES_ROOT\CLSID\<CLSID>\Version = <VERSION> // RegCreate(hkCLSID, TEXT("Control"), &hkSub); RegCloseK(hkSub); RegCreate(hkCLSID, TEXT("MiscStatus"), &hkSub); RegSetStr(hkSub, TEXT("0")); RegCreate(hkSub, TEXT("1"), &hkSub2); wsprintf(szScratch, TEXT("%d"), poi->dwOleMiscFlags); RegSetStr(hkSub2, szScratch); RegCloseK(hkSub2); RegCloseK(hkSub); RegCreate(hkCLSID, TEXT("ToolboxBitmap32"), &hkSub); wsprintf(szScratch, TEXT("%s,%d"), szPath, poi->nidToolbarBitmap); RegSetStr(hkSub, szScratch); RegCloseK(hkSub); RegCreate(hkCLSID, TEXT("Version"), &hkSub); wsprintf(szScratch, TEXT("%ld.0"), poi->lVersion); RegSetStr(hkSub, szScratch); RegCloseK(hkSub); // REVIEW: do we want these? Sweeper's OI_CONTROL does NOT set them // BUGBUG: we probably want to rip them out before ship ... nice to have for testing // // HKEY_CLASSES_ROOT\CLSID\<CLSID>\Insertable // HKEY_CLASSES_ROOT\<static name>\Insertable // RegCreate(hkCLSID, TEXT("Insertable"), &hkSub); RegCloseK(hkSub); RegCreate(hkNAME, TEXT("Insertable"), &hkSub); RegCloseK(hkSub); } RegCloseK(hkCURVER); RegCloseK(hkNAME); } RegCloseK(hkCLSID); return TRUE; CleanUp: if (hkCLSID) RegCloseKey(hkCLSID); if (hkNAME) RegCloseKey(hkNAME); if (hkCURVER) RegCloseKey(hkCURVER); if (hkSub) RegCloseKey(hkSub); if (hkSub2) RegCloseKey(hkSub2); UnregisterObject(poi); return FALSE; } //=--------------------------------------------------------------------------= // UnregisterTypeLibrary //=--------------------------------------------------------------------------= // blows away the type library keys for a given libid. // // Parameters: // REFCLSID - [in] libid to blow away. // // Output: // BOOL - TRUE OK, FALSE bad. // // Notes: // - WARNING: this function just blows away the entire type library section, // including all localized versions of the type library. mildly anti- // social, but not killer. // BOOL UnregisterTypeLibrary ( const CLSID* piidLibrary ) { TCHAR szScratch[GUID_STR_LEN]; HKEY hk; BOOL f; if(piidLibrary == NULL) return TRUE; // convert the libid into a string. // StringFromGuid(piidLibrary, szScratch); RegOpenK(HKEY_CLASSES_ROOT, TEXT("TypeLib"), &hk); f = DeleteKeyAndSubKeys(hk, szScratch); RegCloseKey(hk); return f; } STDAPI DllRegisterServer(void) { const OBJECTINFO *pcls; for (pcls = g_ObjectInfo; pcls->pclsid; pcls++) { if (pcls->nObjectType != OI_NONE) { RegisterObject(pcls); } } return S_OK; } STDAPI DllUnregisterServer(void) { const OBJECTINFO *pcls; for (pcls = g_ObjectInfo; pcls->pclsid; pcls++) { if (pcls->nObjectType != OI_NONE) { UnregisterObject(pcls); } } UnregisterTypeLibrary(NULL); return S_OK; } int LoadSz(UINT id, LPTSTR pszBuf, UINT cMaxSize) { if(cMaxSize == 0) return 0; pszBuf[0] = 0; return LoadString(g_hinst, id, pszBuf, cMaxSize); } 
// Copyright 2014 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/ast-loop-assignment-analyzer.h" #include "src/ast/scopes.h" #include "src/compilation-info.h" #include "src/objects-inl.h" namespace v8 { namespace internal { namespace compiler { typedef class AstLoopAssignmentAnalyzer ALAA; // for code shortitude. ALAA::AstLoopAssignmentAnalyzer(Zone* zone, CompilationInfo* info) : info_(info), zone_(zone), loop_stack_(zone) { InitializeAstVisitor(info->isolate()); } LoopAssignmentAnalysis* ALAA::Analyze() { LoopAssignmentAnalysis* a = new (zone_) LoopAssignmentAnalysis(zone_); result_ = a; VisitStatements(info()->literal()->body()); result_ = nullptr; return a; } void ALAA::Enter(IterationStatement* loop) { int num_variables = 1 + info()->scope()->num_parameters() + info()->scope()->num_stack_slots(); BitVector* bits = new (zone_) BitVector(num_variables, zone_); if (info()->is_osr() && info()->osr_ast_id() == loop->OsrEntryId()) bits->AddAll(); loop_stack_.push_back(bits); } void ALAA::Exit(IterationStatement* loop) { DCHECK(loop_stack_.size() > 0); BitVector* bits = loop_stack_.back(); loop_stack_.pop_back(); if (!loop_stack_.empty()) { loop_stack_.back()->Union(*bits); } result_->list_.push_back( std::pair<IterationStatement*, BitVector*>(loop, bits)); } // --------------------------------------------------------------------------- // -- Leaf nodes ------------------------------------------------------------- // --------------------------------------------------------------------------- void ALAA::VisitVariableDeclaration(VariableDeclaration* leaf) {} void ALAA::VisitFunctionDeclaration(FunctionDeclaration* leaf) {} void ALAA::VisitEmptyStatement(EmptyStatement* leaf) {} void ALAA::VisitContinueStatement(ContinueStatement* leaf) {} void ALAA::VisitBreakStatement(BreakStatement* leaf) {} void ALAA::VisitDebuggerStatement(DebuggerStatement* leaf) {} void ALAA::VisitFunctionLiteral(FunctionLiteral* leaf) {} void ALAA::VisitNativeFunctionLiteral(NativeFunctionLiteral* leaf) {} void ALAA::VisitVariableProxy(VariableProxy* leaf) {} void ALAA::VisitLiteral(Literal* leaf) {} void ALAA::VisitRegExpLiteral(RegExpLiteral* leaf) {} void ALAA::VisitThisFunction(ThisFunction* leaf) {} void ALAA::VisitSuperPropertyReference(SuperPropertyReference* leaf) {} void ALAA::VisitSuperCallReference(SuperCallReference* leaf) {} // --------------------------------------------------------------------------- // -- Pass-through nodes------------------------------------------------------ // --------------------------------------------------------------------------- void ALAA::VisitBlock(Block* stmt) { VisitStatements(stmt->statements()); } void ALAA::VisitDoExpression(DoExpression* expr) { Visit(expr->block()); Visit(expr->result()); } void ALAA::VisitExpressionStatement(ExpressionStatement* stmt) { Visit(stmt->expression()); } void ALAA::VisitIfStatement(IfStatement* stmt) { Visit(stmt->condition()); Visit(stmt->then_statement()); Visit(stmt->else_statement()); } void ALAA::VisitReturnStatement(ReturnStatement* stmt) { Visit(stmt->expression()); } void ALAA::VisitWithStatement(WithStatement* stmt) { Visit(stmt->expression()); Visit(stmt->statement()); } void ALAA::VisitSwitchStatement(SwitchStatement* stmt) { Visit(stmt->tag()); ZoneList<CaseClause*>* clauses = stmt->cases(); for (int i = 0; i < clauses->length(); i++) { Visit(clauses->at(i)); } } void ALAA::VisitTryFinallyStatement(TryFinallyStatement* stmt) { Visit(stmt->try_block()); Visit(stmt->finally_block()); } void ALAA::VisitClassLiteral(ClassLiteral* e) { VisitIfNotNull(e->extends()); VisitIfNotNull(e->constructor()); ZoneList<ClassLiteralProperty*>* properties = e->properties(); for (int i = 0; i < properties->length(); i++) { Visit(properties->at(i)->key()); Visit(properties->at(i)->value()); } } void ALAA::VisitConditional(Conditional* e) { Visit(e->condition()); Visit(e->then_expression()); Visit(e->else_expression()); } void ALAA::VisitObjectLiteral(ObjectLiteral* e) { ZoneList<ObjectLiteralProperty*>* properties = e->properties(); for (int i = 0; i < properties->length(); i++) { Visit(properties->at(i)->key()); Visit(properties->at(i)->value()); } } void ALAA::VisitArrayLiteral(ArrayLiteral* e) { VisitExpressions(e->values()); } void ALAA::VisitSuspend(Suspend* stmt) { Visit(stmt->generator_object()); Visit(stmt->expression()); } void ALAA::VisitThrow(Throw* stmt) { Visit(stmt->exception()); } void ALAA::VisitProperty(Property* e) { Visit(e->obj()); Visit(e->key()); } void ALAA::VisitCall(Call* e) { Visit(e->expression()); VisitExpressions(e->arguments()); } void ALAA::VisitCallNew(CallNew* e) { Visit(e->expression()); VisitExpressions(e->arguments()); } void ALAA::VisitCallRuntime(CallRuntime* e) { VisitExpressions(e->arguments()); } void ALAA::VisitUnaryOperation(UnaryOperation* e) { Visit(e->expression()); } void ALAA::VisitBinaryOperation(BinaryOperation* e) { Visit(e->left()); Visit(e->right()); } void ALAA::VisitCompareOperation(CompareOperation* e) { Visit(e->left()); Visit(e->right()); } void ALAA::VisitSpread(Spread* e) { UNREACHABLE(); } void ALAA::VisitEmptyParentheses(EmptyParentheses* e) { UNREACHABLE(); } void ALAA::VisitGetIterator(GetIterator* e) { UNREACHABLE(); } void ALAA::VisitImportCallExpression(ImportCallExpression* e) { UNREACHABLE(); } void ALAA::VisitCaseClause(CaseClause* cc) { if (!cc->is_default()) Visit(cc->label()); VisitStatements(cc->statements()); } void ALAA::VisitSloppyBlockFunctionStatement( SloppyBlockFunctionStatement* stmt) { Visit(stmt->statement()); } // --------------------------------------------------------------------------- // -- Interesting nodes------------------------------------------------------- // --------------------------------------------------------------------------- void ALAA::VisitTryCatchStatement(TryCatchStatement* stmt) { Visit(stmt->try_block()); Visit(stmt->catch_block()); AnalyzeAssignment(stmt->scope()->catch_variable()); } void ALAA::VisitDoWhileStatement(DoWhileStatement* loop) { Enter(loop); Visit(loop->body()); Visit(loop->cond()); Exit(loop); } void ALAA::VisitWhileStatement(WhileStatement* loop) { Enter(loop); Visit(loop->cond()); Visit(loop->body()); Exit(loop); } void ALAA::VisitForStatement(ForStatement* loop) { VisitIfNotNull(loop->init()); Enter(loop); VisitIfNotNull(loop->cond()); Visit(loop->body()); VisitIfNotNull(loop->next()); Exit(loop); } void ALAA::VisitForInStatement(ForInStatement* loop) { Expression* l = loop->each(); Enter(loop); Visit(l); Visit(loop->subject()); Visit(loop->body()); if (l->IsVariableProxy()) AnalyzeAssignment(l->AsVariableProxy()->var()); Exit(loop); } void ALAA::VisitForOfStatement(ForOfStatement* loop) { Visit(loop->assign_iterator()); Enter(loop); Visit(loop->next_result()); Visit(loop->result_done()); Visit(loop->assign_each()); Visit(loop->body()); Exit(loop); } void ALAA::VisitAssignment(Assignment* stmt) { Expression* l = stmt->target(); Visit(l); Visit(stmt->value()); if (l->IsVariableProxy()) AnalyzeAssignment(l->AsVariableProxy()->var()); } void ALAA::VisitCountOperation(CountOperation* e) { Expression* l = e->expression(); Visit(l); if (l->IsVariableProxy()) AnalyzeAssignment(l->AsVariableProxy()->var()); } void ALAA::VisitRewritableExpression(RewritableExpression* expr) { Visit(expr->expression()); } void ALAA::AnalyzeAssignment(Variable* var) { if (!loop_stack_.empty() && var->IsStackAllocated()) { loop_stack_.back()->Add(GetVariableIndex(info()->scope(), var)); } } int ALAA::GetVariableIndex(DeclarationScope* scope, Variable* var) { CHECK(var->IsStackAllocated()); if (var->is_this()) return 0; if (var->IsParameter()) return 1 + var->index(); return 1 + scope->num_parameters() + var->index(); } int LoopAssignmentAnalysis::GetAssignmentCountForTesting( DeclarationScope* scope, Variable* var) { int count = 0; int var_index = AstLoopAssignmentAnalyzer::GetVariableIndex(scope, var); for (size_t i = 0; i < list_.size(); i++) { if (list_[i].second->Contains(var_index)) count++; } return count; } } // namespace compiler } // namespace internal } // namespace v8
/** * 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 <pulsar/Result.h> #include <iostream> using namespace pulsar; const char* pulsar::strResult(Result result) { switch (result) { case ResultOk: return "Ok"; case ResultUnknownError: return "UnknownError"; case ResultInvalidConfiguration: return "InvalidConfiguration"; case ResultTimeout: return "TimeOut"; case ResultLookupError: return "LookupError"; case ResultConnectError: return "ConnectError"; case ResultAuthenticationError: return "AuthenticationError"; case ResultAuthorizationError: return "AuthorizationError"; case ResultErrorGettingAuthenticationData: return "ErrorGettingAuthenticationData"; case ResultBrokerMetadataError: return "BrokerMetadataError"; case ResultBrokerPersistenceError: return "BrokerPersistenceError"; case ResultConsumerBusy: return "ConsumerBusy"; case ResultNotConnected: return "NotConnected"; case ResultReadError: return "ReadError"; case ResultAlreadyClosed: return "AlreadyClosed"; case ResultInvalidMessage: return "InvalidMessage"; case ResultConsumerNotInitialized: return "ConsumerNotInitialized"; case ResultProducerNotInitialized: return "ProducerNotInitialized"; case ResultInvalidTopicName: return "InvalidTopicName"; case ResultServiceUnitNotReady: return "ServiceUnitNotReady"; case ResultInvalidUrl: return "InvalidUrl"; case ResultChecksumError: return "ChecksumError"; case ResultTooManyLookupRequestException: return "TooManyLookupRequestException"; case ResultOperationNotSupported: return "OperationNotSupported"; case ResultProducerBlockedQuotaExceededError: return "ProducerBlockedQuotaExceededError"; case ResultProducerBlockedQuotaExceededException: return "ProducerBlockedQuotaExceededException"; case ResultProducerQueueIsFull: return "ProducerQueueIsFull"; case ResultMessageTooBig: return "MessageTooBig"; case ResultTopicNotFound: return "TopicNotFound"; case ResultSubscriptionNotFound: return "SubscriptionNotFound"; case ResultConsumerNotFound: return "ConsumerNotFound"; case ResultUnsupportedVersionError: return "UnsupportedVersionError"; case ResultTopicTerminated: return "TopicTerminated"; case ResultCryptoError: return "CryptoError"; case ResultProducerBusy: return "ProducerBusy"; case ResultIncompatibleSchema: return "IncompatibleSchema"; }; // NOTE : Do not add default case in the switch above. In future if we get new cases for // ServerError and miss them in the switch above we would like to get notified. Adding // return here to make the compiler happy. return "UnknownErrorCode"; } #pragma GCC visibility push(default) std::ostream& operator<<(std::ostream& s, Result result) { return s << strResult(result); } #pragma GCC visibility pop
/*============================================================================= Copyright (c) 1999-2003 Jaakko Jarvi Copyright (c) 2001-2011 Joel de Guzman 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 <boost/fusion/container/vector/vector.hpp> #define FUSION_SEQUENCE vector #include "mutate.hpp" int main() { test(); return boost::report_errors(); }
// Author: btjanaka (Bryon Tjanaka) // Problem: (HackerRank) cipher // Title: Cipher // Link: https://www.hackerrank.com/challenges/cipher/problem // Idea: Keep a count of how many bits we expect to see at each position. If the // count is odd, we expect to see "1", and if the count is even, we expect to // see "0". Sometimes, this won't match up though - when it doesn't, we know a 1 // was added into the number. // Difficulty: // Tags: #include <bits/stdc++.h> using namespace std; int main() { int n, k; scanf("%d %d", &n, &k); vector<int> encoded(n + k - 1); for (int i = 0; i < n + k - 1; ++i) scanf("%1d", &encoded[i]); // Keep a running count of number of "on" bits in the last k positions int count = 0; vector<int> res(n, 0); for (int i = 0; i < n; ++i) { if (i >= k && res[i - k] == 1) --count; int expected = count % 2; if (expected != encoded[i]) { ++count; res[i] = 1; } } for (int i = 0; i < n; ++i) printf("%1d", res[i]); printf("\n"); return 0; }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/serial/data_sink_receiver.h" #include <limits> #include "base/bind.h" #include "base/message_loop/message_loop.h" namespace device { // A ReadOnlyBuffer implementation that provides a view of a buffer owned by a // DataSinkReceiver. class DataSinkReceiver::Buffer : public ReadOnlyBuffer { public: Buffer(scoped_refptr<DataSinkReceiver> receiver, const char* buffer, uint32_t buffer_size); ~Buffer() override; void Cancel(int32_t error); // ReadOnlyBuffer overrides. const char* GetData() override; uint32_t GetSize() override; void Done(uint32_t bytes_read) override; void DoneWithError(uint32_t bytes_read, int32_t error) override; private: // The DataSinkReceiver of whose buffer we are providing a view. scoped_refptr<DataSinkReceiver> receiver_; const char* buffer_; uint32_t buffer_size_; // Whether this receive has been cancelled. bool cancelled_; // If |cancelled_|, contains the cancellation error to report. int32_t cancellation_error_; }; // A frame of data received from the client. class DataSinkReceiver::DataFrame { public: explicit DataFrame(mojo::Array<uint8_t> data, const mojo::Callback<void(uint32_t, int32_t)>& callback); // Returns the number of unconsumed bytes remaining of this data frame. uint32_t GetRemainingBytes(); // Returns a pointer to the remaining data to be consumed. const char* GetData(); // Reports that |bytes_read| bytes have been consumed. void OnDataConsumed(uint32_t bytes_read); // Reports that an error occurred. void ReportError(uint32_t bytes_read, int32_t error); private: mojo::Array<uint8_t> data_; uint32_t offset_; const mojo::Callback<void(uint32_t, int32_t)> callback_; }; DataSinkReceiver::DataSinkReceiver( mojo::InterfaceRequest<serial::DataSink> request, const ReadyCallback& ready_callback, const CancelCallback& cancel_callback, const ErrorCallback& error_callback) : binding_(this, request.Pass()), ready_callback_(ready_callback), cancel_callback_(cancel_callback), error_callback_(error_callback), current_error_(0), buffer_in_use_(NULL), shut_down_(false), weak_factory_(this) { binding_.set_error_handler(this); } void DataSinkReceiver::ShutDown() { shut_down_ = true; } DataSinkReceiver::~DataSinkReceiver() { } void DataSinkReceiver::Cancel(int32_t error) { // If we have sent a ReportBytesSentAndError but have not received the // response, that ReportBytesSentAndError message will appear to the // DataSinkClient to be caused by this Cancel message. In that case, we ignore // the cancel. if (current_error_) return; // If there is a buffer is in use, mark the buffer as cancelled and notify the // client by calling |cancel_callback_|. The sink implementation may or may // not take the cancellation into account when deciding what error (if any) to // return. If the sink returns an error, we ignore the cancellation error. // Otherwise, if the sink does not report an error, we override that with the // cancellation error. Once a cancellation has been received, the next report // sent to the client will always contain an error; the error returned by the // sink or the cancellation error if the sink does not return an error. if (buffer_in_use_) { buffer_in_use_->Cancel(error); if (!cancel_callback_.is_null()) cancel_callback_.Run(error); return; } ReportError(0, error); } void DataSinkReceiver::OnData( mojo::Array<uint8_t> data, const mojo::Callback<void(uint32_t, int32_t)>& callback) { if (current_error_) { callback.Run(0, current_error_); return; } pending_data_buffers_.push( linked_ptr<DataFrame>(new DataFrame(data.Pass(), callback))); if (!buffer_in_use_) RunReadyCallback(); } void DataSinkReceiver::OnConnectionError() { DispatchFatalError(); } void DataSinkReceiver::RunReadyCallback() { DCHECK(!shut_down_ && !current_error_); // If data arrives while a call to RunReadyCallback() is posted, we can be // called with buffer_in_use_ already set. if (buffer_in_use_) return; buffer_in_use_ = new Buffer(this, pending_data_buffers_.front()->GetData(), pending_data_buffers_.front()->GetRemainingBytes()); ready_callback_.Run(scoped_ptr<ReadOnlyBuffer>(buffer_in_use_)); } void DataSinkReceiver::Done(uint32_t bytes_read) { if (!DoneInternal(bytes_read)) return; pending_data_buffers_.front()->OnDataConsumed(bytes_read); if (pending_data_buffers_.front()->GetRemainingBytes() == 0) pending_data_buffers_.pop(); if (!pending_data_buffers_.empty()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&DataSinkReceiver::RunReadyCallback, weak_factory_.GetWeakPtr())); } } void DataSinkReceiver::DoneWithError(uint32_t bytes_read, int32_t error) { if (!DoneInternal(bytes_read)) return; ReportError(bytes_read, error); } bool DataSinkReceiver::DoneInternal(uint32_t bytes_read) { if (shut_down_) return false; DCHECK(buffer_in_use_); buffer_in_use_ = NULL; return true; } void DataSinkReceiver::ReportError(uint32_t bytes_read, int32_t error) { // When we encounter an error, we must discard the data from any send buffers // transmitted by the DataSink client before it receives this error. DCHECK(error); current_error_ = error; while (!pending_data_buffers_.empty()) { pending_data_buffers_.front()->ReportError(bytes_read, error); pending_data_buffers_.pop(); bytes_read = 0; } } void DataSinkReceiver::ClearError() { current_error_ = 0; } void DataSinkReceiver::DispatchFatalError() { if (shut_down_) return; ShutDown(); if (!error_callback_.is_null()) error_callback_.Run(); } DataSinkReceiver::Buffer::Buffer(scoped_refptr<DataSinkReceiver> receiver, const char* buffer, uint32_t buffer_size) : receiver_(receiver), buffer_(buffer), buffer_size_(buffer_size), cancelled_(false), cancellation_error_(0) { } DataSinkReceiver::Buffer::~Buffer() { if (!receiver_.get()) return; if (cancelled_) receiver_->DoneWithError(0, cancellation_error_); else receiver_->Done(0); } void DataSinkReceiver::Buffer::Cancel(int32_t error) { cancelled_ = true; cancellation_error_ = error; } const char* DataSinkReceiver::Buffer::GetData() { return buffer_; } uint32_t DataSinkReceiver::Buffer::GetSize() { return buffer_size_; } void DataSinkReceiver::Buffer::Done(uint32_t bytes_read) { scoped_refptr<DataSinkReceiver> receiver = receiver_; receiver_ = nullptr; if (cancelled_) receiver->DoneWithError(bytes_read, cancellation_error_); else receiver->Done(bytes_read); buffer_ = NULL; buffer_size_ = 0; } void DataSinkReceiver::Buffer::DoneWithError(uint32_t bytes_read, int32_t error) { scoped_refptr<DataSinkReceiver> receiver = receiver_; receiver_ = nullptr; receiver->DoneWithError(bytes_read, error); buffer_ = NULL; buffer_size_ = 0; } DataSinkReceiver::DataFrame::DataFrame( mojo::Array<uint8_t> data, const mojo::Callback<void(uint32_t, int32_t)>& callback) : data_(data.Pass()), offset_(0), callback_(callback) { DCHECK_LT(0u, data_.size()); } // Returns the number of uncomsumed bytes remaining of this data frame. uint32_t DataSinkReceiver::DataFrame::GetRemainingBytes() { return static_cast<uint32_t>(data_.size() - offset_); } // Returns a pointer to the remaining data to be consumed. const char* DataSinkReceiver::DataFrame::GetData() { DCHECK_LT(offset_, data_.size()); return reinterpret_cast<const char*>(&data_[0]) + offset_; } void DataSinkReceiver::DataFrame::OnDataConsumed(uint32_t bytes_read) { offset_ += bytes_read; DCHECK_LE(offset_, data_.size()); if (offset_ == data_.size()) callback_.Run(offset_, 0); } void DataSinkReceiver::DataFrame::ReportError(uint32_t bytes_read, int32_t error) { offset_ += bytes_read; DCHECK_LE(offset_, data_.size()); callback_.Run(offset_, error); } } // namespace device
#include "tp_maps_ui/draw_helpers/DarkDrawHelper.h" namespace tp_maps_ui { //################################################################################################## DarkDrawHelper::DarkDrawHelper(UILayer* layer): ThemeDrawHelper(layer, params()) { } //################################################################################################## ThemeParameters DarkDrawHelper::params() { ThemeParameters params; //A panel { params.normalPanelFrame.l = {186,189,182,255}; params.normalPanelFrame.r = {120,120,120,255}; params.normalPanelFrame.t = {186,189,182,255}; params.normalPanelFrame.b = {120,120,120,255}; params.normalPanelFrame.c = {146,148,143,255}; params.normalPanelFrame.tl = {192,192,192,255}; params.normalPanelFrame.tr = {136,138,133,255}; params.normalPanelFrame.bl = {136,138,133,255}; params.normalPanelFrame.br = {120,120,120,255}; } //A normal raised button { params.raisedButtonFrame.l = {186,189,182,255}; params.raisedButtonFrame.r = {120,120,120,255}; params.raisedButtonFrame.t = {186,189,182,255}; params.raisedButtonFrame.b = {120,120,120,255}; params.raisedButtonFrame.c = {146,148,143,255}; params.raisedButtonFrame.tl = {192,192,192,255}; params.raisedButtonFrame.tr = {136,138,133,255}; params.raisedButtonFrame.bl = {136,138,133,255}; params.raisedButtonFrame.br = {120,120,120,255}; } //A pressed button { params.sunkenButtonFrame.l = {120,120,120,255}; params.sunkenButtonFrame.r = {186,189,182,255}; params.sunkenButtonFrame.t = {120,120,120,255}; params.sunkenButtonFrame.b = {186,189,182,255}; params.sunkenButtonFrame.c = {136,138,133,255}; params.sunkenButtonFrame.tl = {120,120,120,255}; params.sunkenButtonFrame.tr = {136,138,133,255}; params.sunkenButtonFrame.bl = {136,138,133,255}; params.sunkenButtonFrame.br = {192,192,192,255}; } return params; } }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "AIModulePrivate.h" #include "BehaviorTree/Blackboard/BlackboardKeyType_String.h" const UBlackboardKeyType_String::FDataType UBlackboardKeyType_String::InvalidValue = FString(); UBlackboardKeyType_String::UBlackboardKeyType_String(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { ValueSize = 0; bCreateKeyInstance = true; SupportedOp = EBlackboardKeyOperation::Text; } FString UBlackboardKeyType_String::GetValue(const UBlackboardKeyType_String* KeyOb, const uint8* RawData) { return KeyOb->StringValue; } bool UBlackboardKeyType_String::SetValue(UBlackboardKeyType_String* KeyOb, uint8* RawData, const FString& Value) { const bool bChanged = !KeyOb->StringValue.Equals(Value); KeyOb->StringValue = Value; return bChanged; } EBlackboardCompare::Type UBlackboardKeyType_String::CompareValues(const UBlackboardComponent& OwnerComp, const uint8* MemoryBlock, const UBlackboardKeyType* OtherKeyOb, const uint8* OtherMemoryBlock) const { const FString MyValue = GetValue(this, MemoryBlock); const FString OtherValue = GetValue((UBlackboardKeyType_String*)OtherKeyOb, OtherMemoryBlock); return MyValue.Equals(OtherValue) ? EBlackboardCompare::Equal : EBlackboardCompare::NotEqual; } void UBlackboardKeyType_String::CopyValues(UBlackboardComponent& OwnerComp, uint8* MemoryBlock, const UBlackboardKeyType* SourceKeyOb, const uint8* SourceBlock) { StringValue = ((UBlackboardKeyType_String*)SourceKeyOb)->StringValue; } FString UBlackboardKeyType_String::DescribeValue(const UBlackboardComponent& OwnerComp, const uint8* RawData) const { return StringValue; } bool UBlackboardKeyType_String::TestTextOperation(const UBlackboardComponent& OwnerComp, const uint8* MemoryBlock, ETextKeyOperation::Type Op, const FString& OtherString) const { switch (Op) { case ETextKeyOperation::Equal: return (StringValue == OtherString); case ETextKeyOperation::NotEqual: return (StringValue != OtherString); case ETextKeyOperation::Contain: return (StringValue.Contains(OtherString) == true); case ETextKeyOperation::NotContain: return (StringValue.Contains(OtherString) == false); default: break; } return false; } void UBlackboardKeyType_String::Clear(UBlackboardComponent& OwnerComp, uint8* MemoryBlock) { StringValue.Empty(); } bool UBlackboardKeyType_String::IsEmpty(const UBlackboardComponent& OwnerComp, const uint8* MemoryBlock) const { return StringValue.IsEmpty(); }
#include <json5pp.hpp> #include <ostream> void exec(std::ostream& out) { auto value = json5pp::object({{"foo", "bar"}}); out << value.stringify(); }
#ifndef GLSHADOWMAP_HPP #define GLSHADOWMAP_HPP #include <GL/glew.h> #include <GL/gl.h> #define GLM_ENABLE_EXPERIMENTAL #include <glm/glm.hpp> #include "Utils.hpp" class GLShadowMap { public: GLShadowMap(const glm::ivec2& size); GLShadowMap(GLShadowMap const& that) = delete; void operator=(GLShadowMap& that) = delete; ~GLShadowMap(); GLuint getFrameBufferID() const; GLuint getDepthTextureID() const; glm::ivec2 getSize() const; GLuint getVaoID() const; private: glm::ivec2 size; GLuint frameBufferID; GLuint depthTextureID; GLuint vaoID; GLuint vboID; bool isOperational; }; #endif // GLSHADOWMAP_HPP
class Solution { public: /** * @param A: An integer array. * @param B: An integer array. * @return: Cosine similarity. */ double cosineSimilarity(vector<int> A, vector<int> B) { double Asum = 0, Bsum = 0, ABsum = 0; for (int i = 0; i < A.size(); i++) { double a = A[i], b = B[i]; Asum += a*a; Bsum += b*b; ABsum += a*b; } double product = Asum * Bsum; return product == 0? 2 : ABsum / sqrt(product); } };
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // Copyright (c) 2018, The TurtleCoin Developers // Copyright (c) 2019, The Lithe Project // // Please see the included LICENSE file for more information. #include "WalletUtils.h" #include "CryptoNote.h" #include "crypto/crypto.h" #include "Wallet/WalletErrors.h" namespace CryptoNote { uint64_t getDefaultMixinByHeight(const uint64_t height) { return CryptoNote::parameters::DEFAULT_MIXIN; } void throwIfKeysMismatch(const Crypto::SecretKey& secretKey, const Crypto::PublicKey& expectedPublicKey, const std::string& message) { Crypto::PublicKey pub; bool r = Crypto::secret_key_to_public_key(secretKey, pub); if (!r || expectedPublicKey != pub) { throw std::system_error(make_error_code(CryptoNote::error::WRONG_PASSWORD), message); } } bool validateAddress(const std::string& address, const CryptoNote::Currency& currency) { CryptoNote::AccountPublicAddress ignore; return currency.parseAccountAddressString(address, ignore); } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletTransactionState state) { switch (state) { case CryptoNote::WalletTransactionState::SUCCEEDED: os << "SUCCEEDED"; break; case CryptoNote::WalletTransactionState::FAILED: os << "FAILED"; break; case CryptoNote::WalletTransactionState::CANCELLED: os << "CANCELLED"; break; case CryptoNote::WalletTransactionState::CREATED: os << "CREATED"; break; case CryptoNote::WalletTransactionState::DELETED: os << "DELETED"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(state) << ')'; } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletTransferType type) { switch (type) { case CryptoNote::WalletTransferType::USUAL: os << "USUAL"; break; case CryptoNote::WalletTransferType::DONATION: os << "DONATION"; break; case CryptoNote::WalletTransferType::CHANGE: os << "CHANGE"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(type) << ')'; } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletGreen::WalletState state) { switch (state) { case CryptoNote::WalletGreen::WalletState::INITIALIZED: os << "INITIALIZED"; break; case CryptoNote::WalletGreen::WalletState::NOT_INITIALIZED: os << "NOT_INITIALIZED"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(state) << ')'; } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletGreen::WalletTrackingMode mode) { switch (mode) { case CryptoNote::WalletGreen::WalletTrackingMode::TRACKING: os << "TRACKING"; break; case CryptoNote::WalletGreen::WalletTrackingMode::NOT_TRACKING: os << "NOT_TRACKING"; break; case CryptoNote::WalletGreen::WalletTrackingMode::NO_ADDRESSES: os << "NO_ADDRESSES"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(mode) << ')'; } TransferListFormatter::TransferListFormatter(const CryptoNote::Currency& currency, const WalletGreen::TransfersRange& range) : m_currency(currency), m_range(range) { } void TransferListFormatter::print(std::ostream& os) const { for (auto it = m_range.first; it != m_range.second; ++it) { os << '\n' << std::setw(21) << m_currency.formatAmount(it->second.amount) << ' ' << (it->second.address.empty() ? "<UNKNOWN>" : it->second.address) << ' ' << it->second.type; } } std::ostream& operator<<(std::ostream& os, const TransferListFormatter& formatter) { formatter.print(os); return os; } WalletOrderListFormatter::WalletOrderListFormatter(const CryptoNote::Currency& currency, const std::vector<CryptoNote::WalletOrder>& walletOrderList) : m_currency(currency), m_walletOrderList(walletOrderList) { } void WalletOrderListFormatter::print(std::ostream& os) const { os << '{'; if (!m_walletOrderList.empty()) { os << '<' << m_currency.formatAmount(m_walletOrderList.front().amount) << ", " << m_walletOrderList.front().address << '>'; for (auto it = std::next(m_walletOrderList.begin()); it != m_walletOrderList.end(); ++it) { os << '<' << m_currency.formatAmount(it->amount) << ", " << it->address << '>'; } } os << '}'; } std::ostream& operator<<(std::ostream& os, const WalletOrderListFormatter& formatter) { formatter.print(os); return os; } }
#include "AppHdr.h" #ifdef USE_TILE_LOCAL #include "tilereg-cmd.h" #include "ability.h" #include "cio.h" #include "command.h" #include "describe.h" #include "env.h" #include "items.h" #include "libutil.h" #include "macro.h" #include "nearby-danger.h" #include "religion.h" #include "spl-cast.h" #include "stringutil.h" #include "rltiles/tiledef-icons.h" #include "tilepick.h" #include "tiles-build-specific.h" #include "viewmap.h" CommandRegion::CommandRegion(const TileRegionInit &init, const command_type commands[], const int n_commands, const string _name, const string help) : GridRegion(init), _common_commands( commands, commands + n_commands ), m_name(_name), m_help(help) { n_common_commands = n_commands; } void CommandRegion::activate() { } void CommandRegion::draw_tag() { if (m_cursor == NO_CURSOR) return; int curs_index = cursor_index(); if (curs_index >= (int)m_items.size()) return; int idx = m_items[curs_index].idx; if (idx == -1) return; const command_type cmd = (command_type) idx; draw_desc(get_command_description(cmd, true).c_str()); } int CommandRegion::handle_mouse(wm_mouse_event &event) { unsigned int item_idx; if (!place_cursor(event, item_idx)) return 0; if (event.button == wm_mouse_event::LEFT) { const command_type cmd = (command_type) m_items[item_idx].idx; m_last_clicked_item = item_idx; if (tiles.is_using_small_layout()) { // close the tab that we've just successfully used a command from tiles.deactivate_tab(); } if (tiles.get_map_display()) process_map_command(cmd); else process_command(cmd); return CK_MOUSE_CMD; } return 0; } bool CommandRegion::update_tab_tip_text(string &tip, bool active) { const char *prefix = active ? "" : "[L-Click] "; tip = make_stringf("%s%s", prefix, m_help.c_str()); return true; } bool CommandRegion::update_tip_text(string& tip) { if (m_cursor == NO_CURSOR) return false; unsigned int item_idx = cursor_index(); if (item_idx >= m_items.size() || m_items[item_idx].empty()) return false; const command_type cmd = (command_type) m_items[item_idx].idx; tip = make_stringf("[L-Click] %s", get_command_description(cmd, true).c_str()); if (command_to_key(cmd) != '\0') { tip += " (%)"; insert_commands(tip, { cmd }); } // tip += "\n[R-Click] Describe"; return true; } bool CommandRegion::update_alt_text(string &alt) { if (m_cursor == NO_CURSOR) return false; unsigned int item_idx = cursor_index(); if (item_idx >= m_items.size() || m_items[item_idx].empty()) return false; if (m_last_clicked_item >= 0 && item_idx == (unsigned int) m_last_clicked_item) { return false; } int idx = m_items[item_idx].idx; const command_type cmd = (command_type) idx; const string desc = get_command_description(cmd, false); if (desc.empty()) return false; describe_info inf; inf.body << desc; alt = process_description(inf); return true; } void CommandRegion::pack_buffers() { unsigned int i = 0; for (int y = 0; y < my; y++) { if (i >= m_items.size()) break; for (int x = 0; x < mx; x++) { if (i >= m_items.size()) break; InventoryTile &item = m_items[i++]; if (item.flag & TILEI_FLAG_INVALID) m_buf.add_icons_tile(TILEI_MESH, x, y); if (item.tile) m_buf.add_command_tile(item.tile, x, y); if (item.flag & TILEI_FLAG_CURSOR) m_buf.add_icons_tile(TILEI_CURSOR, x, y); } } } bool tile_command_not_applicable(const command_type cmd, bool safe) { // in the level map, only the map pan commands work const bool map_cmd = context_for_command(cmd) == KMC_LEVELMAP; if (tiles.get_map_display() != map_cmd) return true; switch (cmd) { case CMD_REST: case CMD_EXPLORE: case CMD_INTERLEVEL_TRAVEL: case CMD_MEMORISE_SPELL: return !safe; case CMD_DISPLAY_RELIGION: return you_worship(GOD_NO_GOD); case CMD_USE_ABILITY: return your_talents(false).empty(); case CMD_CAST_SPELL: return !can_cast_spells(true); default: return false; } } bool tile_command_not_applicable(const command_type cmd) { return tile_command_not_applicable(cmd, i_feel_safe(false)); } void CommandRegion::update() { m_items.clear(); m_dirty = true; if (mx * my == 0) return; const bool safe = i_feel_safe(false); for (int idx = 0; idx < n_common_commands; ++idx) { command_type cmd = _common_commands[idx]; // hackily toggle between display map and exit map display depending // on whether we are in map mode if (cmd == CMD_DISPLAY_MAP && tiles.get_map_display()) cmd = CMD_MAP_EXIT_MAP; InventoryTile desc; desc.tile = tileidx_command(cmd); desc.idx = cmd; // Auto-explore while monsters around etc. if (tile_command_not_applicable(cmd, safe)) desc.flag |= TILEI_FLAG_INVALID; m_items.push_back(desc); } } #endif
// RUN: %clang_cc1 -Weverything -fsyntax-only %s -verify // This previously crashed due to a bug in the CFG. Exercising all // warnings helps check CFG construction. class PR12271 { public: PR12271(); ~PR12271(); }; void testPR12271() { // expected-warning {{no previous prototype for function 'testPR12271'}} PR12271 a[1][1]; }
#include <TinyProcessLib/Process.hpp> namespace TinyProcessLib { Process::Process(const std::vector<string_type> &arguments, const string_type &path, std::function<void(const char *bytes, size_t n)> read_stdout, std::function<void(const char *bytes, size_t n)> read_stderr, bool open_stdin, const Config &config) noexcept : closed(true), read_stdout(std::move(read_stdout)), read_stderr(std::move(read_stderr)), open_stdin(open_stdin), config(config) { open(arguments, path); async_read(); } Process::Process(const string_type &command, const string_type &path, std::function<void(const char *bytes, size_t n)> read_stdout, std::function<void(const char *bytes, size_t n)> read_stderr, bool open_stdin, const Config &config) noexcept : closed(true), read_stdout(std::move(read_stdout)), read_stderr(std::move(read_stderr)), open_stdin(open_stdin), config(config) { open(command, path); async_read(); } Process::Process(const std::vector<string_type> &arguments, const string_type &path, const environment_type &environment, std::function<void(const char *bytes, size_t n)> read_stdout, std::function<void(const char *bytes, size_t n)> read_stderr, bool open_stdin, const Config &config) noexcept : closed(true), read_stdout(std::move(read_stdout)), read_stderr(std::move(read_stderr)), open_stdin(open_stdin), config(config) { open(arguments, path, &environment); async_read(); } Process::Process(const string_type &command, const string_type &path, const environment_type &environment, std::function<void(const char *bytes, size_t n)> read_stdout, std::function<void(const char *bytes, size_t n)> read_stderr, bool open_stdin, const Config &config) noexcept : closed(true), read_stdout(std::move(read_stdout)), read_stderr(std::move(read_stderr)), open_stdin(open_stdin), config(config) { open(command, path, &environment); async_read(); } Process::~Process() noexcept { close_fds(); } Process::id_type Process::get_id() const noexcept { return data.id; } bool Process::write(const std::string &str) { return write(str.c_str(), str.size()); } } // namespace TinyProcessLib
#ifdef PEGASUS_OS_ZOS #ifndef __UNIX_ZONECAPABILITIES_PRIVATE_H #define __UNIX_ZONECAPABILITIES_PRIVATE_H #endif #endif
#ifndef STAN_MCMC_HMC_NUTS_CLASSIC_DENSE_E_NUTS_CLASSIC_HPP #define STAN_MCMC_HMC_NUTS_CLASSIC_DENSE_E_NUTS_CLASSIC_HPP #include <stan/mcmc/hmc/nuts_classic/base_nuts_classic.hpp> #include <stan/mcmc/hmc/hamiltonians/dense_e_point.hpp> #include <stan/mcmc/hmc/hamiltonians/dense_e_metric.hpp> #include <stan/mcmc/hmc/integrators/expl_leapfrog.hpp> namespace stan { namespace mcmc { // The No-U-Turn Sampler (NUTS) on a // Euclidean manifold with dense metric template <class Model, class BaseRNG> class dense_e_nuts_classic : public base_nuts_classic<Model, dense_e_metric, expl_leapfrog, BaseRNG> { public: dense_e_nuts_classic(const Model& model, BaseRNG& rng) : base_nuts_classic<Model, dense_e_metric, expl_leapfrog, BaseRNG>(model, rng) {} // Note that the points don't need to be swapped // here since start.inv_e_metric_ = finish.inv_e_metric_ bool compute_criterion(ps_point& start, dense_e_point& finish, Eigen::VectorXd& rho) { return finish.p.transpose() * finish.inv_e_metric_ * (rho - finish.p) > 0 && start.p.transpose() * finish.inv_e_metric_ * (rho - start.p) > 0; } }; } // namespace mcmc } // namespace stan #endif
/* * Copyright (c) 1995-2021, Nikolay Pultsin <geometer@geometer.name> * * 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 "DiagramEditor.h" namespace KE::TwoD { namespace { struct SavePointCommand : public DiagramEditor::Command { void play(Diagram&) override { } }; std::shared_ptr<DiagramEditor::Command> savePointCommand(new SavePointCommand()); } void DiagramEditor::savePoint() { if (this->indexInLog > 0 && this->log[this->indexInLog - 1] != savePointCommand) { this->trimLog(); this->log.push_back(savePointCommand); this->indexInLog += 1; } } void DiagramEditor::trimLog() { if (this->indexInLog < this->log.size()) { this->log.erase(this->log.begin() + this->indexInLog, this->log.end()); } } void DiagramEditor::addCommand(const std::shared_ptr<Command> &command, bool savePoint) { this->trimLog(); this->log.push_back(command); this->indexInLog += 1; if (savePoint) { this->savePoint(); } } bool DiagramEditor::canUndo() const { return this->indexInLog > 0; } bool DiagramEditor::canRedo() const { return this->indexInLog < this->log.size(); } void DiagramEditor::undo() { if (this->indexInLog == 0) { return; } for (this->indexInLog -= 1; this->indexInLog > 0; this->indexInLog -= 1) { if (this->log[this->indexInLog - 1] == savePointCommand) { break; } } auto replacement = std::make_shared<Diagram>(this->initialDiagram.serialize()); for (std::size_t index = 0; index < this->indexInLog; index += 1) { this->log[index]->play(*replacement); } this->currentDiagram = replacement; } void DiagramEditor::redo() { for (; this->indexInLog < this->log.size(); this->indexInLog += 1) { const auto &command = this->log[this->indexInLog]; if (command == savePointCommand) { this->indexInLog += 1; break; } command->play(*this->currentDiagram); } } }
/* * Cloud-based Object Recognition Engine (CORE) * */ #include <core/features/normals.h> void computeNormals (const pcl::search::KdTree<pcl::PointXYZRGB>::Ptr &tree, const pcl::PointCloud<pcl::PointXYZRGB>::Ptr &cloud, pcl::PointCloud<pcl::Normal>::Ptr &cloud_normals, float radius) { pcl::NormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal> ne; ne.setSearchMethod (tree); ne.setInputCloud (cloud); ne.setRadiusSearch (radius); ne.compute (*cloud_normals); } void computeIntegralImageNormals (const pcl::PointCloud<pcl::PointXYZRGB>::Ptr &cloud, pcl::PointCloud<pcl::Normal>::Ptr &cloud_normals, float change_factor, float smoothing_size) { pcl::IntegralImageNormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne; // The following normal estimation methods are available: COVARIANCE_MATRIX, // AVERAGE_3D_GRADIENT, AVERAGE_DEPTH_CHANGE. ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT); ne.setMaxDepthChangeFactor(change_factor); ne.setNormalSmoothingSize(smoothing_size); ne.setInputCloud (cloud); ne.compute (*cloud_normals); }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // // popup-manager.cpp // #include "popup-manager.hpp" #include "context.hpp" #include "gui-text.hpp" #include "layout.hpp" #include "media.hpp" #include "util.hpp" namespace castlecrawl { void PopupManager::setupBanner(Context & context, const std::string & message) { const TextBlock textBlock = context.media.makeTextBlock(FontSize::Medium, message); m_texts = textBlock.lines; m_fadeRectangle.setSize(context.layout.windowSize()); m_fadeRectangle.setFillColor(sf::Color(0, 0, 0, 64)); m_bgRectangle.setFillColor(sf::Color(25, 100, 115, 200)); m_bgRectangle.setOutlineColor(sf::Color(255, 255, 255, 200)); m_bgRectangle.setOutlineThickness(2.0f); m_bgRectangle.setPosition(0.0f, (context.layout.windowSize().y * 0.2f)); const float vertPad{ context.layout.windowSize().y * 0.015f }; const sf::Vector2f pos{ ((context.layout.windowSize().x * 0.5f) - (textBlock.size.x * 0.5f)), (m_bgRectangle.getGlobalBounds().top + vertPad) }; for (sf::Text & text : m_texts) { text.move(pos); } const float bgRectangleHeight{ (util::bottom(m_texts.back().getGlobalBounds()) - m_bgRectangle.getGlobalBounds().top) + vertPad }; m_bgRectangle.setSize(sf::Vector2f{ context.layout.windowSize().x, bgRectangleHeight }); m_paperSprite = {}; } void PopupManager::setupPaper( Context & context, const PopupBackground background, const FontSize fontSize, const sf::Color & color, const std::string & text) { m_fadeRectangle.setSize(context.layout.windowSize()); m_fadeRectangle.setFillColor(sf::Color(0, 0, 0, 64)); m_bgRectangle.setFillColor(sf::Color::Transparent); m_bgRectangle.setOutlineColor(sf::Color::Transparent); m_bgRectangle.setOutlineThickness(0.0f); m_bgRectangle.setSize({ 0.0f, 0.0f }); m_paperSprite = [&]() { if (PopupBackground::Paper1 == background) { return sf::Sprite(context.media.paper1Texture()); } else { return sf::Sprite(context.media.paper2Texture()); } }(); const sf::Vector2f windowSize{ context.layout.windowSize() }; const float paperWidth{ windowSize.x * 0.3f }; const sf::FloatRect sizingRect{ ((windowSize.x * 0.5f) - (paperWidth * 0.5f)), 0.0f, paperWidth, windowSize.y }; util::fitAndCenterInside(m_paperSprite, sizingRect); sf::FloatRect textRegion = [&]() { if (PopupBackground::Paper1 == background) { return context.media.paper1InnerRect(); } else { return context.media.paper2InnerRect(); } }(); const float paperLocalWidth{ m_paperSprite.getLocalBounds().width }; const float resizeRatio{ 1.0f - ((paperLocalWidth - paperWidth) / paperLocalWidth) }; textRegion.left *= resizeRatio; textRegion.top *= resizeRatio; textRegion.width *= resizeRatio; textRegion.height *= resizeRatio; textRegion.left += util::position(m_paperSprite).x; textRegion.top += util::position(m_paperSprite).y; m_texts = typeset(context, fontSize, color, textRegion, text); } void PopupManager::draw(sf::RenderTarget & target, sf::RenderStates states) const { target.draw(m_fadeRectangle, states); target.draw(m_bgRectangle, states); target.draw(m_paperSprite, states); for (const sf::Text & text : m_texts) { target.draw(text, states); } } } // namespace castlecrawl
#include "NFCAsyMysqlModule.h" #include "NFCMysqlDriverManager.h" bool SMysqlBaseParam::PackParam(std::string& strData) { try { NFMsg::PackMysqlParam xMsg; xMsg.set_strrecordname(strRecordName); xMsg.set_strkey(strKey); xMsg.set_bexit(bExit); xMsg.set_nreqid(nReqID); xMsg.set_nret(nRet); xMsg.set_etype(eType); for (int i = 0; i < fieldVec.size(); i++) { const std::string& strFiled = fieldVec[i]; xMsg.add_fieldveclist(strFiled); } for (int i = 0; i < valueVec.size(); i++) { const std::string& strValue = valueVec[i]; xMsg.add_valueveclist(strValue); } return xMsg.SerializeToString(&strData); } catch (...) { return false; } return true; } bool SMysqlBaseParam::UnPackParam(const std::string& strData) { try { NFMsg::PackMysqlParam xMsg; if (!xMsg.ParseFromString(strData)) { return false; } strRecordName = xMsg.strrecordname(); strKey = xMsg.strkey(); bExit = xMsg.bexit(); nReqID = xMsg.nreqid(); nRet = xMsg.nret(); eType = (NFIAsyMysqlModule::ACOTERMYSQLEVENT)xMsg.etype(); for (int i = 0; i < xMsg.fieldveclist_size(); i++) { const std::string& strField = xMsg.fieldveclist(i); fieldVec.push_back(strField); } for (int i = 0; i < xMsg.valueveclist_size(); i++) { const std::string& strValue = xMsg.valueveclist(i); valueVec.push_back(strValue); } } catch (...) { return false; } return true; } bool NFCMysqlComponent::Init() { return true; } bool NFCMysqlComponent::AfterInit() { m_pMysqlDriverManager = NF_SHARE_PTR<NFIMysqlDriverManager>(NF_NEW NFCMysqlDriverManager()); return true; } int NFCMysqlComponent::OnASyncEvent(const NFGUID& self, const int event, std::string& arg) { int nRet = 0; switch (event) { case NFCAsyMysqlModule::ACOTERMYSQLEVENT_UPDATA: { nRet = OnASyUpdataMysqlEvent(self, event, arg); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_QUERY: { nRet = OnASyQueryMysqlEvent(self, event, arg); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_SELECT: { nRet = OnASySelectMysqlEvent(self, event, arg); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_DELETE: { nRet = OnASyDeleteMysqlEvent(self, event, arg); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_EXISTS: { nRet = OnASyExistsMysqlEvent(self, event, arg); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_KEYS: { nRet = OnASyKeysMysqlEvent(self, event, arg); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_INISERVER: { nRet = OnASyAddMysqlServerEvent(self, event, arg); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_KEEPALIVESERVER: { nRet = OnASyKeepServerAliveEvent(self, event, arg); } break; default: break; } return nRet; } int NFCMysqlComponent::OnASyUpdataMysqlEvent(const NFGUID& self, const int event, std::string& arg) { SMysqlBaseParam xparam; if (!xparam.UnPackParam(arg)) { return -1; } if (!m_pMysqlDriverManager.get()) { return -2; } NFIMysqlDriver* pDriver = m_pMysqlDriverManager->GetMysqlDriver(); if (NULL == pDriver) { return -3; } if (xparam.eType != NFCAsyMysqlModule::ACOTERMYSQLEVENT_UPDATA) { return -4; } if (!pDriver->Updata(xparam.strRecordName, xparam.strKey, xparam.fieldVec, xparam.valueVec)) { xparam.nRet = -1; } xparam.PackParam(arg); return 0; } int NFCMysqlComponent::OnASyQueryMysqlEvent(const NFGUID& self, const int event, std::string& arg) { SMysqlBaseParam xparam; if (!xparam.UnPackParam(arg)) { return -1; } if (!m_pMysqlDriverManager.get()) { return -2; } NFIMysqlDriver* pDriver = m_pMysqlDriverManager->GetMysqlDriver(); if (NULL == pDriver) { return -3; } if (xparam.eType != NFCAsyMysqlModule::ACOTERMYSQLEVENT_QUERY) { return -4; } if (!pDriver->Query(xparam.strRecordName, xparam.strKey, xparam.fieldVec, xparam.valueVec)) { xparam.nRet = -1; } xparam.PackParam(arg); return 0; } int NFCMysqlComponent::OnASySelectMysqlEvent(const NFGUID& self, const int event, std::string& arg) { SMysqlBaseParam xparam; if (!xparam.UnPackParam(arg)) { return -1; } if (!m_pMysqlDriverManager.get()) { return -2; } NFIMysqlDriver* pDriver = m_pMysqlDriverManager->GetMysqlDriver(); if (NULL == pDriver) { return -3; } if (xparam.eType != NFCAsyMysqlModule::ACOTERMYSQLEVENT_SELECT) { return -4; } if (!pDriver->Select(xparam.strRecordName, xparam.strKey, xparam.fieldVec, xparam.valueVec)) { xparam.nRet = -1; } xparam.PackParam(arg); return 0; } int NFCMysqlComponent::OnASyDeleteMysqlEvent(const NFGUID& self, const int event, std::string& arg) { SMysqlBaseParam xparam; if (!xparam.UnPackParam(arg)) { return -1; } if (!m_pMysqlDriverManager.get()) { return -2; } NFIMysqlDriver* pDriver = m_pMysqlDriverManager->GetMysqlDriver(); if (NULL == pDriver) { return -3; } if (xparam.eType != NFCAsyMysqlModule::ACOTERMYSQLEVENT_DELETE) { return -4; } if (!pDriver->Delete(xparam.strRecordName, xparam.strKey)) { xparam.nRet = -1; } xparam.PackParam(arg); return 0; } int NFCMysqlComponent::OnASyExistsMysqlEvent(const NFGUID& self, const int event, std::string& arg) { SMysqlBaseParam xparam; if (!xparam.UnPackParam(arg)) { return -1; } if (!m_pMysqlDriverManager.get()) { return -2; } NFIMysqlDriver* pDriver = m_pMysqlDriverManager->GetMysqlDriver(); if (NULL == pDriver) { return -3; } if (xparam.eType != NFCAsyMysqlModule::ACOTERMYSQLEVENT_EXISTS) { return -4; } bool bExit = false; if (!pDriver->Exists(xparam.strRecordName, xparam.strKey, bExit)) { xparam.bExit = bExit; xparam.nRet = -1; } xparam.PackParam(arg); return 0; } int NFCMysqlComponent::OnASyKeysMysqlEvent(const NFGUID& self, const int event, std::string& arg) { SMysqlBaseParam xparam; if (!xparam.UnPackParam(arg)) { return -1; } if (!m_pMysqlDriverManager.get()) { return -2; } NFIMysqlDriver* pDriver = m_pMysqlDriverManager->GetMysqlDriver(); if (NULL == pDriver) { return -3; } if (xparam.eType != NFCAsyMysqlModule::ACOTERMYSQLEVENT_KEYS) { return -4; } if (!pDriver->Keys(xparam.strRecordName, xparam.strKey, xparam.valueVec)) { xparam.nRet = -1; } xparam.PackParam(arg); return 0; } int NFCMysqlComponent::OnASyAddMysqlServerEvent(const NFGUID& self, const int event, std::string& arg) { NFMsg::PackMysqlServerInfo xMsg; if (!xMsg.ParseFromString(arg)) { return -1; } if (!m_pMysqlDriverManager->AddMysqlServer(xMsg.nserverid(), "", xMsg.strdnsip(), xMsg.nport(), xMsg.strdbname(), xMsg.strdbuser(), xMsg.strdbpwd(), xMsg.nrconnecttime(), xMsg.nrconnecount())) { return -2; } return 0; } int NFCMysqlComponent::OnASyKeepServerAliveEvent(const NFGUID& self, const int event, std::string& arg) { m_pMysqlDriverManager->CheckMysql(); return 0; } NF_SHARE_PTR<NFIComponent> NFCMysqlComponent::CreateNewInstance() { return NF_SHARE_PTR<NFIComponent> (NF_NEW NFCMysqlComponent(NFGUID(1, 2), "")); } NFCAsyMysqlModule::NFCAsyMysqlModule(NFIPluginManager* p) { pPluginManager = p; mnLastCheckTime = 0; } NFCAsyMysqlModule::~NFCAsyMysqlModule() { } bool NFCAsyMysqlModule::Init() { return true; } bool NFCAsyMysqlModule::Shut() { return true; } bool NFCAsyMysqlModule::Execute() { return true; } bool NFCAsyMysqlModule::AfterInit() { m_pActorModule = pPluginManager->FindModule<NFIActorModule>(); StartActorPool(10); return true; } bool NFCAsyMysqlModule::Updata(const NFGUID& self, const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec, const MYSQL_RETURN_FUNCTOR& mFunReturnRsp, const std::string& strUseData) { NF_SHARE_PTR<SMysqlUpDataParam> pParam(NF_NEW SMysqlUpDataParam()); if (NULL == pParam) { return false; } pParam->strRecordName = strRecordName; pParam->strKey = strKey; pParam->fieldVec = fieldVec; pParam->valueVec = valueVec; pParam->nReqID = nCurReqID++; pParam->mFunReturnRsp = mFunReturnRsp; pParam->mstrUseData = strUseData; pParam->self = self; if (ApplyRequest(pParam, pParam->eType) < 0) { return false; } return true; } bool NFCAsyMysqlModule::Query(const NFGUID& self, const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, const MYSQL_RETURN_VECKEY_VECVALUE_FUNCTOR& mFunReturnVeckKeyValueRsp, const std::string& strUseData) { NF_SHARE_PTR<SMysqlQueryParam> pParam(NF_NEW SMysqlQueryParam()); if (NULL == pParam) { return false; } pParam->strRecordName = strRecordName; pParam->strKey = strKey; pParam->fieldVec = fieldVec; pParam->nReqID = nCurReqID++; pParam->mFunReturnVeckKeyValueRsp = mFunReturnVeckKeyValueRsp; pParam->mstrUseData = strUseData; pParam->self = self; if (ApplyRequest(pParam, pParam->eType) < 0) { return false; } return true; } bool NFCAsyMysqlModule::Select(const NFGUID& self, const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, const MYSQL_RETURN_VECKEY_VECVALUE_FUNCTOR& mFunReturnVeckKeyValueRsp, const std::string& strUseData) { NF_SHARE_PTR<SMysqlSelectParam> pParam(NF_NEW SMysqlSelectParam()); if (NULL == pParam) { return false; } pParam->strRecordName = strRecordName; pParam->strKey = strKey; pParam->fieldVec = fieldVec; pParam->nReqID = nCurReqID++; pParam->mFunReturnVeckKeyValueRsp = mFunReturnVeckKeyValueRsp; pParam->mstrUseData = strUseData; pParam->self = self; if (ApplyRequest(pParam, pParam->eType) < 0) { return false; } return true; } bool NFCAsyMysqlModule::Delete(const NFGUID& self, const std::string& strRecordName, const std::string& strKey, const MYSQL_RETURN_FUNCTOR& mFunReturnRsp, const std::string& strUseData) { NF_SHARE_PTR<SMysqlDeleteParam> pParam(NF_NEW SMysqlDeleteParam()); if (NULL == pParam) { return false; } pParam->strRecordName = strRecordName; pParam->strKey = strKey; pParam->nReqID = nCurReqID++; pParam->mFunReturnRsp = mFunReturnRsp; pParam->mstrUseData = strUseData; pParam->self = self; if (ApplyRequest(pParam, pParam->eType) < 0) { return false; } return true; } bool NFCAsyMysqlModule::Exists(const NFGUID& self, const std::string& strRecordName, const std::string& strKey, const MYSQL_RETURN_INT_FUNCTOR& mFunReturnIntRsp, const std::string& strUseData) { NF_SHARE_PTR<SMysqlExistsParam> pParam(NF_NEW SMysqlExistsParam()); if (NULL == pParam) { return false; } pParam->strRecordName = strRecordName; pParam->strKey = strKey; pParam->nReqID = nCurReqID++; pParam->mFunReturnIntRsp = mFunReturnIntRsp; pParam->mstrUseData = strUseData; pParam->self = self; if (ApplyRequest(pParam, pParam->eType) < 0) { return false; } return true; } bool NFCAsyMysqlModule::Keys(const NFGUID& self, const std::string& strRecordName, const std::string& strKeyName, const MYSQL_RETURN_VECVALUE_FUNCTOR& mFunReturnVecValueRsp, const std::string& strUseData) { NF_SHARE_PTR<SMysqlKeysParam> pParam(NF_NEW SMysqlKeysParam()); if (NULL == pParam) { return false; } pParam->strRecordName = strRecordName; pParam->strKey = strKeyName; pParam->nReqID = nCurReqID++; pParam->mFunReturnVecValueRsp = mFunReturnVecValueRsp; pParam->mstrUseData = strUseData; pParam->self = self; if (ApplyRequest(pParam, pParam->eType) < 0) { return false; } return true; } bool NFCAsyMysqlModule::StartActorPool(const int nCount) { for (int i = 0; i < nCount; i++) { int nActorID = m_pActorModule->RequireActor<NFCMysqlComponent>(this, &NFCAsyMysqlModule::RequestAsyEnd); if (nActorID > 0) { mActorList.AddElement(i, NF_SHARE_PTR<int> (NF_NEW int(nActorID))); } } return true; } bool NFCAsyMysqlModule::CloseActorPool() { int nActor = 0; for (NF_SHARE_PTR<int> pData = mActorList.First(nActor); pData != NULL; pData = mActorList.Next(nActor)) { m_pActorModule->ReleaseActor(nActor); } mActorList.ClearAll(); return true; } int NFCAsyMysqlModule::ApplyRequest(NF_SHARE_PTR<SMysqlBaseParam> pParam, const int nEvetID/* = ACOTERMYSQLEVENT_USEDB*/) { int nAcotrID = GetActor(); if (nAcotrID <= 0) { return -2; } std::string arg; if (!pParam->PackParam(arg)) { return -3; } if (!mReqList.AddElement(pParam->nReqID, pParam)) { return -4; } if (!m_pActorModule->SendMsgToActor(nAcotrID, pParam->self, nEvetID, arg)) { mReqList.RemoveElement(pParam->nReqID); return -5; } return 0; } int NFCAsyMysqlModule::RequestAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { int nRet = 0; switch (nEventID) { case NFCAsyMysqlModule::ACOTERMYSQLEVENT_UPDATA: { nRet = OnUpDataMysqlAsyEnd(self, nFormActor, nEventID, strData); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_QUERY: { nRet = OnQueryMysqlAsyEnd(self, nFormActor, nEventID, strData); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_SELECT: { nRet = OnSelectMysqlAsyEnd(self, nFormActor, nEventID, strData); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_DELETE: { nRet = OnDeleteMysqlAsyEnd(self, nFormActor, nEventID, strData); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_EXISTS: { nRet = OnExistsMysqlAsyEnd(self, nFormActor, nEventID, strData); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_KEYS: { nRet = OnUpKeyMysqlAsyEnd(self, nFormActor, nEventID, strData); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_INISERVER: { nRet = OnAddMysqlServerAsyEnd(self, nFormActor, nEventID, strData); } break; case NFCAsyMysqlModule::ACOTERMYSQLEVENT_KEEPALIVESERVER: { nRet = OnKeepServerAliveAsyEnd(self, nFormActor, nEventID, strData); } break; default: break; } return nRet; } int NFCAsyMysqlModule::GetActor() { if (mActorList.Count() <= 0) { return -1; } mnSuitIndex ++; mnSuitIndex = mnSuitIndex % mActorList.Count(); int i = 0; for (int* pData = mActorList.FirstNude(); pData != NULL ; pData = mActorList.NextNude()) { if (i < mActorList.Count() && i == mnSuitIndex) { return *pData; } ++i; } return -1; } bool NFCAsyMysqlModule::AddMysqlServer(const int nServerID, const std::string& strDns, const std::string& strIP, const int nPort, const std::string strDBName, const std::string strDBUser, const std::string strDBPwd, const int nRconnectTime /*= 10*/, const int nRconneCount /*= -1*/) { NFMsg::PackMysqlServerInfo xMsg; xMsg.set_nrconnecttime(nRconnectTime); xMsg.set_nrconnecount(nRconneCount); xMsg.set_nport(nPort); xMsg.set_strdbname(strDBName); xMsg.set_strdnsip(strIP); xMsg.set_strdbuser(strDBUser); xMsg.set_strdbpwd(strDBPwd); xMsg.set_nserverid(nServerID); std::string arg; if (!xMsg.SerializeToString(&arg)) { return false; } const int nEvetID = ACOTERMYSQLEVENT_INISERVER; for (int* pData = mActorList.FirstNude(); pData != NULL ; pData = mActorList.NextNude()) { int nAcotrID = *pData; m_pActorModule->SendMsgToActor(nAcotrID, NFGUID(), nEvetID, arg); } return true; } bool NFCAsyMysqlModule::KeepAliveMysqlServer() { std::string arg; const int nEvetID = ACOTERMYSQLEVENT_KEEPALIVESERVER; for (int* pData = mActorList.FirstNude(); pData != NULL ; pData = mActorList.NextNude()) { int nAcotrID = *pData; m_pActorModule->SendMsgToActor(nAcotrID, NFGUID(), nEvetID, arg); } return true; } int NFCAsyMysqlModule::OnUpDataMysqlAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { SMysqlUpDataParam* pReqData = UnpackResult<SMysqlUpDataParam>(strData); if (NULL == pReqData) { return -3; } if (pReqData->mFunReturnRsp) { pReqData->mFunReturnRsp(pReqData->self, pReqData->nRet, pReqData->mstrUseData); } mReqList.RemoveElement(pReqData->nReqID); return 0; } int NFCAsyMysqlModule::OnQueryMysqlAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { SMysqlQueryParam* pReqData = UnpackResult<SMysqlQueryParam>(strData); if (NULL == pReqData) { return -3; } if (pReqData->mFunReturnVeckKeyValueRsp) { pReqData->mFunReturnVeckKeyValueRsp(pReqData->self, pReqData->nRet, pReqData->fieldVec, pReqData->valueVec, pReqData->mstrUseData); } mReqList.RemoveElement(pReqData->nReqID); return 0; } int NFCAsyMysqlModule::OnSelectMysqlAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { SMysqlSelectParam* pReqData = UnpackResult<SMysqlSelectParam>(strData); if (NULL == pReqData) { return -3; } if (pReqData->mFunReturnVeckKeyValueRsp) { pReqData->mFunReturnVeckKeyValueRsp(pReqData->self, pReqData->nRet, pReqData->fieldVec, pReqData->valueVec, pReqData->mstrUseData); } mReqList.RemoveElement(pReqData->nReqID); return 0; } int NFCAsyMysqlModule::OnDeleteMysqlAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { SMysqlDeleteParam* pReqData = UnpackResult<SMysqlDeleteParam>(strData); if (NULL == pReqData) { return -3; } if (pReqData->mFunReturnRsp) { pReqData->mFunReturnRsp(pReqData->self, pReqData->nRet, pReqData->mstrUseData); } mReqList.RemoveElement(pReqData->nReqID); return 0; } int NFCAsyMysqlModule::OnExistsMysqlAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { SMysqlExistsParam* pReqData = UnpackResult<SMysqlExistsParam>(strData); if (NULL == pReqData) { return -3; } if (pReqData->mFunReturnIntRsp) { pReqData->mFunReturnIntRsp(pReqData->self, pReqData->nRet, pReqData->bExit, pReqData->mstrUseData); } mReqList.RemoveElement(pReqData->nReqID); return 0; } int NFCAsyMysqlModule::OnUpKeyMysqlAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { SMysqlKeysParam* pReqData = UnpackResult<SMysqlKeysParam>(strData); if (NULL == pReqData) { return -3; } if (pReqData->mFunReturnVecValueRsp) { pReqData->mFunReturnVecValueRsp(pReqData->self, pReqData->nRet, pReqData->valueVec, pReqData->mstrUseData); } mReqList.RemoveElement(pReqData->nReqID); return 0; } int NFCAsyMysqlModule::OnAddMysqlServerAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { return 0; } int NFCAsyMysqlModule::OnKeepServerAliveAsyEnd(const NFGUID& self, const int nFormActor, const int nEventID, const std::string& strData) { return 0; } template<typename ClassParam> ClassParam* NFCAsyMysqlModule::UnpackResult(const std::string& strMsgData) { SMysqlBaseParam xResultparam; if (!xResultparam.UnPackParam(strMsgData)) { return NULL; } NF_SHARE_PTR<SMysqlBaseParam> pReqBaseData = mReqList.GetElement(xResultparam.nReqID); if (NULL == pReqBaseData) { return NULL; } ClassParam* pReqData = dynamic_cast<ClassParam*>(pReqBaseData.get()); if (NULL == pReqData) { return NULL; } pReqData->valueVec = xResultparam.valueVec; pReqData->bExit = xResultparam.bExit; pReqData->nRet = xResultparam.nRet; return pReqData; }
#include <sandshark_common/condition.h> #include <cstddef> #include <sandshark_msgs/ApplicationAbort.h> #include <sandshark_msgs/LEDCommand.h> namespace bluefin { namespace sandshark { ConditionManager *ConditionManager::_instance = NULL; void AbortAction::createPublisher(ros::NodeHandle *node) { _abortPub = node->advertise<sandshark_msgs::ApplicationAbort>("/objectivecontrol/abort", 1); } void AbortAction::execute(std::string reason) { ROS_ERROR("AbortAction activated! Reason = %s", reason.c_str()); sandshark_msgs::ApplicationAbort amsg; amsg.abort = true; amsg.reason = reason; _abortPub.publish(amsg); } void SolidRedLEDAction::createPublisher(ros::NodeHandle *node) { _redLEDPub = node->advertise<sandshark_msgs::LEDCommand>("/ledcontrol/red", 1); } void SolidRedLEDAction::execute(std::string reason) { sandshark_msgs::LEDCommand msg; msg.command = sandshark_msgs::LEDCommand::COMMAND_ON; _redLEDPub.publish(msg); } void SolidAllLEDAction::createPublisher(ros::NodeHandle *node) { _redLEDPub = node->advertise<sandshark_msgs::LEDCommand>("/ledcontrol/red", 1); _greenLEDPub = node->advertise<sandshark_msgs::LEDCommand>("/ledcontrol/green", 1); _amberLEDPub = node->advertise<sandshark_msgs::LEDCommand>("/ledcontrol/amber", 1); } void SolidAllLEDAction::execute(std::string reason) { sandshark_msgs::LEDCommand msg; msg.command = sandshark_msgs::LEDCommand::COMMAND_ON; _redLEDPub.publish(msg); _greenLEDPub.publish(msg); _amberLEDPub.publish(msg); } void ConditionManager::executeTriggeredConditions() { for (std::vector<Condition *>::iterator iter = _orderedConditions.begin(); iter != _orderedConditions.end(); ++iter) { if ((*iter)->isTriggered()) { std::map<Condition *, std::set<Action *> >::iterator actIter = _conditionToActions.find(*iter); if (actIter != _conditionToActions.end()) { for (std::set<Action *>::iterator actSet = actIter->second.begin(); actSet != actIter->second.end(); ++actSet) { (*actSet)->execute(actIter->first->getReason()); } } else { ROS_WARN("No Action for triggered condition"); } } } } void ConditionManager::updateAbortAction(ros::NodeHandle * node) { _abortAction->createPublisher(node); } void ConditionManager::updateSolidRedLEDAction(ros::NodeHandle * node) { _solidRedLEDAction->createPublisher(node); } void ConditionManager::updateSolidAllLEDAction(ros::NodeHandle * node) { _solidAllLEDAction->createPublisher(node); } bool ConditionManager::addCondition(ros::NodeHandle * node, Condition * cond) { std::string topic = cond->getTopicName(); std::map<std::string, std::vector<Condition *> >::iterator iter = _topicToConditions.find(topic); if (iter == _topicToConditions.end()) { _topicToSub[topic] = node->subscribe<topic_tools::ShapeShifter>(topic, 1, boost::bind(&ConditionManager::msgCallback, this, _1, topic)); } //Check for same condition insertion? _topicToConditions[topic].push_back(cond); _orderedConditions.push_back(cond); std::sort(_orderedConditions.begin(), _orderedConditions.end(), ConditionCompare()); return false; } void ConditionManager::msgCallback(const topic_tools::ShapeShifter::ConstPtr & msg, const std::string & topic) { std::map<std::string, std::vector<Condition *> >::iterator iter = _topicToConditions.find(topic); if (iter != _topicToConditions.end()) { for (std::vector<Condition *>::iterator viter = _topicToConditions[topic].begin(); viter != _topicToConditions[topic].end(); ++viter) { (*viter)->processMessage(msg); } } } void ConditionManager::linkConditionToAction(Condition *cond, Action *act) { _conditionToActions[cond].insert(act); } } }
/* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #include "PiiImage.h" #include <PiiMatrixUtil.h> namespace PiiImage { PiiMatrix<int> sobelX(3, 3, -1, 0, 1, -2, 0, 2, -1, 0, 1); PiiMatrix<int> sobelY(3, 3, -1,-2,-1, 0, 0, 0, 1, 2, 1); PiiMatrix<int> robertsX(2, 2, 1, 0, 0, -1); PiiMatrix<int> robertsY(2, 2, 0, 1, -1, 0); PiiMatrix<int> prewittX(3, 3, -1, 0, 1, -1, 0, 1, -1, 0, 1); PiiMatrix<int> prewittY(3, 3, -1,-1,-1, 0, 0, 0, 1, 1, 1); PiiMatrix<double> makeGaussian(unsigned int size) { size |= 1; // make odd PiiMatrix<double> matResult(PiiMatrix<double>::uninitialized(size,size)); int iCenter = size / 2; // Cut the filter at 2 times std double dSigma = double(iCenter) / 2.0; double dExponentScale = -0.5 / (dSigma * dSigma); double dSum = 0; for (int r = -iCenter; r <= iCenter; ++r) for (int c = -iCenter; c <= iCenter; ++c) { double dVal = exp((r * r + c * c) * dExponentScale); dSum += dVal; matResult(r + iCenter, c + iCenter) = dVal; } matResult /= dSum; return matResult; } PiiMatrix<double> makeLoGaussian(unsigned int size) { size |= 1; // make odd PiiMatrix<double> matResult(PiiMatrix<double>::uninitialized(size,size)); int iCenter = size / 2; // Cut the filter at 3 times std double dSigma = double(iCenter) / 3.0; double dExponentScale = -0.5 / (dSigma * dSigma); double dMean = 0; for (int r = -iCenter; r <= iCenter; ++r) for (int c = -iCenter; c <= iCenter; ++c) { double dExponent = dExponentScale * (c * c + r * r); double dVal = (1 + dExponent) * exp(dExponent); dMean += dVal; matResult(r + iCenter, c + iCenter) = dVal; } dMean /= size * size; // The maximum value is now 1 at the center. matResult -= dMean; // Max is now 1 - dMean -> scale so that the center is -4. matResult *= -4.0 / (1.0 - dMean); return matResult; } static inline bool nonZeroSums(int iSum, double dSum) { return iSum != 0 && !Pii::almostEqualRel(dSum, 0.0) && Pii::sign(iSum) == Pii::sign(dSum); } PiiMatrix<int> intFilter(const PiiMatrix<int>& image, const PiiMatrix<double>& doubleFilter, Pii::ExtendMode mode, double scale) { if (scale == 0) { double dMax = Pii::maxAbs(doubleFilter); if (dMax != 0) scale = 256.0 / dMax; } PiiMatrix<int> integerFilter(Pii::round<int>(doubleFilter * scale)); int iSum = Pii::sum<int>(integerFilter); double dSum = Pii::sum<double>(doubleFilter); //qDebug("%d %lg", iSum, dSum); if (nonZeroSums(iSum, dSum)) scale = iSum / dSum; PiiMatrix<int> filtered = filter<int>(image, integerFilter, mode); filtered.map(Pii::unaryCompose(Pii::Round<double,int>(), std::bind2nd(std::multiplies<double>(), 1.0/scale))); return filtered; } PiiMatrix<int> intFilter(const PiiMatrix<int>& image, const PiiMatrix<double>& horizontalFilter, const PiiMatrix<double>& verticalFilter, Pii::ExtendMode mode, double scale) { if (horizontalFilter.rows() != 1 || verticalFilter.columns() != 1) return image; double hMax = Pii::maxAbs(horizontalFilter), vMax = Pii::maxAbs(verticalFilter); if (hMax == 0) hMax = 1; if (vMax == 0) vMax = 1; double dHScale = scale == 0 ? 64.0 / hMax : scale; double dVScale = scale == 0 ? 64.0 / vMax : scale; // Scale the filters and round to int PiiMatrix<int> horizontalIntegerFilter(Pii::round<int>(horizontalFilter * dHScale)); PiiMatrix<int> verticalIntegerFilter(Pii::round<int>(verticalFilter * dVScale)); // Recalculate the real scale (after rounding) int iHSum = Pii::sum<int>(horizontalIntegerFilter), iVSum = Pii::sum<int>(verticalIntegerFilter); double dHSum = Pii::sum<double>(horizontalFilter), dVSum = Pii::sum<double>(verticalFilter); if (nonZeroSums(iHSum, dHSum)) dHScale = double(iHSum) / dHSum; if (nonZeroSums(iVSum, dVSum)) dVScale = double(iVSum) / dVSum; if (mode == Pii::ExtendZeros) { PiiMatrix<int> filtered = PiiDsp::filter<int>(PiiDsp::filter<int>(image, horizontalIntegerFilter, PiiDsp::FilterOriginalSize), verticalIntegerFilter, PiiDsp::FilterOriginalSize); // Readable? Not. Scales each element as doubles and rounds // the result to an int. filtered.map(Pii::unaryCompose(Pii::Round<double,int>(), std::bind2nd(std::multiplies<double>(), 1.0/(dVScale*dHScale)))); return filtered; } const int rows = verticalFilter.rows() >> 1, cols = horizontalFilter.columns() >> 1; PiiMatrix<int> filtered = PiiDsp::filter<int>(PiiDsp::filter<int>(Pii::extend(image, rows, rows, cols, cols, mode), horizontalIntegerFilter, PiiDsp::FilterValidPart), verticalIntegerFilter, PiiDsp::FilterValidPart); // Scale back, see above filtered.map(Pii::unaryCompose(Pii::Round<double,int>(), std::bind2nd(std::multiplies<double>(), 1.0/(dVScale*dHScale)))); return filtered; } PiiMatrix<float> createRotationTransform(float theta) { float fSin = Pii::sin(theta), fCos = Pii::cos(theta); return PiiMatrix<float>(3,3, fCos, -fSin, 0.0, fSin, fCos, 0.0, 0.0, 0.0, 1.0); } PiiMatrix<float> createRotationTransform(float theta, float centerX, float centerY) { // Move origin to the new center, rotate, and move back return createTranslationTransform(centerX, centerY) * createRotationTransform(theta) * createTranslationTransform(-centerX, -centerY); } PiiMatrix<float> createShearingTransform(float shearX, float shearY) { return PiiMatrix<float>(3,3, 1.0, shearX, 0.0, shearY, 1.0, 0.0, 0.0, 0.0, 1.0); } PiiMatrix<float> createTranslationTransform(float x, float y) { return PiiMatrix<float>(3,3, 1.0, 0.0, x, 0.0, 1.0, y, 0.0, 0.0, 1.0); } PiiMatrix<float> createScalingTransform(float scaleX, float scaleY) { return PiiMatrix<float>(3,3, scaleX, 0.0, 0.0, 0.0, scaleY, 0.0, 0.0, 0.0, 1.0); } PiiMatrix<bool> createRoiMask(int rows, int columns, const PiiMatrix<int>& rectangles) { PiiMatrix<bool> result(rows, columns); for (int r=0; r<rows; ++r) { const PiiRectangle<int>& rect = rectangles.rowAs<PiiRectangle<int> >(r); if (rect.x >=0 && rect.x < columns && rect.y >=0 && rect.y < rows && rect.width > 0 && rect.height > 0 && rect.x + rect.width <= columns && rect.y + rect.height <= rows) result(rect.y, rect.x, rect.height, rect.width) = true; } return result; } bool overlapping(const PiiMatrix<int>& rectangles) { const int iRows = rectangles.rows(); if (iRows <= 1) return false; for (int r1=0; r1<iRows; ++r1) { const PiiRectangle<int>& rect = rectangles.rowAs<PiiRectangle<int> >(r1); for (int r2=r1+1; r2<iRows; ++r2) if (rect.intersects(rectangles.rowAs<PiiRectangle<int> >(r2))) return true; } return false; } PiiMatrix<bool> alphaToMask(const PiiMatrix<PiiColor4<> >& image) { const int iRows = image.rows(), iColumns = image.columns(); PiiMatrix<bool> matMask(PiiMatrix<bool>::uninitialized(iRows, iColumns)); for (int r=0; r<iRows; ++r) { const PiiColor4<>* pSourceRow = image[r]; bool* pTargetRow = matMask[r]; for (int c=0; c<iColumns; ++c) pTargetRow[c] = !!pSourceRow[c].rgbaA; } return matMask; } }
// See LICENSE_CELLO file for license and copyright information /// @file parameters_ParamNode.hpp /// @author James Bordner (jobordner@ucsd.edu) /// @date Mon May 10 12:43:27 PDT 2010 /// @brief [\ref Parameters] Node for representing parameters in a /// tree of groups / subgroups /parameters /values #ifndef PARAMETERS_PARAM_NODE_HPP #define PARAMETERS_PARAM_NODE_HPP class ParamNode { /// @class ParamNode /// @ingroup Parameters /// @brief [\ref Parameters] Node representing a subtree of parameters public: // interface /// Constructor ParamNode(std::string name) throw() : name_(name), subnodes_() {}; //---------------------------------------------------------------------- // Big Three //---------------------------------------------------------------------- /// Destructor ~ParamNode() throw() { std::map<std::string,ParamNode *>::iterator it_param; for (it_param = subnodes_.begin(); it_param != subnodes_.end(); ++it_param) { delete it_param->second; } }; private: // No copy or assign /// Copy constructor ParamNode(const ParamNode & param_node) throw() { } /// Assignment operator ParamNode & operator= (const ParamNode & param_node) throw() { return *this; } public: // interface /// CHARM++ Pack / Unpack function inline void pup (PUP::er &p) { TRACEPUP; // NOTE: change this function whenever attributes change p | name_; WARNING("ParamNode::pup","skipping subnodes_ [ map<string,Param*> ]"); // p | subnodes_; } /// Return the node name std::string name() const {return name_;}; /// Return the number of subgroups int size() {return subnodes_.size(); } /// Return the ith subgroup std::string subgroup (int group_index) { if (0 <= group_index && group_index < size()) { std::map<std::string,ParamNode *>::iterator it_param; int i; for (i=0,it_param = subnodes_.begin(); it_param != subnodes_.end(); ++it_param,i++) { if (group_index == i) { return it_param->first; } } } return ""; }; /// Return the given subnode, returning 0 if it doesn't exist ParamNode * subnode(std::string subgroup) { return subnodes_[subgroup]; } /// Return the given subgroup, creating a new one if it doesn't exist ParamNode * new_subnode(std::string subgroup) { if (subnodes_[subgroup] == 0) { subnodes_[subgroup] = new ParamNode(subgroup); } return subnodes_[subgroup]; } private: // attributes /// Subnodes of the tree std::string name_; std::map<std::string, ParamNode *> subnodes_; }; #endif /* PARAMETERS_PARAM_NODE_HPP */
/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for license. */ //-----------------------------------NOTICE----------------------------------// // Some of this file is automatically filled in by a Python script. Only // // add custom code in the designated areas or it will be overwritten during // // the next update. // //-----------------------------------NOTICE----------------------------------// //--BEGIN FILE HEAD CUSTOM CODE--// //--END CUSTOM CODE--// #include "../../include/FixLink.h" #include "../../include/ObjectRegistry.h" #include "../../include/NIF_IO.h" #include "../../include/obj/NiProperty.h" using namespace Niflib; //Definition of TYPE constant const Type NiProperty::TYPE("NiProperty", &NiObjectNET::TYPE ); NiProperty::NiProperty() { //--BEGIN CONSTRUCTOR CUSTOM CODE--// //--END CUSTOM CODE--// } NiProperty::~NiProperty() { //--BEGIN DESTRUCTOR CUSTOM CODE--// //--END CUSTOM CODE--// } const Type & NiProperty::GetType() const { return TYPE; } NiObject * NiProperty::Create() { return new NiProperty; } void NiProperty::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) { //--BEGIN PRE-READ CUSTOM CODE--// //--END CUSTOM CODE--// NiObjectNET::Read( in, link_stack, info ); //--BEGIN POST-READ CUSTOM CODE--// //--END CUSTOM CODE--// } void NiProperty::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const { //--BEGIN PRE-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// NiObjectNET::Write( out, link_map, missing_link_stack, info ); //--BEGIN POST-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// } std::string NiProperty::asString( bool verbose ) const { //--BEGIN PRE-STRING CUSTOM CODE--// //--END CUSTOM CODE--// stringstream out; out << NiObjectNET::asString(); return out.str(); //--BEGIN POST-STRING CUSTOM CODE--// //--END CUSTOM CODE--// } void NiProperty::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info ) { //--BEGIN PRE-FIXLINKS CUSTOM CODE--// //--END CUSTOM CODE--// NiObjectNET::FixLinks( objects, link_stack, missing_link_stack, info ); //--BEGIN POST-FIXLINKS CUSTOM CODE--// //--END CUSTOM CODE--// } std::list<NiObjectRef> NiProperty::GetRefs() const { list<Ref<NiObject> > refs; refs = NiObjectNET::GetRefs(); return refs; } std::list<NiObject *> NiProperty::GetPtrs() const { list<NiObject *> ptrs; ptrs = NiObjectNET::GetPtrs(); return ptrs; } //--BEGIN MISC CUSTOM CODE--// //--END CUSTOM CODE--//
#pragma once namespace Sonar { class RBM // Rapid Button Masher { public: /** * \brief Class constructor */ RBM( const float &threshold, const float &amountToTickUp, const Time &tickDownTime, const float &tickDownAmount ); /** * \brief Class destructor */ ~RBM( ); /** * \brief Get the start status * * \return Output returns the started status (true or false) */ bool HasStarted( ) const; /** * \brief Checks if the RBM is complete * * \return Output returns the complete status of the RBM */ bool IsComplete( ) const; /** * \brief Get the RBM clock * * \return Output returns the RBM clock */ Clock GetClock( ) const; /** * \brief Update the RBM */ void Update( ); /** * \brief Restart the RBM (reset event position back to 0) */ void Restart( ); /** * \brief Get the number of failures * * \return Output returns the RBM failure count */ int GetFailureCount( ) const; /** * \brief Tick up the RBM counter */ void TickUp( ); /** * \brief Get the count of the RBM * * \return Output returns the RBM counter */ float GetCounter( ) const; private: /** * \brief Has the RBM begun (has the user pressed the first input) */ bool _started; /** * \brief Amount to get to in the RBM */ float _thresholdGoal; /** * \brief Per press amount to add to counter */ float _amountToTickUp; /** * \brief Period after which the counter goes down */ Time _tickDownTime; /** * \brief Amount for counter to go down */ float _tickDownAmount; /** * \brief Progress of the RBM */ float _counter; /** * \brief Clock to track the RBM countdown between events */ Clock _clock; /** * \brief How many times has the RBM failed */ int _failureCount; }; }
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- Header Order Module. * * This modules tracks header presence and order, exposing that information * in a var. * * By default, the module tracks the headers listed at * `c_default_request_config` and `c_default_response_config` * abbreviating each with a camel cased abbreviation. The user can define a * different list via directives on a per-context basis. * * The result is stored at the REQUEST_HEADER and RESPONSE_HEADER phases in * the vars named by `c_request_var` and `c_response_var`. * * Case in header keys is ignored. * * @author Christopher Alfeld <calfeld@qualys.com> */ #include <ironbeepp/all.hpp> #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wunused-local-typedef") #pragma clang diagnostic ignored "-Wunused-local-typedef" #endif #endif #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/bind.hpp> #ifdef __clang__ #pragma clang diagnostic pop #endif using boost::bind; using namespace std; using namespace IronBee; namespace { // CONFIGURATION //! Default configuration for request headers. static const char* c_default_request_config = "H=Host " "U=User-Agent " "A=Accept " "E=Accept-Encoding " "L=Accept-Language " "N=Transfer-Encoding " "N=TE " "P=Pragma " "C=Cache-Control " "O=Cookie " "T=Content-Type " "L=Content-Length " "I=Connection " "R=Referer " "G=Range " ; //! Default configuration for response headers. static const char* c_default_response_config = "S=Server " "A=Location " "N=Transfer-Encoding " "N=TE " "D=Date " "M=Last-Modified " "C=Cache-Control " "O=Set-Cookie " "T=Content-Type " "L=Content-Length " "E=Content-Encoding " "L=Content-Language " "I=Connection " "X=Expires " "V=Via " "Y=Vary " "R=Trailer " ; //! Var to store request header order in. static const char* c_request_var = "REQUEST_HEADER_ORDER"; //! Var to store response header order in. static const char* c_response_var = "RESPONSE_HEADER_ORDER"; //! Directive to configure request header order. static const char* c_request_directive = "HeaderOrderRequest"; //! Directive to configure response header order. static const char* c_response_directive = "HeaderOrderResponse"; // END CONFIGURATION //! Map of header key to abbreviation. Keys must be lowercase. typedef map<string, string> header_map_t; //! Per context data. struct PerContext { //! Map of header key to abbreviation for request headers. header_map_t request; //! Map of header key to abbreviation for response headers. header_map_t response; }; /** * Configure a header map. * * @param[in] header_map Header map to configure. * @param[in] config Configuration string. **/ void configure_header_map( header_map_t& header_map, const char* config ); //! Module delegate. class Delegate : public ModuleDelegate { public: //! Constructor. explicit Delegate(Module module); private: /** * Handle @ref c_request_directive and @ref c_response_directive. * * @param[in] request True if request, false if response. * @param[in] cp Configuration parser. * @param[in] name Name of directive. * @param[in] config Configuration string. * @throws einval on failure. **/ void order_directive( bool request, ConfigurationParser cp, const char* name, const char* config ); /** * Handle REQUEST_HEADER and RESPONSE_HEADER phase. * * @param[in] tx Current transaction. * @param[in] state Which state fired for. **/ void handle_header_state( Transaction tx, Engine::state_e state ) const; //! Request header order var. @sa c_request_var. VarSource m_request_var; //! Response header order var. @sa c_response_var. VarSource m_response_var; }; } // Anonymous namespace IBPP_BOOTSTRAP_MODULE_DELEGATE("header_order", Delegate) // Implementation // PerContext // Keep doxygen happy. namespace { void configure_header_map( header_map_t& header_map, const char* config ) { header_map.clear(); list<string> parts; boost::algorithm::split(parts, config, boost::is_any_of(" \t\r\n")); BOOST_FOREACH(const string& part, parts) { if (part.empty()) { continue; } size_t equal_pos = part.find_first_of('='); if (equal_pos == string::npos) { BOOST_THROW_EXCEPTION( einval() << errinfo_what( part + " does not match key=abbreviation." ) ); } string abbrev = part.substr(0, equal_pos); string key = part.substr(equal_pos + 1); transform(key.begin(), key.end(), key.begin(), ::tolower); header_map.insert(header_map_t::value_type(key, abbrev)); } } Delegate::Delegate(Module module) : ModuleDelegate(module) { assert(module); Engine engine = module.engine(); PerContext base; configure_header_map(base.request, c_default_request_config); configure_header_map(base.response, c_default_response_config); module.set_configuration_data<PerContext>(base); engine.register_hooks() .request_header_finished( bind(&Delegate::handle_header_state, this, _2, _3) ) .response_header_finished( bind(&Delegate::handle_header_state, this, _2, _3) ) ; engine.register_configuration_directives() .param1( c_request_directive, bind(&Delegate::order_directive, this, true, _1, _2, _3) ) .param1( c_response_directive, bind(&Delegate::order_directive, this, false, _1, _2, _3) ) ; m_request_var = VarSource::register_(engine.var_config(), c_request_var); m_response_var = VarSource::register_(engine.var_config(), c_response_var); } void Delegate::order_directive( bool request, ConfigurationParser cp, const char* name, const char* config ) { assert(cp); assert(config); PerContext& per_context = module().configuration_data<PerContext>(cp.current_context()); header_map_t* header_map = request ? &per_context.request : &per_context.response; configure_header_map(*header_map, config); } void Delegate::handle_header_state( Transaction tx, Engine::state_e state ) const { assert(tx); PerContext& per_context = module().configuration_data<PerContext>(tx.context()); const header_map_t* header_map; VarSource var_source; ConstParsedHeader header; if (state == Engine::request_header_finished) { header_map = &per_context.request; var_source = m_request_var; header = tx.request_header(); } else if (state == Engine::response_header_finished) { header_map = &per_context.response; var_source = m_response_var; header = tx.response_header(); } else { BOOST_THROW_EXCEPTION( eother() << errinfo_what( "Insanity: Handle header state handler called" " for non-handle header state." ) ); } string result; string key; header_map_t::const_iterator key_i; while (header) { key = header.name().to_s(); transform(key.begin(), key.end(), key.begin(), ::tolower); key_i = header_map->find(key); if (key_i != header_map->end()) { result += key_i->second; } header = header.next(); } var_source.set( tx.var_store(), Field::create_byte_string( tx.memory_manager(), "", 0, ByteString::create( tx.memory_manager(), result.data(), result.length() ) ) ); } }
#include "LinkKinematicsKit.h" #include "Body.h" #include "JointPath.h" #include "JointPathConfigurationHandler.h" #include "CompositeBodyIK.h" #include "HolderDevice.h" #include "AttachmentDevice.h" #include <cnoid/LinkCoordinateFrameSet> using namespace std; using namespace cnoid; namespace cnoid { class LinkKinematicsKit::Impl { public: BodyPtr body; LinkPtr link; Vector3 referenceRpy; bool isRpySpecified; shared_ptr<InverseKinematics> inverseKinematics; shared_ptr<JointPath> jointPath; shared_ptr<JointPathConfigurationHandler> configurationHandler; LinkCoordinateFrameSetPtr frameSets; GeneralId currentFrameId[3]; int currentBaseFrameType; Signal<void()> sigCurrentFrameChanged; Impl(Link* link); void setBaseLink(Link* link); void setInversetKinematics(std::shared_ptr<InverseKinematics> ik); void setFrameSets(LinkCoordinateFrameSet* frameSets); }; } LinkKinematicsKit::LinkKinematicsKit(Link* link) { impl = new Impl(link); } LinkKinematicsKit::Impl::Impl(Link* link) : link(link), referenceRpy(Vector3::Zero()), currentFrameId{ 0, 0, 0 }, currentBaseFrameType(WorldFrame) { if(link){ body = link->body(); } } LinkKinematicsKit::~LinkKinematicsKit() { delete impl; } void LinkKinematicsKit::setBaseLink(Link* baseLink) { impl->setBaseLink(baseLink); } void LinkKinematicsKit::Impl::setBaseLink(Link* baseLink) { jointPath.reset(); inverseKinematics.reset(); configurationHandler.reset(); if(baseLink && baseLink->body() == body){ jointPath = JointPath::getCustomPath(body, baseLink, link); if(jointPath){ inverseKinematics = jointPath; if(jointPath->hasCustomIK()){ configurationHandler = dynamic_pointer_cast<JointPathConfigurationHandler>(jointPath); } } } } void LinkKinematicsKit::setInversetKinematics(std::shared_ptr<InverseKinematics> ik) { impl->setInversetKinematics(ik); } void LinkKinematicsKit::Impl::setInversetKinematics(std::shared_ptr<InverseKinematics> ik) { jointPath.reset(); inverseKinematics.reset(); configurationHandler.reset(); inverseKinematics = ik; if(auto compositeBodyIK = dynamic_pointer_cast<CompositeBodyIK>(ik)){ configurationHandler = dynamic_pointer_cast<JointPathConfigurationHandler>( compositeBodyIK->getParentBodyIK()); } else { configurationHandler = dynamic_pointer_cast<JointPathConfigurationHandler>(ik); } jointPath = dynamic_pointer_cast<JointPath>(ik); } void LinkKinematicsKit::setFrameSets(LinkCoordinateFrameSet* frameSets) { impl->setFrameSets(frameSets); } void LinkKinematicsKit::Impl::setFrameSets(LinkCoordinateFrameSet* frameSets) { this->frameSets = frameSets; } Body* LinkKinematicsKit::body() { return impl->body; } Link* LinkKinematicsKit::link() { return impl->link; } Link* LinkKinematicsKit::baseLink() { if(impl->jointPath){ return impl->jointPath->baseLink(); } return nullptr; } std::shared_ptr<InverseKinematics> LinkKinematicsKit::inverseKinematics() { return impl->inverseKinematics; } std::shared_ptr<JointPath> LinkKinematicsKit::jointPath() { return impl->jointPath; } std::shared_ptr<JointPathConfigurationHandler> LinkKinematicsKit::configurationHandler() { return impl->configurationHandler; } int LinkKinematicsKit::currentConfiguration() const { if(impl->configurationHandler){ impl->configurationHandler->getCurrentConfiguration(); } return 0; } std::string LinkKinematicsKit::configurationName(int index) const { if(impl->configurationHandler){ return impl->configurationHandler->getConfigurationName(index); } return std::string(); } Vector3 LinkKinematicsKit::referenceRpy() const { return impl->referenceRpy; } void LinkKinematicsKit::setReferenceRpy(const Vector3& rpy) { impl->referenceRpy = rpy; } void LinkKinematicsKit::resetReferenceRpy() { impl->referenceRpy.setZero(); } bool LinkKinematicsKit::isManipulator() const { if(impl->body && impl->link && impl->link == impl->body->findUniqueEndLink() && impl->configurationHandler){ return true; } return false; } LinkCoordinateFrameSet* LinkKinematicsKit::frameSets() { return impl->frameSets; } CoordinateFrameSet* LinkKinematicsKit::frameSet(int frameType) { return impl->frameSets->frameSet(frameType); } CoordinateFrameSet* LinkKinematicsKit::worldFrameSet() { return impl->frameSets->worldFrameSet(); } CoordinateFrameSet* LinkKinematicsKit::bodyFrameSet() { return impl->frameSets->bodyFrameSet(); } CoordinateFrameSet* LinkKinematicsKit::endFrameSet() { return impl->frameSets->endFrameSet(); } CoordinateFrame* LinkKinematicsKit::worldFrame(const GeneralId& id) { return impl->frameSets->worldFrame(id); } CoordinateFrame* LinkKinematicsKit::bodyFrame(const GeneralId& id) { return impl->frameSets->bodyFrame(id); } CoordinateFrame* LinkKinematicsKit::endFrame(const GeneralId& id) { return impl->frameSets->endFrame(id); } const GeneralId& LinkKinematicsKit::currentFrameId(int frameType) { return impl->currentFrameId[frameType]; } const GeneralId& LinkKinematicsKit::currentWorldFrameId() { return impl->currentFrameId[WorldFrame]; } const GeneralId& LinkKinematicsKit::currentBodyFrameId() { return impl->currentFrameId[BodyFrame]; } const GeneralId& LinkKinematicsKit::currentEndFrameId() { return impl->currentFrameId[EndFrame]; } CoordinateFrame* LinkKinematicsKit::currentFrame(int frameType) { return impl->frameSets->frameSet(frameType)->getFrame(currentFrameId(frameType)); } CoordinateFrame* LinkKinematicsKit::currentWorldFrame() { return impl->frameSets->worldFrameSet()->getFrame(currentWorldFrameId()); } CoordinateFrame* LinkKinematicsKit::currentBodyFrame() { return impl->frameSets->bodyFrameSet()->getFrame(currentBodyFrameId()); } CoordinateFrame* LinkKinematicsKit::currentEndFrame() { return impl->frameSets->endFrameSet()->getFrame(currentEndFrameId()); } void LinkKinematicsKit::setCurrentFrame(int frameType, const GeneralId& id) { impl->currentFrameId[frameType] = id; } void LinkKinematicsKit::setCurrentWorldFrame(const GeneralId& id) { impl->currentFrameId[WorldFrame] = id; } void LinkKinematicsKit::setCurrentBodyFrame(const GeneralId& id) { impl->currentFrameId[BodyFrame] = id; } void LinkKinematicsKit::setCurrentEndFrame(const GeneralId& id) { impl->currentFrameId[EndFrame] = id; } int LinkKinematicsKit::currentBaseFrameType() { return impl->currentBaseFrameType; } void LinkKinematicsKit::setCurrentBaseFrameType(int frameType) { impl->currentBaseFrameType = frameType; } const GeneralId& LinkKinematicsKit::currentBaseFrameId() { if(impl->currentBaseFrameType == WorldFrame){ return currentWorldFrameId(); } else { return currentBodyFrameId(); } } CoordinateFrame* LinkKinematicsKit::currentBaseFrame() { if(impl->currentBaseFrameType == WorldFrame){ return currentWorldFrame(); } else { return currentBodyFrame(); } } void LinkKinematicsKit::setCurrentBaseFrame(const GeneralId& id) { if(impl->currentBaseFrameType == WorldFrame){ setCurrentWorldFrame(id); } else { setCurrentBodyFrame(id); } } SignalProxy<void()> LinkKinematicsKit::sigCurrentFrameChanged() { return impl->sigCurrentFrameChanged; } void LinkKinematicsKit::notifyCurrentFrameChange() { impl->sigCurrentFrameChanged(); } Body* LinkKinematicsKit::findAttachedEndEffector() const { if(auto body = impl->body){ for(auto& holder : body->devices<HolderDevice>()){ if(holder->category() == "EndEffector"){ if(auto attachment = holder->attachment()){ return attachment->link()->body(); } } } } return nullptr; }
// Copyright (c) 2011-2019 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 <qt/bitcoingui.h> #include <qt/bitcoinunits.h> #include <qt/clientmodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/modaloverlay.h> #include <qt/networkstyle.h> #include <qt/notificator.h> #include <qt/openuridialog.h> #include <qt/optionsdialog.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/rpcconsole.h> #include <qt/utilitydialog.h> #ifdef ENABLE_WALLET #include <qt/walletcontroller.h> #include <qt/walletframe.h> #include <qt/walletmodel.h> #include <qt/walletview.h> #endif // ENABLE_WALLET #ifdef Q_OS_MAC #include <qt/macdockiconhandler.h> #endif #include <chain.h> #include <chainparams.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <ui_interface.h> #include <util/system.h> #include <iostream> #include <memory> #include <QAction> #include <QApplication> #include <QComboBox> #include <QDateTime> #include <QDesktopWidget> #include <QDragEnterEvent> #include <QListWidget> #include <QMenu> #include <QMenuBar> #include <QMessageBox> #include <QMimeData> #include <QProgressDialog> #include <QSettings> #include <QShortcut> #include <QStackedWidget> #include <QStatusBar> #include <QStyle> #include <QSystemTrayIcon> #include <QTimer> #include <QToolBar> #include <QUrlQuery> #include <QVBoxLayout> #include <QWindow> const std::string BitcoinGUI::DEFAULT_UIPLATFORM = #if defined(Q_OS_MAC) "macosx" #elif defined(Q_OS_WIN) "windows" #else "other" #endif ; BitcoinGUI::BitcoinGUI(interfaces::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) : QMainWindow(parent), m_node(node), trayIconMenu{new QMenu()}, platformStyle(_platformStyle), m_network_style(networkStyle) { QSettings settings; if (!restoreGeometry(settings.value("MainWindowGeometry").toByteArray())) { // Restore failed (perhaps missing setting), center the window move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center()); } #ifdef ENABLE_WALLET enableWallet = WalletModel::isWalletEnabled(); #endif // ENABLE_WALLET QApplication::setWindowIcon(m_network_style->getTrayAndWindowIcon()); setWindowIcon(m_network_style->getTrayAndWindowIcon()); updateWindowTitle(); rpcConsole = new RPCConsole(node, _platformStyle, nullptr); helpMessageDialog = new HelpMessageDialog(node, this, false); #ifdef ENABLE_WALLET if(enableWallet) { /** Create wallet frame and make it the central widget */ walletFrame = new WalletFrame(_platformStyle, this); setCentralWidget(walletFrame); } else #endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); Q_EMIT consoleShown(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification if (QSystemTrayIcon::isSystemTrayAvailable()) { createTrayIcon(); } notificator = new Notificator(QApplication::applicationName(), trayIcon, this); // Create status bar statusBar(); // Disable size grip because it looks ugly and nobody needs it statusBar()->setSizeGripEnabled(false); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle); labelWalletEncryptionIcon = new QLabel(); labelWalletHDStatusIcon = new QLabel(); labelProxyIcon = new GUIUtil::ClickableLabel(); connectionsControl = new GUIUtil::ClickableLabel(); labelBlocksIcon = new GUIUtil::ClickableLabel(); if(enableWallet) { frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(unitDisplayControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelWalletEncryptionIcon); frameBlocksLayout->addWidget(labelWalletHDStatusIcon); } frameBlocksLayout->addWidget(labelProxyIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(connectionsControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new GUIUtil::ProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://doc.qt.io/qt-5/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); connect(connectionsControl, &GUIUtil::ClickableLabel::clicked, [this] { m_node.setNetworkActive(!m_node.getNetworkActive()); }); connect(labelProxyIcon, &GUIUtil::ClickableLabel::clicked, [this] { openOptionsDialogWithTab(OptionsDialog::TAB_NETWORK); }); modalOverlay = new ModalOverlay(this->centralWidget()); #ifdef ENABLE_WALLET if(enableWallet) { connect(walletFrame, &WalletFrame::requestedSyncWarningInfo, this, &BitcoinGUI::showModalOverlay); connect(labelBlocksIcon, &GUIUtil::ClickableLabel::clicked, this, &BitcoinGUI::showModalOverlay); connect(progressBar, &GUIUtil::ClickableProgressBar::clicked, this, &BitcoinGUI::showModalOverlay); } #endif #ifdef Q_OS_MAC m_app_nap_inhibitor = new CAppNapInhibitor; #endif } BitcoinGUI::~BitcoinGUI() { // Unsubscribe from notifications from core unsubscribeFromCoreSignals(); QSettings settings; settings.setValue("MainWindowGeometry", saveGeometry()); if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete m_app_nap_inhibitor; delete appMenuBar; MacDockIconHandler::cleanup(); #endif delete rpcConsole; } void BitcoinGUI::createActions() { QActionGroup *tabGroup = new QActionGroup(this); overviewAction = new QAction(platformStyle->SingleColorIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a Bitcoin address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(sendCoinsAction); sendCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/send"), sendCoinsAction->text(), this); sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip()); sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip()); receiveCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and bitcoin: URIs)")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); tabGroup->addAction(receiveCoinsAction); receiveCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/receiving_addresses"), receiveCoinsAction->text(), this); receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip()); receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip()); historyAction = new QAction(platformStyle->SingleColorIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); #ifdef ENABLE_WALLET // These showNormalIfMinimized are needed because Send Coins and Receive Coins // can be triggered from the tray menu, and need to show the GUI to be useful. connect(overviewAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(overviewAction, &QAction::triggered, this, &BitcoinGUI::gotoOverviewPage); connect(sendCoinsAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(sendCoinsAction, &QAction::triggered, [this]{ gotoSendCoinsPage(); }); connect(sendCoinsMenuAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(sendCoinsMenuAction, &QAction::triggered, [this]{ gotoSendCoinsPage(); }); connect(receiveCoinsAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(receiveCoinsAction, &QAction::triggered, this, &BitcoinGUI::gotoReceiveCoinsPage); connect(receiveCoinsMenuAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(receiveCoinsMenuAction, &QAction::triggered, this, &BitcoinGUI::gotoReceiveCoinsPage); connect(historyAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(historyAction, &QAction::triggered, this, &BitcoinGUI::gotoHistoryPage); #endif // ENABLE_WALLET quitAction = new QAction(platformStyle->TextColorIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&About %1").arg(tr(PACKAGE_NAME)), this); aboutAction->setStatusTip(tr("Show information about %1").arg(tr(PACKAGE_NAME))); aboutAction->setMenuRole(QAction::AboutRole); aboutAction->setEnabled(false); aboutQtAction = new QAction(platformStyle->TextColorIcon(":/icons/about_qt"), tr("About &Qt"), this); aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(platformStyle->TextColorIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for %1").arg(tr(PACKAGE_NAME))); optionsAction->setMenuRole(QAction::PreferencesRole); optionsAction->setEnabled(false); toggleHideAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(platformStyle->TextColorIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); signMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your Bitcoin addresses to prove you own them")); verifyMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/verify"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Bitcoin addresses")); openRPCConsoleAction = new QAction(platformStyle->TextColorIcon(":/icons/debugwindow"), tr("&Debug window"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console")); // initially disable the debug window menu item openRPCConsoleAction->setEnabled(false); openRPCConsoleAction->setObjectName("openRPCConsoleAction"); usedSendingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Sending addresses"), this); usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels")); usedReceivingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Receiving addresses"), this); usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels")); openAction = new QAction(platformStyle->TextColorIcon(":/icons/open"), tr("Open &URI..."), this); openAction->setStatusTip(tr("Open a bitcoin: URI or payment request")); m_open_wallet_action = new QAction(tr("Open Wallet"), this); m_open_wallet_action->setMenu(new QMenu(this)); m_open_wallet_action->setStatusTip(tr("Open a wallet")); m_close_wallet_action = new QAction(tr("Close Wallet..."), this); m_close_wallet_action->setStatusTip(tr("Close wallet")); showHelpMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/info"), tr("&Command-line options"), this); showHelpMessageAction->setMenuRole(QAction::NoRole); showHelpMessageAction->setStatusTip(tr("Show the %1 help message to get a list with possible Bitcoin command-line options").arg(tr(PACKAGE_NAME))); connect(quitAction, &QAction::triggered, qApp, QApplication::quit); connect(aboutAction, &QAction::triggered, this, &BitcoinGUI::aboutClicked); connect(aboutQtAction, &QAction::triggered, qApp, QApplication::aboutQt); connect(optionsAction, &QAction::triggered, this, &BitcoinGUI::optionsClicked); connect(toggleHideAction, &QAction::triggered, this, &BitcoinGUI::toggleHidden); connect(showHelpMessageAction, &QAction::triggered, this, &BitcoinGUI::showHelpMessageClicked); connect(openRPCConsoleAction, &QAction::triggered, this, &BitcoinGUI::showDebugWindow); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, &QAction::triggered, rpcConsole, &QWidget::hide); #ifdef ENABLE_WALLET if(walletFrame) { connect(encryptWalletAction, &QAction::triggered, walletFrame, &WalletFrame::encryptWallet); connect(backupWalletAction, &QAction::triggered, walletFrame, &WalletFrame::backupWallet); connect(changePassphraseAction, &QAction::triggered, walletFrame, &WalletFrame::changePassphrase); connect(signMessageAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(signMessageAction, &QAction::triggered, [this]{ gotoSignMessageTab(); }); connect(verifyMessageAction, &QAction::triggered, [this]{ showNormalIfMinimized(); }); connect(verifyMessageAction, &QAction::triggered, [this]{ gotoVerifyMessageTab(); }); connect(usedSendingAddressesAction, &QAction::triggered, walletFrame, &WalletFrame::usedSendingAddresses); connect(usedReceivingAddressesAction, &QAction::triggered, walletFrame, &WalletFrame::usedReceivingAddresses); connect(openAction, &QAction::triggered, this, &BitcoinGUI::openClicked); connect(m_open_wallet_action->menu(), &QMenu::aboutToShow, [this] { m_open_wallet_action->menu()->clear(); std::vector<std::string> available_wallets = m_wallet_controller->getWalletsAvailableToOpen(); std::vector<std::string> wallets = m_node.listWalletDir(); for (const auto& path : wallets) { QString name = path.empty() ? QString("["+tr("default wallet")+"]") : QString::fromStdString(path); QAction* action = m_open_wallet_action->menu()->addAction(name); if (std::find(available_wallets.begin(), available_wallets.end(), path) == available_wallets.end()) { // This wallet is already loaded action->setEnabled(false); continue; } connect(action, &QAction::triggered, [this, name, path] { OpenWalletActivity* activity = m_wallet_controller->openWallet(path); QProgressDialog* dialog = new QProgressDialog(this); dialog->setLabelText(tr("Opening Wallet <b>%1</b>...").arg(name.toHtmlEscaped())); dialog->setRange(0, 0); dialog->setCancelButton(nullptr); dialog->setWindowModality(Qt::ApplicationModal); dialog->show(); connect(activity, &OpenWalletActivity::message, this, [this] (QMessageBox::Icon icon, QString text) { QMessageBox box; box.setIcon(icon); box.setText(tr("Open Wallet Failed")); box.setInformativeText(text); box.setStandardButtons(QMessageBox::Ok); box.setDefaultButton(QMessageBox::Ok); connect(this, &QObject::destroyed, &box, &QDialog::accept); box.exec(); }); connect(activity, &OpenWalletActivity::opened, this, &BitcoinGUI::setCurrentWallet); connect(activity, &OpenWalletActivity::finished, activity, &QObject::deleteLater); connect(activity, &OpenWalletActivity::finished, dialog, &QObject::deleteLater); bool invoked = QMetaObject::invokeMethod(activity, "open"); assert(invoked); }); } if (wallets.empty()) { QAction* action = m_open_wallet_action->menu()->addAction(tr("No wallets available")); action->setEnabled(false); } }); connect(m_close_wallet_action, &QAction::triggered, [this] { m_wallet_controller->closeWallet(walletFrame->currentWalletModel(), this); }); } #endif // ENABLE_WALLET connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), this), &QShortcut::activated, this, &BitcoinGUI::showDebugWindowActivateConsole); connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_D), this), &QShortcut::activated, this, &BitcoinGUI::showDebugWindow); } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); if(walletFrame) { file->addAction(m_open_wallet_action); file->addAction(m_close_wallet_action); file->addSeparator(); file->addAction(openAction); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); } file->addAction(quitAction); QMenu *settings = appMenuBar->addMenu(tr("&Settings")); if(walletFrame) { settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addSeparator(); } settings->addAction(optionsAction); QMenu* window_menu = appMenuBar->addMenu(tr("&Window")); QAction* minimize_action = window_menu->addAction(tr("Minimize")); minimize_action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_M)); connect(minimize_action, &QAction::triggered, [] { qApp->focusWindow()->showMinimized(); }); connect(qApp, &QApplication::focusWindowChanged, [minimize_action] (QWindow* window) { minimize_action->setEnabled(window != nullptr && (window->flags() & Qt::Dialog) != Qt::Dialog && window->windowState() != Qt::WindowMinimized); }); #ifdef Q_OS_MAC QAction* zoom_action = window_menu->addAction(tr("Zoom")); connect(zoom_action, &QAction::triggered, [] { QWindow* window = qApp->focusWindow(); if (window->windowState() != Qt::WindowMaximized) { window->showMaximized(); } else { window->showNormal(); } }); connect(qApp, &QApplication::focusWindowChanged, [zoom_action] (QWindow* window) { zoom_action->setEnabled(window != nullptr); }); #else QAction* restore_action = window_menu->addAction(tr("Restore")); connect(restore_action, &QAction::triggered, [] { qApp->focusWindow()->showNormal(); }); connect(qApp, &QApplication::focusWindowChanged, [restore_action] (QWindow* window) { restore_action->setEnabled(window != nullptr); }); #endif if (walletFrame) { window_menu->addSeparator(); QAction* main_window_action = window_menu->addAction(tr("Main Window")); connect(main_window_action, &QAction::triggered, [this] { GUIUtil::bringToFront(this); }); window_menu->addSeparator(); window_menu->addAction(usedSendingAddressesAction); window_menu->addAction(usedReceivingAddressesAction); } window_menu->addSeparator(); for (RPCConsole::TabTypes tab_type : rpcConsole->tabs()) { QAction* tab_action = window_menu->addAction(rpcConsole->tabTitle(tab_type)); connect(tab_action, &QAction::triggered, [this, tab_type] { rpcConsole->setTabFocus(tab_type); showDebugWindow(); }); } QMenu *help = appMenuBar->addMenu(tr("&Help")); help->addAction(showHelpMessageAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { if(walletFrame) { QToolBar *toolbar = addToolBar(tr("Tabs toolbar")); appToolBar = toolbar; toolbar->setContextMenuPolicy(Qt::PreventContextMenu); toolbar->setMovable(false); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); overviewAction->setChecked(true); #ifdef ENABLE_WALLET QWidget *spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); toolbar->addWidget(spacer); m_wallet_selector = new QComboBox(); m_wallet_selector->setSizeAdjustPolicy(QComboBox::AdjustToContents); connect(m_wallet_selector, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &BitcoinGUI::setCurrentWalletBySelectorIndex); m_wallet_selector_label = new QLabel(); m_wallet_selector_label->setText(tr("Wallet:") + " "); m_wallet_selector_label->setBuddy(m_wallet_selector); m_wallet_selector_label_action = appToolBar->addWidget(m_wallet_selector_label); m_wallet_selector_action = appToolBar->addWidget(m_wallet_selector); m_wallet_selector_label_action->setVisible(false); m_wallet_selector_action->setVisible(false); #endif } } void BitcoinGUI::setClientModel(ClientModel *_clientModel) { this->clientModel = _clientModel; if(_clientModel) { // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client updateNetworkState(); connect(_clientModel, &ClientModel::numConnectionsChanged, this, &BitcoinGUI::setNumConnections); connect(_clientModel, &ClientModel::networkActiveChanged, this, &BitcoinGUI::setNetworkActive); modalOverlay->setKnownBestHeight(_clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(_clientModel->getHeaderTipTime())); setNumBlocks(m_node.getNumBlocks(), QDateTime::fromTime_t(m_node.getLastBlockTime()), m_node.getVerificationProgress(), false); connect(_clientModel, &ClientModel::numBlocksChanged, this, &BitcoinGUI::setNumBlocks); // Receive and report messages from client model connect(_clientModel, &ClientModel::message, [this](const QString &title, const QString &message, unsigned int style){ this->message(title, message, style); }); // Show progress dialog connect(_clientModel, &ClientModel::showProgress, this, &BitcoinGUI::showProgress); rpcConsole->setClientModel(_clientModel); updateProxyIcon(); #ifdef ENABLE_WALLET if(walletFrame) { walletFrame->setClientModel(_clientModel); } #endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(_clientModel->getOptionsModel()); OptionsModel* optionsModel = _clientModel->getOptionsModel(); if (optionsModel && trayIcon) { // be aware of the tray icon disable state change reported by the OptionsModel object. connect(optionsModel, &OptionsModel::hideTrayIconChanged, this, &BitcoinGUI::setTrayIconVisible); // initialize the disable state of the tray icon with the current value in the model. setTrayIconVisible(optionsModel->getHideTrayIcon()); } } else { // Disable possibility to show main window via action toggleHideAction->setEnabled(false); if(trayIconMenu) { // Disable context menu on tray icon trayIconMenu->clear(); } // Propagate cleared model to child objects rpcConsole->setClientModel(nullptr); #ifdef ENABLE_WALLET if (walletFrame) { walletFrame->setClientModel(nullptr); } #endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(nullptr); } } #ifdef ENABLE_WALLET void BitcoinGUI::setWalletController(WalletController* wallet_controller) { assert(!m_wallet_controller); assert(wallet_controller); m_wallet_controller = wallet_controller; connect(wallet_controller, &WalletController::walletAdded, this, &BitcoinGUI::addWallet); connect(wallet_controller, &WalletController::walletRemoved, this, &BitcoinGUI::removeWallet); for (WalletModel* wallet_model : m_wallet_controller->getWallets()) { addWallet(wallet_model); } } void BitcoinGUI::addWallet(WalletModel* walletModel) { if (!walletFrame) return; const QString display_name = walletModel->getDisplayName(); setWalletActionsEnabled(true); rpcConsole->addWallet(walletModel); walletFrame->addWallet(walletModel); m_wallet_selector->addItem(display_name, QVariant::fromValue(walletModel)); if (m_wallet_selector->count() == 2) { m_wallet_selector_label_action->setVisible(true); m_wallet_selector_action->setVisible(true); } } void BitcoinGUI::removeWallet(WalletModel* walletModel) { if (!walletFrame) return; int index = m_wallet_selector->findData(QVariant::fromValue(walletModel)); m_wallet_selector->removeItem(index); if (m_wallet_selector->count() == 0) { setWalletActionsEnabled(false); } else if (m_wallet_selector->count() == 1) { m_wallet_selector_label_action->setVisible(false); m_wallet_selector_action->setVisible(false); } rpcConsole->removeWallet(walletModel); walletFrame->removeWallet(walletModel); updateWindowTitle(); } void BitcoinGUI::setCurrentWallet(WalletModel* wallet_model) { if (!walletFrame) return; walletFrame->setCurrentWallet(wallet_model); for (int index = 0; index < m_wallet_selector->count(); ++index) { if (m_wallet_selector->itemData(index).value<WalletModel*>() == wallet_model) { m_wallet_selector->setCurrentIndex(index); break; } } updateWindowTitle(); } void BitcoinGUI::setCurrentWalletBySelectorIndex(int index) { WalletModel* wallet_model = m_wallet_selector->itemData(index).value<WalletModel*>(); if (wallet_model) setCurrentWallet(wallet_model); } void BitcoinGUI::removeAllWallets() { if(!walletFrame) return; setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } #endif // ENABLE_WALLET void BitcoinGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); sendCoinsMenuAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); receiveCoinsMenuAction->setEnabled(enabled); historyAction->setEnabled(enabled); encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); usedSendingAddressesAction->setEnabled(enabled); usedReceivingAddressesAction->setEnabled(enabled); openAction->setEnabled(enabled); m_close_wallet_action->setEnabled(enabled); } void BitcoinGUI::createTrayIcon() { assert(QSystemTrayIcon::isSystemTrayAvailable()); #ifndef Q_OS_MAC if (QSystemTrayIcon::isSystemTrayAvailable()) { trayIcon = new QSystemTrayIcon(m_network_style->getTrayAndWindowIcon(), this); QString toolTip = tr("%1 client").arg(tr(PACKAGE_NAME)) + " " + m_network_style->getTitleAddText(); trayIcon->setToolTip(toolTip); } #endif } void BitcoinGUI::createTrayIconMenu() { #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-macOSes) if (!trayIcon) return; trayIcon->setContextMenu(trayIconMenu.get()); connect(trayIcon, &QSystemTrayIcon::activated, this, &BitcoinGUI::trayIconActivated); #else // Note: On macOS, the Dock icon is used to provide the tray's functionality. MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance(); connect(dockIconHandler, &MacDockIconHandler::dockIconClicked, this, &BitcoinGUI::macosDockIconActivated); trayIconMenu->setAsDockMenu(); #endif // Configuration of the tray icon (or Dock icon) menu #ifndef Q_OS_MAC // Note: On macOS, the Dock icon's menu already has Show / Hide action. trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); #endif if (enableWallet) { trayIconMenu->addAction(sendCoinsMenuAction); trayIconMenu->addAction(receiveCoinsMenuAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(openRPCConsoleAction); } trayIconMenu->addAction(optionsAction); #ifndef Q_OS_MAC // This is built-in on macOS trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHidden(); } } #else void BitcoinGUI::macosDockIconActivated() { show(); activateWindow(); } #endif void BitcoinGUI::optionsClicked() { openOptionsDialogWithTab(OptionsDialog::TAB_MAIN); } void BitcoinGUI::aboutClicked() { if(!clientModel) return; HelpMessageDialog dlg(m_node, this, true); dlg.exec(); } void BitcoinGUI::showDebugWindow() { GUIUtil::bringToFront(rpcConsole); Q_EMIT consoleShown(rpcConsole); } void BitcoinGUI::showDebugWindowActivateConsole() { rpcConsole->setTabFocus(RPCConsole::TAB_CONSOLE); showDebugWindow(); } void BitcoinGUI::showHelpMessageClicked() { helpMessageDialog->show(); } #ifdef ENABLE_WALLET void BitcoinGUI::openClicked() { OpenURIDialog dlg(this); if(dlg.exec()) { Q_EMIT receivedURI(dlg.getURI()); } } void BitcoinGUI::gotoOverviewPage() { overviewAction->setChecked(true); if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { historyAction->setChecked(true); if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { sendCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } #endif // ENABLE_WALLET void BitcoinGUI::updateNetworkState() { int count = clientModel->getNumConnections(); QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } QString tooltip; if (m_node.getNetworkActive()) { tooltip = tr("%n active connection(s) to Bitcoin network", "", count) + QString(".<br>") + tr("Click to disable network activity."); } else { tooltip = tr("Network activity disabled.") + QString("<br>") + tr("Click to enable network activity again."); icon = ":/icons/network_disabled"; } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); connectionsControl->setToolTip(tooltip); connectionsControl->setPixmap(platformStyle->SingleColorIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); } void BitcoinGUI::setNumConnections(int count) { updateNetworkState(); } void BitcoinGUI::setNetworkActive(bool networkActive) { updateNetworkState(); } void BitcoinGUI::updateHeadersSyncProgressLabel() { int64_t headersTipTime = clientModel->getHeaderTipTime(); int headersTipHeight = clientModel->getHeaderTipHeight(); int estHeadersLeft = (GetTime() - headersTipTime) / Params().GetConsensus().nPowTargetSpacing; if (estHeadersLeft > HEADER_HEIGHT_DELTA_SYNC) progressBarLabel->setText(tr("Syncing Headers (%1%)...").arg(QString::number(100.0 / (headersTipHeight+estHeadersLeft)*headersTipHeight, 'f', 1))); } void BitcoinGUI::openOptionsDialogWithTab(OptionsDialog::Tab tab) { if (!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg(this, enableWallet); dlg.setCurrentTab(tab); dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool header) { // Disabling macOS App Nap on initial sync, disk and reindex operations. #ifdef Q_OS_MAC (m_node.isInitialBlockDownload() || m_node.getReindex() || m_node.getImporting()) ? m_app_nap_inhibitor->disableAppNap() : m_app_nap_inhibitor->enableAppNap(); #endif if (modalOverlay) { if (header) modalOverlay->setKnownBestHeight(count, blockDate); else modalOverlay->tipUpdate(count, blockDate, nVerificationProgress); } if (!clientModel) return; // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BlockSource::NETWORK: if (header) { updateHeadersSyncProgressLabel(); return; } progressBarLabel->setText(tr("Synchronizing with network...")); updateHeadersSyncProgressLabel(); break; case BlockSource::DISK: if (header) { progressBarLabel->setText(tr("Indexing blocks on disk...")); } else { progressBarLabel->setText(tr("Processing blocks on disk...")); } break; case BlockSource::REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BlockSource::NONE: if (header) { return; } progressBarLabel->setText(tr("Connecting to peers...")); break; } QString tooltip; QDateTime currentDate = QDateTime::currentDateTime(); qint64 secs = blockDate.secsTo(currentDate); tooltip = tr("Processed %n block(s) of transaction history.", "", count); // Set icon state: spinning if catching up, tick otherwise if (secs < MAX_BLOCK_TIME_GAP) { tooltip = tr("Up to date") + QString(".<br>") + tooltip; labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); #ifdef ENABLE_WALLET if(walletFrame) { walletFrame->showOutOfSyncWarning(false); modalOverlay->showHide(true, true); } #endif // ENABLE_WALLET progressBarLabel->setVisible(false); progressBar->setVisible(false); } else { QString timeBehindText = GUIUtil::formatNiceTimeOffset(secs); progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(nVerificationProgress * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; if(count != prevBlocks) { labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString( ":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; } prevBlocks = count; #ifdef ENABLE_WALLET if(walletFrame) { walletFrame->showOutOfSyncWarning(true); modalOverlay->showHide(); } #endif // ENABLE_WALLET tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret) { QString strTitle = tr("Bitcoin"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "Bitcoin - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; showNormalIfMinimized(); QMessageBox mBox(static_cast<QMessageBox::Icon>(nMBoxIcon), strTitle, message, buttons, this); mBox.setTextFormat(Qt::PlainText); int r = mBox.exec(); if (ret != nullptr) *ret = r == QMessageBox::Ok; } else notificator->notify(static_cast<Notificator::Class>(nNotifyIcon), strTitle, message); } void BitcoinGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if(e->type() == QEvent::WindowStateChange) { if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e); if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, &BitcoinGUI::hide); e->ignore(); } else if((wsevt->oldState() & Qt::WindowMinimized) && !isMinimized()) { QTimer::singleShot(0, this, &BitcoinGUI::show); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent *event) { #ifndef Q_OS_MAC // Ignored on Mac if(clientModel && clientModel->getOptionsModel()) { if(!clientModel->getOptionsModel()->getMinimizeOnClose()) { // close rpcConsole in case it was open to make some space for the shutdown window rpcConsole->close(); QApplication::quit(); } else { QMainWindow::showMinimized(); event->ignore(); } } #else QMainWindow::closeEvent(event); #endif } void BitcoinGUI::showEvent(QShowEvent *event) { // enable the debug window when the main window shows up openRPCConsoleAction->setEnabled(true); aboutAction->setEnabled(true); optionsAction->setEnabled(true); } #ifdef ENABLE_WALLET void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label, const QString& walletName) { // On new transaction, make an info balloon QString msg = tr("Date: %1\n").arg(date) + tr("Amount: %1\n").arg(BitcoinUnits::formatWithUnit(unit, amount, true)); if (m_node.getWallets().size() > 1 && !walletName.isEmpty()) { msg += tr("Wallet: %1\n").arg(walletName); } msg += tr("Type: %1\n").arg(type); if (!label.isEmpty()) msg += tr("Label: %1\n").arg(label); else if (!address.isEmpty()) msg += tr("Address: %1\n").arg(address); message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), msg, CClientUIInterface::MSG_INFORMATION); } #endif // ENABLE_WALLET void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs if(event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls()) { for (const QUrl &uri : event->mimeData()->urls()) { Q_EMIT receivedURI(uri.toString()); } } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject *object, QEvent *event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } #ifdef ENABLE_WALLET bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient) { // URI has to be valid if (walletFrame && walletFrame->handlePaymentRequest(recipient)) { showNormalIfMinimized(); gotoSendCoinsPage(); return true; } return false; } void BitcoinGUI::setHDStatus(bool privkeyDisabled, int hdEnabled) { labelWalletHDStatusIcon->setPixmap(platformStyle->SingleColorIcon(privkeyDisabled ? ":/icons/eye" : hdEnabled ? ":/icons/hd_enabled" : ":/icons/hd_disabled").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelWalletHDStatusIcon->setToolTip(privkeyDisabled ? tr("Private key <b>disabled</b>") : hdEnabled ? tr("HD key generation is <b>enabled</b>") : tr("HD key generation is <b>disabled</b>")); // eventually disable the QLabel to set its opacity to 50% labelWalletHDStatusIcon->setEnabled(hdEnabled); } void BitcoinGUI::setEncryptionStatus(int status) { switch(status) { case WalletModel::Unencrypted: labelWalletEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelWalletEncryptionIcon->show(); labelWalletEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelWalletEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelWalletEncryptionIcon->show(); labelWalletEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelWalletEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } void BitcoinGUI::updateWalletStatus() { if (!walletFrame) { return; } WalletView * const walletView = walletFrame->currentWalletView(); if (!walletView) { return; } WalletModel * const walletModel = walletView->getWalletModel(); setEncryptionStatus(walletModel->getEncryptionStatus()); setHDStatus(walletModel->privateKeysDisabled(), walletModel->wallet().hdEnabled()); } #endif // ENABLE_WALLET void BitcoinGUI::updateProxyIcon() { std::string ip_port; bool proxy_enabled = clientModel->getProxyInfo(ip_port); if (proxy_enabled) { if (labelProxyIcon->pixmap() == nullptr) { QString ip_port_q = QString::fromStdString(ip_port); labelProxyIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/proxy").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelProxyIcon->setToolTip(tr("Proxy is <b>enabled</b>: %1").arg(ip_port_q)); } else { labelProxyIcon->show(); } } else { labelProxyIcon->hide(); } } void BitcoinGUI::updateWindowTitle() { QString window_title = tr(PACKAGE_NAME); #ifdef ENABLE_WALLET if (walletFrame) { WalletModel* const wallet_model = walletFrame->currentWalletModel(); if (wallet_model && !wallet_model->getWalletName().isEmpty()) { window_title += " - " + wallet_model->getDisplayName(); } } #endif if (!m_network_style->getTitleAddText().isEmpty()) { window_title += " - " + m_network_style->getTitleAddText(); } setWindowTitle(window_title); } void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { if(!clientModel) return; if (!isHidden() && !isMinimized() && !GUIUtil::isObscured(this) && fToggleHidden) { hide(); } else { GUIUtil::bringToFront(this); } } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (m_node.shutdownRequested()) { if(rpcConsole) rpcConsole->hide(); qApp->quit(); } } void BitcoinGUI::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, QString(), 0, 100); GUIUtil::PolishProgressDialog(progressDialog); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) { progressDialog->setValue(nProgress); } } void BitcoinGUI::setTrayIconVisible(bool fHideTrayIcon) { if (trayIcon) { trayIcon->setVisible(!fHideTrayIcon); } } void BitcoinGUI::showModalOverlay() { if (modalOverlay && (progressBar->isVisible() || modalOverlay->isLayerVisible())) modalOverlay->toggleVisibility(); } static bool ThreadSafeMessageBox(BitcoinGUI* gui, const std::string& message, const std::string& caption, unsigned int style) { bool modal = (style & CClientUIInterface::MODAL); // The SECURE flag has no effect in the Qt GUI. // bool secure = (style & CClientUIInterface::SECURE); style &= ~CClientUIInterface::SECURE; bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(gui, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } void BitcoinGUI::subscribeToCoreSignals() { // Connect signals to client m_handler_message_box = m_node.handleMessageBox(std::bind(ThreadSafeMessageBox, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); m_handler_question = m_node.handleQuestion(std::bind(ThreadSafeMessageBox, this, std::placeholders::_1, std::placeholders::_3, std::placeholders::_4)); } void BitcoinGUI::unsubscribeFromCoreSignals() { // Disconnect signals from client m_handler_message_box->disconnect(); m_handler_question->disconnect(); } UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) : optionsModel(nullptr), menu(nullptr) { createContextMenu(); setToolTip(tr("Unit to show amounts in. Click to select another unit.")); QList<BitcoinUnits::Unit> units = BitcoinUnits::availableUnits(); int max_width = 0; const QFontMetrics fm(font()); for (const BitcoinUnits::Unit unit : units) { max_width = qMax(max_width, fm.width(BitcoinUnits::longName(unit))); } setMinimumSize(max_width, 0); setAlignment(Qt::AlignRight | Qt::AlignVCenter); setStyleSheet(QString("QLabel { color : %1 }").arg(platformStyle->SingleColor().name())); } /** So that it responds to button clicks */ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event) { onDisplayUnitsClicked(event->pos()); } /** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */ void UnitDisplayStatusBarControl::createContextMenu() { menu = new QMenu(this); for (const BitcoinUnits::Unit u : BitcoinUnits::availableUnits()) { QAction *menuAction = new QAction(QString(BitcoinUnits::longName(u)), this); menuAction->setData(QVariant(u)); menu->addAction(menuAction); } connect(menu, &QMenu::triggered, this, &UnitDisplayStatusBarControl::onMenuSelection); } /** Lets the control know about the Options Model (and its signals) */ void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *_optionsModel) { if (_optionsModel) { this->optionsModel = _optionsModel; // be aware of a display unit change reported by the OptionsModel object. connect(_optionsModel, &OptionsModel::displayUnitChanged, this, &UnitDisplayStatusBarControl::updateDisplayUnit); // initialize the display units label with the current value in the model. updateDisplayUnit(_optionsModel->getDisplayUnit()); } } /** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */ void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits) { setText(BitcoinUnits::longName(newUnits)); } /** Shows context menu with Display Unit options by the mouse coordinates */ void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point) { QPoint globalPos = mapToGlobal(point); menu->exec(globalPos); } /** Tells underlying optionsModel to update its current display unit. */ void UnitDisplayStatusBarControl::onMenuSelection(QAction* action) { if (action) { optionsModel->setDisplayUnit(action->data()); } }
#include<iostream> #include<cctype> #include<algorithm> #include<cstdio> #include<cstdlib> #include<vector> #include<map> #include<queue> #include<set> #include<stack> #include<cctype> #include<cstring> #include<utility> const int inf=0x7fffffff; typedef long long int ll; using namespace std; char w[21]=" "; char t[1000+10]; char tt[1000+1000]; char eof[]="END_OF_TEXT"; void turn(){ int i=0; while(tt[i]!='\0'){tt[i]=tolower(tt[i]);i++;} } int main() { //#ifdef DEBUG // freopen("in", "r", stdin); //// freopen("out", "w", stdout); //#endif scanf("%s", t); //cout<<t<<endl; strcat(w,t); strcat(w," "); //cout<<w<<endl; int cnt=0; memset(t,0,sizeof(t)); memset(tt,0,sizeof(tt)); while(fgets(t,sizeof(t),stdin)!=NULL){ //cout<<t<<endl; if(!strcmp(w,eof))break; strcat(tt,"."); strcat(tt,t); strcat(tt,"."); } for(int i=0;tt[i]!='\0';i++){ if(tt[i]=='.'||tt[i]=='\n')tt[i]=' '; } turn(); char *cur=tt+1; char *tmp; //cout<<tt<<endl; while(1){ tmp=strstr(cur,w); if(!tmp)break; cur=tmp+1; // cout<<*cur<<endl; // while(*cur!='\0'&&isalpha(*cur))cur++; cnt++; // cout<<cur-tt<<endl; } printf("%d\n", cnt); //insert code return 0; } //1_9_a.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/autoclick/autoclick_controller.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/events/event.h" #include "ui/events/event_constants.h" #include "ui/events/event_handler.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/events/test/event_generator.h" namespace ash { class MouseEventCapturer : public ui::EventHandler { public: MouseEventCapturer() { Reset(); } ~MouseEventCapturer() override {} void Reset() { events_.clear(); } void OnMouseEvent(ui::MouseEvent* event) override { if (!(event->flags() & ui::EF_LEFT_MOUSE_BUTTON)) return; // Filter out extraneous mouse events like mouse entered, exited, // capture changed, etc. ui::EventType type = event->type(); if (type == ui::ET_MOUSE_MOVED || type == ui::ET_MOUSE_PRESSED || type == ui::ET_MOUSE_RELEASED) { events_.push_back(ui::MouseEvent(event->type(), event->location(), event->root_location(), ui::EventTimeForNow(), event->flags(), event->changed_button_flags())); // Stop event propagation so we don't click on random stuff that // might break test assumptions. event->StopPropagation(); } // If there is a possibility that we're in an infinite loop, we should // exit early with a sensible error rather than letting the test time out. ASSERT_LT(events_.size(), 100u); } const std::vector<ui::MouseEvent>& captured_events() const { return events_; } private: std::vector<ui::MouseEvent> events_; DISALLOW_COPY_AND_ASSIGN(MouseEventCapturer); }; class AutoclickTest : public test::AshTestBase { public: AutoclickTest() {} ~AutoclickTest() override {} void SetUp() override { test::AshTestBase::SetUp(); Shell::GetInstance()->AddPreTargetHandler(&mouse_event_capturer_); GetAutoclickController()->SetAutoclickDelay(0); // Move mouse to deterministic location at the start of each test. GetEventGenerator().MoveMouseTo(100, 100); } void TearDown() override { Shell::GetInstance()->RemovePreTargetHandler(&mouse_event_capturer_); test::AshTestBase::TearDown(); } void MoveMouseWithFlagsTo(int x, int y, ui::EventFlags flags) { GetEventGenerator().set_flags(flags); GetEventGenerator().MoveMouseTo(x, y); GetEventGenerator().set_flags(ui::EF_NONE); } const std::vector<ui::MouseEvent>& WaitForMouseEvents() { mouse_event_capturer_.Reset(); RunAllPendingInMessageLoop(); return mouse_event_capturer_.captured_events(); } AutoclickController* GetAutoclickController() { return Shell::GetInstance()->autoclick_controller(); } private: MouseEventCapturer mouse_event_capturer_; DISALLOW_COPY_AND_ASSIGN(AutoclickTest); }; TEST_F(AutoclickTest, ToggleEnabled) { std::vector<ui::MouseEvent> events; // We should not see any events initially. EXPECT_FALSE(GetAutoclickController()->IsEnabled()); events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); // Enable autoclick, and we should see a mouse pressed and // a mouse released event, simulating a click. GetAutoclickController()->SetEnabled(true); GetEventGenerator().MoveMouseTo(0, 0); EXPECT_TRUE(GetAutoclickController()->IsEnabled()); events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); EXPECT_EQ(ui::ET_MOUSE_PRESSED, events[0].type()); EXPECT_EQ(ui::ET_MOUSE_RELEASED, events[1].type()); // We should not get any more clicks until we move the mouse. events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); GetEventGenerator().MoveMouseTo(30, 30); events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); EXPECT_EQ(ui::ET_MOUSE_PRESSED, events[0].type()); EXPECT_EQ(ui::ET_MOUSE_RELEASED, events[1].type()); // Disable autoclick, and we should see the original behaviour. GetAutoclickController()->SetEnabled(false); EXPECT_FALSE(GetAutoclickController()->IsEnabled()); events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); } TEST_F(AutoclickTest, MouseMovement) { std::vector<ui::MouseEvent> events; GetAutoclickController()->SetEnabled(true); gfx::Point p1(0, 0); gfx::Point p2(20, 20); gfx::Point p3(40, 40); // Move mouse to p1. GetEventGenerator().MoveMouseTo(p1); events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); EXPECT_EQ(p1.ToString(), events[0].root_location().ToString()); EXPECT_EQ(p1.ToString(), events[1].root_location().ToString()); // Move mouse to multiple locations and finally arrive at p3. GetEventGenerator().MoveMouseTo(p2); GetEventGenerator().MoveMouseTo(p1); GetEventGenerator().MoveMouseTo(p3); events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); EXPECT_EQ(p3.ToString(), events[0].root_location().ToString()); EXPECT_EQ(p3.ToString(), events[1].root_location().ToString()); } TEST_F(AutoclickTest, MovementThreshold) { UpdateDisplay("1280x1024,800x600"); RunAllPendingInMessageLoop(); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); EXPECT_EQ(2u, root_windows.size()); // Run test for the secondary display too to test fix for crbug.com/449870. for (const auto& root_window : root_windows) { gfx::Point center = root_window->GetBoundsInScreen().CenterPoint(); GetAutoclickController()->SetEnabled(true); GetEventGenerator().MoveMouseTo(center); EXPECT_EQ(2u, WaitForMouseEvents().size()); // Small mouse movements should not trigger an autoclick. GetEventGenerator().MoveMouseTo(center + gfx::Vector2d(1, 1)); EXPECT_EQ(0u, WaitForMouseEvents().size()); GetEventGenerator().MoveMouseTo(center + gfx::Vector2d(2, 2)); EXPECT_EQ(0u, WaitForMouseEvents().size()); GetEventGenerator().MoveMouseTo(center); EXPECT_EQ(0u, WaitForMouseEvents().size()); // A large mouse movement should trigger an autoclick. GetEventGenerator().MoveMouseTo(center + gfx::Vector2d(100, 100)); EXPECT_EQ(2u, WaitForMouseEvents().size()); } } TEST_F(AutoclickTest, SingleKeyModifier) { GetAutoclickController()->SetEnabled(true); MoveMouseWithFlagsTo(20, 20, ui::EF_SHIFT_DOWN); std::vector<ui::MouseEvent> events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); EXPECT_EQ(ui::EF_SHIFT_DOWN, events[0].flags() & ui::EF_SHIFT_DOWN); EXPECT_EQ(ui::EF_SHIFT_DOWN, events[1].flags() & ui::EF_SHIFT_DOWN); } TEST_F(AutoclickTest, MultipleKeyModifiers) { GetAutoclickController()->SetEnabled(true); ui::EventFlags modifier_flags = static_cast<ui::EventFlags>( ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_SHIFT_DOWN); MoveMouseWithFlagsTo(30, 30, modifier_flags); std::vector<ui::MouseEvent> events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); EXPECT_EQ(modifier_flags, events[0].flags() & modifier_flags); EXPECT_EQ(modifier_flags, events[1].flags() & modifier_flags); } TEST_F(AutoclickTest, KeyModifiersReleased) { GetAutoclickController()->SetEnabled(true); ui::EventFlags modifier_flags = static_cast<ui::EventFlags>( ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_SHIFT_DOWN); MoveMouseWithFlagsTo(12, 12, modifier_flags); // Simulate releasing key modifiers by sending key released events. GetEventGenerator().ReleaseKey(ui::VKEY_CONTROL, static_cast<ui::EventFlags>(ui::EF_ALT_DOWN | ui::EF_SHIFT_DOWN)); GetEventGenerator().ReleaseKey(ui::VKEY_SHIFT, ui::EF_ALT_DOWN); std::vector<ui::MouseEvent> events; events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); EXPECT_EQ(0, events[0].flags() & ui::EF_CONTROL_DOWN); EXPECT_EQ(0, events[0].flags() & ui::EF_SHIFT_DOWN); EXPECT_EQ(ui::EF_ALT_DOWN, events[0].flags() & ui::EF_ALT_DOWN); } TEST_F(AutoclickTest, UserInputCancelsAutoclick) { GetAutoclickController()->SetEnabled(true); std::vector<ui::MouseEvent> events; // Pressing a normal key should cancel the autoclick. GetEventGenerator().MoveMouseTo(200, 200); GetEventGenerator().PressKey(ui::VKEY_K, ui::EF_NONE); GetEventGenerator().ReleaseKey(ui::VKEY_K, ui::EF_NONE); events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); // Pressing a modifier key should NOT cancel the autoclick. GetEventGenerator().MoveMouseTo(100, 100); GetEventGenerator().PressKey(ui::VKEY_SHIFT, ui::EF_SHIFT_DOWN); GetEventGenerator().ReleaseKey(ui::VKEY_SHIFT, ui::EF_NONE); events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); // Performing a gesture should cancel the autoclick. GetEventGenerator().MoveMouseTo(200, 200); GetEventGenerator().GestureTapDownAndUp(gfx::Point(100, 100)); events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); // Test another gesture. GetEventGenerator().MoveMouseTo(100, 100); GetEventGenerator().GestureScrollSequence( gfx::Point(100, 100), gfx::Point(200, 200), base::TimeDelta::FromMilliseconds(200), 3); events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); // Test scroll events. GetEventGenerator().MoveMouseTo(200, 200); GetEventGenerator().ScrollSequence( gfx::Point(100, 100), base::TimeDelta::FromMilliseconds(200), 0, 100, 3, 2); events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); } TEST_F(AutoclickTest, SynthesizedMouseMovesIgnored) { GetAutoclickController()->SetEnabled(true); std::vector<ui::MouseEvent> events; GetEventGenerator().MoveMouseTo(100, 100); events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); // Show a window and make sure the new window is under the cursor. As a // result, synthesized mouse events will be dispatched to the window, but it // should not trigger an autoclick. aura::test::EventCountDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowInShellWithDelegate( &delegate, 123, gfx::Rect(50, 50, 100, 100))); window->Show(); events = WaitForMouseEvents(); EXPECT_EQ(0u, events.size()); EXPECT_EQ("1 1 0", delegate.GetMouseMotionCountsAndReset()); } } // namespace ash
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *bitcoin_strings[] = {QT_TRANSLATE_NOOP("bitcoin-core", "MachtCoin version"), QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"), QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or MachtCoind"), QT_TRANSLATE_NOOP("bitcoin-core", "List commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"), QT_TRANSLATE_NOOP("bitcoin-core", "Options:"), QT_TRANSLATE_NOOP("bitcoin-core", "This help message"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: MachtCoin.conf)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: MachtCoind.pid)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database disk log size in megabytes (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect through SOCKS5 proxy"), QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 11333 or testnet: 20130)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"), QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"), QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"), QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Bind to given address. Use [host]:port notation for IPv6"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Query for peer addresses via DNS lookup, if low on addresses (default: 1 " "unless -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Always query for peer addresses via DNS lookup (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Sync time with other nodes. Disable if time on your system is precise e.g. " "syncing with NTP (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: " "86400)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"), QT_TRANSLATE_NOOP("bitcoin-core", "" "When creating transactions, ignore inputs with value less than this " "(default: 0.01)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Output debugging information (default: 0, supplying <category> is optional)"), QT_TRANSLATE_NOOP("bitcoin-core", "If <category> is not supplied, output all debugging information."), QT_TRANSLATE_NOOP("bitcoin-core", "<category> can be:"), QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"), QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Enter regression test mode, which uses a special chain in which blocks can " "be solved instantly. This is intended for regression testing tools and app " "development."), QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Listen for JSON-RPC connections on <port> (default: 11332 or testnet: 20131)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"), QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Wait for RPC server to start"), QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: 4)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("bitcoin-core", "Require a confirmations for change (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a relevant alert is received (%s in cmd is replaced by " "message)"), QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 500, 0 = all)"), QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-6, default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000?.dat file"), QT_TRANSLATE_NOOP("bitcoin-core", "Keep at most <n> MiB of unconnectable blocks in memory (default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"), QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Bitcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"), QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!" "3DES:@STRENGTH)"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Deprecated argument -debugnet ignored, use -debug=net"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: Unsupported argument -socks found. Setting SOCKS version isn't " "possible anymore, only SOCKS5 proxies are supported."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mininput=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Initialization sanity check failed. MachtCoin is shutting down."), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside data directory %s."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot obtain a lock on data directory %s. MachtCoin is probably already " "running."), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying database integrity..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -reservebalance=<amount>"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of MachtCoin"), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart MachtCoin to complete"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."), QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "This is a pre-release test build - use at your own risk - do not use for " "mining or merchant applications"), QT_TRANSLATE_NOOP("bitcoin-core", "Error"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning"), QT_TRANSLATE_NOOP("bitcoin-core", "Information"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong MachtCoin will not work properly."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Unable to bind to %s on this computer. MachtCoin is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet unlocked for staking only, unable to create transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Transaction creation failed!"), QT_TRANSLATE_NOOP("bitcoin-core", "Sending..."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: The transaction was rejected! This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"), QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"), QT_TRANSLATE_NOOP("bitcoin-core", "" "You must set rpcpassword=<password> in the configuration file:\n" "%s\n" "If the file does not exist, create it with owner-readable-only file " "permissions."), QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"), QT_TRANSLATE_NOOP("bitcoin-core", "" "%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=machtcoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"MachtCoin Alert\" admin@foo." "com\n"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv6, " "falling back to IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv4: %s"), };
// 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 <boost/version.hpp> #if defined(WIN32) && BOOST_VERSION == 104900 #define BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME #define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME #endif #include "qtipcserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include <boost/version.hpp> #if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900) #warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392 #endif using namespace boost; using namespace boost::interprocess; using namespace boost::posix_time; #if defined MAC_OSX || defined __FreeBSD__ // URI handling not implemented on OSX yet void ipcScanRelay(int argc, char *argv[]) { } void ipcInit(int argc, char *argv[]) { } #else static void ipcThread2(void* pArg); static bool ipcScanCmd(int argc, char *argv[], bool fRelay) { // Check for URI in argv bool fSent = false; for (int i = 1; i < argc; i++) { if (boost::algorithm::istarts_with(argv[i], "zombucks:")) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if (mq.try_send(strURI, strlen(strURI), 0)) fSent = true; else if (fRelay) break; } catch (boost::interprocess::interprocess_exception &ex) { // don't log the "file not found" exception, because that's normal for // the first start of the first instance if (ex.get_error_code() != boost::interprocess::not_found_error || !fRelay) { printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what()); break; } } } } return fSent; } void ipcScanRelay(int argc, char *argv[]) { if (ipcScanCmd(argc, argv, true)) exit(0); } static void ipcThread(void* pArg) { // Make this thread recognisable as the GUI-IPC thread RenameThread("zombucks-gui-ipc"); try { ipcThread2(pArg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ipcThread()"); } catch (...) { PrintExceptionContinue(NULL, "ipcThread()"); } printf("ipcThread exited\n"); } static void ipcThread2(void* pArg) { printf("ipcThread started\n"); message_queue* mq = (message_queue*)pArg; char buffer[MAX_URI_LENGTH + 1] = ""; size_t nSize = 0; unsigned int nPriority = 0; while (true) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100); if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize)); MilliSleep(1000); } if (fShutdown) break; } // Remove message queue message_queue::remove(BITCOINURI_QUEUE_NAME); // Cleanup allocated memory delete mq; } void ipcInit(int argc, char *argv[]) { message_queue* mq = NULL; char buffer[MAX_URI_LENGTH + 1] = ""; size_t nSize = 0; unsigned int nPriority = 0; try { mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH); // Make sure we don't lose any bitcoin: URIs for (int i = 0; i < 2; i++) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1); if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize)); } else break; } // Make sure only one bitcoin instance is listening message_queue::remove(BITCOINURI_QUEUE_NAME); delete mq; mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH); } catch (interprocess_exception &ex) { printf("ipcInit() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what()); return; } if (!NewThread(ipcThread, mq)) { delete mq; return; } ipcScanCmd(argc, argv, false); } #endif
#include "Halide.h" #include <tiramisu/utils.h> #include <cstdlib> #include <iostream> #include "wrapper_test_23.h" #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } // extern "C" #endif int main(int, char **) { Halide::Buffer<uint8_t> reference_buf1(SIZE0, SIZE1); Halide::Buffer<uint8_t> reference_buf2(SIZE0, SIZE1); init_buffer(reference_buf1, (uint8_t)1); init_buffer(reference_buf2, (uint8_t)4); Halide::Buffer<uint8_t> output_buf0(SIZE0, SIZE1); Halide::Buffer<uint8_t> output_buf1(SIZE0, SIZE1); Halide::Buffer<uint8_t> output_buf2(SIZE0, SIZE1); Halide::Buffer<uint8_t> output_buf3(SIZE0, SIZE1); Halide::Buffer<uint8_t> output_buf4(SIZE0, SIZE1); init_buffer(output_buf0, (uint8_t)0); init_buffer(output_buf1, (uint8_t)0); init_buffer(output_buf2, (uint8_t)0); init_buffer(output_buf3, (uint8_t)0); init_buffer(output_buf4, (uint8_t)0); // Call the Tiramisu generated code tiramisu_generated_code(output_buf0.raw_buffer(), output_buf1.raw_buffer(), output_buf2.raw_buffer(), output_buf3.raw_buffer(), output_buf4.raw_buffer()); compare_buffers(std::string(TEST_NAME_STR) + " 2", output_buf1, reference_buf1); compare_buffers(std::string(TEST_NAME_STR) + " 3", output_buf4, reference_buf2); return 0; }
// 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 "components/autofill/core/browser/ui/payments/card_name_fix_flow_controller_impl.h" #include <utility> #include "base/check.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/ui/payments/card_name_fix_flow_view.h" #include "components/grit/components_scaled_resources.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace autofill { CardNameFixFlowControllerImpl::CardNameFixFlowControllerImpl() {} CardNameFixFlowControllerImpl::~CardNameFixFlowControllerImpl() { if (card_name_fix_flow_view_) card_name_fix_flow_view_->ControllerGone(); if (shown_ && !had_user_interaction_) { AutofillMetrics::LogCardholderNameFixFlowPromptEvent( AutofillMetrics:: CARDHOLDER_NAME_FIX_FLOW_PROMPT_CLOSED_WITHOUT_INTERACTION); } } void CardNameFixFlowControllerImpl::Show( CardNameFixFlowView* card_name_fix_flow_view, const std::u16string& inferred_cardholder_name, base::OnceCallback<void(const std::u16string&)> name_accepted_callback) { DCHECK(!name_accepted_callback.is_null()); DCHECK(card_name_fix_flow_view); if (card_name_fix_flow_view_) card_name_fix_flow_view_->ControllerGone(); card_name_fix_flow_view_ = card_name_fix_flow_view; name_accepted_callback_ = std::move(name_accepted_callback); inferred_cardholder_name_ = inferred_cardholder_name; AutofillMetrics::LogSaveCardCardholderNamePrefilled( !inferred_cardholder_name_.empty()); card_name_fix_flow_view_->Show(); AutofillMetrics::LogCardholderNameFixFlowPromptEvent( AutofillMetrics::CARDHOLDER_NAME_FIX_FLOW_PROMPT_SHOWN); shown_ = true; } void CardNameFixFlowControllerImpl::OnConfirmNameDialogClosed() { card_name_fix_flow_view_ = nullptr; } void CardNameFixFlowControllerImpl::OnNameAccepted(const std::u16string& name) { AutofillMetrics::LogCardholderNameFixFlowPromptEvent( AutofillMetrics::CARDHOLDER_NAME_FIX_FLOW_PROMPT_ACCEPTED); had_user_interaction_ = true; AutofillMetrics::LogSaveCardCardholderNameWasEdited( inferred_cardholder_name_ != name); std::u16string trimmed_name; base::TrimWhitespace(name, base::TRIM_ALL, &trimmed_name); std::move(name_accepted_callback_).Run(trimmed_name); } void CardNameFixFlowControllerImpl::OnDismissed() { AutofillMetrics::LogCardholderNameFixFlowPromptEvent( AutofillMetrics::CARDHOLDER_NAME_FIX_FLOW_PROMPT_DISMISSED); had_user_interaction_ = true; } int CardNameFixFlowControllerImpl::GetIconId() const { #if BUILDFLAG(GOOGLE_CHROME_BRANDING) return IDR_AUTOFILL_GOOGLE_PAY_WITH_DIVIDER; #else return 0; #endif } std::u16string CardNameFixFlowControllerImpl::GetCancelButtonLabel() const { return l10n_util::GetStringUTF16(IDS_CANCEL); } std::u16string CardNameFixFlowControllerImpl::GetInferredCardholderName() const { return inferred_cardholder_name_; } std::u16string CardNameFixFlowControllerImpl::GetInferredNameTooltipText() const { return l10n_util::GetStringUTF16( IDS_AUTOFILL_SAVE_CARD_PROMPT_CARDHOLDER_NAME_TOOLTIP); } std::u16string CardNameFixFlowControllerImpl::GetInputLabel() const { return l10n_util::GetStringUTF16( IDS_AUTOFILL_SAVE_CARD_PROMPT_CARDHOLDER_NAME); } std::u16string CardNameFixFlowControllerImpl::GetInputPlaceholderText() const { return l10n_util::GetStringUTF16( IDS_AUTOFILL_SAVE_CARD_PROMPT_CARDHOLDER_NAME); } std::u16string CardNameFixFlowControllerImpl::GetSaveButtonLabel() const { #if defined(OS_IOS) return l10n_util::GetStringUTF16(IDS_SAVE); #else return l10n_util::GetStringUTF16( IDS_AUTOFILL_FIX_FLOW_PROMPT_SAVE_CARD_LABEL); #endif } std::u16string CardNameFixFlowControllerImpl::GetTitleText() const { return l10n_util::GetStringUTF16( IDS_AUTOFILL_SAVE_CARD_CARDHOLDER_NAME_FIX_FLOW_HEADER); } } // namespace autofill
// Copyright (c) 2020, devgo.club // All rights reserved. #include <stdint.h> #include <stdlib.h> #include <iostream> #include <string> class Student { public: std::string get_name() { return m_strName; }; void set_name(std::string _name) { m_strName = _name; }; int get_score() { return m_iScore; } void study(int _score) { m_iScore += _score; } private: std::string m_strName; int m_iScore; }; int main(int argc, char **argv) { Student *stu = new Student(); if (stu == NULL) { std::cout << "create new student failed" << std::endl; return EXIT_FAILURE; } stu->set_name("Terrence"); stu->study(60); stu->study(60); std::cout << "name: " << stu->get_name() << ", score: " << stu->get_score() << std::endl; return EXIT_SUCCESS; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/touch/touch_observer_hud.h" #include "ash/root_window_controller.h" #include "ash/root_window_settings.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ui/aura/root_window.h" #include "ui/gfx/display.h" #include "ui/gfx/rect.h" #include "ui/gfx/screen.h" #include "ui/gfx/size.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { TouchObserverHUD::TouchObserverHUD(aura::Window* initial_root) : display_id_(GetRootWindowSettings(initial_root)->display_id), root_window_(initial_root), widget_(NULL) { const gfx::Display& display = Shell::GetInstance()->display_manager()->GetDisplayForId(display_id_); views::View* content = new views::View; const gfx::Size& display_size = display.size(); content->SetSize(display_size); widget_ = new views::Widget(); views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.can_activate = false; params.accept_events = false; params.bounds = display.bounds(); params.parent = Shell::GetContainer( root_window_, internal::kShellWindowId_OverlayContainer); widget_->Init(params); widget_->SetContentsView(content); widget_->StackAtTop(); widget_->Show(); widget_->AddObserver(this); // Observe changes in display size and mode to update touch HUD. Shell::GetScreen()->AddObserver(this); #if defined(OS_CHROMEOS) Shell::GetInstance()->output_configurator()->AddObserver(this); #endif // defined(OS_CHROMEOS) Shell::GetInstance()->display_controller()->AddObserver(this); root_window_->AddPreTargetHandler(this); } TouchObserverHUD::~TouchObserverHUD() { Shell::GetInstance()->display_controller()->RemoveObserver(this); #if defined(OS_CHROMEOS) Shell::GetInstance()->output_configurator()->RemoveObserver(this); #endif // defined(OS_CHROMEOS) Shell::GetScreen()->RemoveObserver(this); widget_->RemoveObserver(this); } void TouchObserverHUD::Clear() { } void TouchObserverHUD::Remove() { root_window_->RemovePreTargetHandler(this); RootWindowController* controller = GetRootWindowController(root_window_); UnsetHudForRootWindowController(controller); widget_->CloseNow(); } void TouchObserverHUD::OnTouchEvent(ui::TouchEvent* /*event*/) { } void TouchObserverHUD::OnWidgetDestroying(views::Widget* widget) { DCHECK_EQ(widget, widget_); delete this; } void TouchObserverHUD::OnDisplayBoundsChanged(const gfx::Display& display) { if (display.id() != display_id_) return; widget_->SetSize(display.size()); } void TouchObserverHUD::OnDisplayAdded(const gfx::Display& new_display) {} void TouchObserverHUD::OnDisplayRemoved(const gfx::Display& old_display) { if (old_display.id() != display_id_) return; widget_->CloseNow(); } #if defined(OS_CHROMEOS) void TouchObserverHUD::OnDisplayModeChanged( const std::vector<chromeos::OutputConfigurator::OutputSnapshot>& outputs) { // Clear touch HUD for any change in display mode (single, dual extended, dual // mirrored, ...). Clear(); } #endif // defined(OS_CHROMEOS) void TouchObserverHUD::OnDisplayConfigurationChanging() { if (!root_window_) return; root_window_->RemovePreTargetHandler(this); RootWindowController* controller = GetRootWindowController(root_window_); UnsetHudForRootWindowController(controller); views::Widget::ReparentNativeView( widget_->GetNativeView(), Shell::GetContainer(root_window_, internal::kShellWindowId_UnparentedControlContainer)); root_window_ = NULL; } void TouchObserverHUD::OnDisplayConfigurationChanged() { if (root_window_) return; root_window_ = Shell::GetInstance()->display_controller()-> GetRootWindowForDisplayId(display_id_); views::Widget::ReparentNativeView( widget_->GetNativeView(), Shell::GetContainer(root_window_, internal::kShellWindowId_OverlayContainer)); RootWindowController* controller = GetRootWindowController(root_window_); SetHudForRootWindowController(controller); root_window_->AddPreTargetHandler(this); } } // namespace internal } // namespace ash