diff options
author | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-06-27 06:07:23 +0000 |
---|---|---|
committer | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-06-27 06:07:23 +0000 |
commit | 1bf1084f2b10c3b47fd1a588d85d21ed0eb41d0c (patch) | |
tree | 46dcd36c86e7fbc6e5df36deb463b33e9967a6f7 /Source/JavaScriptCore/inspector | |
parent | 32761a6cee1d0dee366b885b7b9c777e67885688 (diff) | |
download | WebKitGtk-tarball-master.tar.gz |
webkitgtk-2.16.5HEADwebkitgtk-2.16.5master
Diffstat (limited to 'Source/JavaScriptCore/inspector')
220 files changed, 41423 insertions, 6364 deletions
diff --git a/Source/JavaScriptCore/inspector/AsyncStackTrace.cpp b/Source/JavaScriptCore/inspector/AsyncStackTrace.cpp new file mode 100644 index 000000000..4002964ac --- /dev/null +++ b/Source/JavaScriptCore/inspector/AsyncStackTrace.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2017 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "AsyncStackTrace.h" + +#include "InspectorValues.h" +#include "ScriptCallStack.h" + +namespace Inspector { + +RefPtr<AsyncStackTrace> AsyncStackTrace::create(Ref<ScriptCallStack>&& callStack, bool singleShot, RefPtr<AsyncStackTrace> parent) +{ + ASSERT(callStack->size()); + return adoptRef(*new AsyncStackTrace(WTFMove(callStack), singleShot, WTFMove(parent))); +} + +AsyncStackTrace::AsyncStackTrace(Ref<ScriptCallStack>&& callStack, bool singleShot, RefPtr<AsyncStackTrace> parent) + : m_callStack(WTFMove(callStack)) + , m_parent(parent) + , m_singleShot(singleShot) +{ + if (m_parent) + m_parent->m_childCount++; +} + +AsyncStackTrace::~AsyncStackTrace() +{ + if (m_parent) + remove(); + ASSERT(!m_childCount); +} + +bool AsyncStackTrace::isPending() const +{ + return m_state == State::Pending; +} + +bool AsyncStackTrace::isLocked() const +{ + return m_state == State::Pending || m_state == State::Active || m_childCount > 1; +} + +void AsyncStackTrace::willDispatchAsyncCall(size_t maxDepth) +{ + ASSERT(m_state == State::Pending); + m_state = State::Active; + + truncate(maxDepth); +} + +void AsyncStackTrace::didDispatchAsyncCall() +{ + ASSERT(m_state == State::Active || m_state == State::Canceled); + + if (m_state == State::Active && !m_singleShot) { + m_state = State::Pending; + return; + } + + m_state = State::Dispatched; + + if (!m_childCount) + remove(); +} + +void AsyncStackTrace::didCancelAsyncCall() +{ + if (m_state == State::Canceled) + return; + + if (m_state == State::Pending && !m_childCount) + remove(); + + m_state = State::Canceled; +} + +RefPtr<Inspector::Protocol::Console::StackTrace> AsyncStackTrace::buildInspectorObject() const +{ + RefPtr<Inspector::Protocol::Console::StackTrace> topStackTrace; + RefPtr<Inspector::Protocol::Console::StackTrace> previousStackTrace; + + auto* stackTrace = this; + while (stackTrace) { + auto& callStack = stackTrace->m_callStack; + ASSERT(callStack->size()); + + RefPtr<Inspector::Protocol::Console::StackTrace> protocolObject = Inspector::Protocol::Console::StackTrace::create() + .setCallFrames(callStack->buildInspectorArray()) + .release(); + + if (stackTrace->m_truncated) + protocolObject->setTruncated(true); + if (callStack->at(0).isNative()) + protocolObject->setTopCallFrameIsBoundary(true); + + if (!topStackTrace) + topStackTrace = protocolObject; + + if (previousStackTrace) + previousStackTrace->setParentStackTrace(protocolObject); + + previousStackTrace = protocolObject; + stackTrace = stackTrace->m_parent.get(); + } + + return topStackTrace; +} + +void AsyncStackTrace::truncate(size_t maxDepth) +{ + AsyncStackTrace* lastUnlockedAncestor = nullptr; + size_t depth = 0; + + auto* newStackTraceRoot = this; + while (newStackTraceRoot) { + depth += newStackTraceRoot->m_callStack->size(); + if (depth >= maxDepth) + break; + + auto* parent = newStackTraceRoot->m_parent.get(); + if (!lastUnlockedAncestor && parent && parent->isLocked()) + lastUnlockedAncestor = newStackTraceRoot; + + newStackTraceRoot = parent; + } + + if (!newStackTraceRoot || !newStackTraceRoot->m_parent) + return; + + if (!lastUnlockedAncestor) { + // No locked nodes belong to the trace. The subtree at the new root + // is moved to a new tree, and marked as truncated if necessary. + newStackTraceRoot->m_truncated = true; + newStackTraceRoot->remove(); + return; + } + + // The new root has a locked descendent. Since truncating a stack trace + // cannot mutate locked nodes or their ancestors, a new tree is created by + // cloning the locked portion of the trace (the path from the locked node + // to the new root). The subtree rooted at the last unlocked ancestor is + // then appended to the new tree. + auto* currentNode = lastUnlockedAncestor; + while (currentNode->m_parent) { + auto& parentNode = currentNode->m_parent; + currentNode->m_parent = AsyncStackTrace::create(parentNode->m_callStack.copyRef(), true, parentNode->m_parent); + currentNode = currentNode->m_parent.get(); + + if (parentNode.get() == newStackTraceRoot) + break; + } + + currentNode->m_truncated = true; + currentNode->remove(); + + // Decrement the child count of the first locked ancestor after removing its subtree. + auto& firstLockedAncestor = lastUnlockedAncestor->m_parent; + firstLockedAncestor->m_childCount--; +} + +void AsyncStackTrace::remove() +{ + if (!m_parent) + return; + + ASSERT(m_parent->m_childCount); + m_parent->m_childCount--; + m_parent = nullptr; +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/AsyncStackTrace.h b/Source/JavaScriptCore/inspector/AsyncStackTrace.h new file mode 100644 index 000000000..a618fe7af --- /dev/null +++ b/Source/JavaScriptCore/inspector/AsyncStackTrace.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2017 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorProtocolObjects.h" +#include <wtf/Forward.h> +#include <wtf/RefCounted.h> + +namespace Inspector { + +class ScriptCallStack; + +class JS_EXPORT_PRIVATE AsyncStackTrace : public RefCounted<AsyncStackTrace> { +public: + enum class State { + Pending, + Active, + Dispatched, + Canceled, + }; + + static RefPtr<AsyncStackTrace> create(Ref<ScriptCallStack>&&, bool singleShot, RefPtr<AsyncStackTrace> parent); + + bool isPending() const; + bool isLocked() const; + + void willDispatchAsyncCall(size_t maxDepth); + void didDispatchAsyncCall(); + void didCancelAsyncCall(); + + RefPtr<Inspector::Protocol::Console::StackTrace> buildInspectorObject() const; + + ~AsyncStackTrace(); + +private: + AsyncStackTrace(Ref<ScriptCallStack>&&, bool, RefPtr<AsyncStackTrace>); + + void truncate(size_t maxDepth); + void remove(); + + Ref<ScriptCallStack> m_callStack; + RefPtr<AsyncStackTrace> m_parent; + unsigned m_childCount { 0 }; + State m_state { State::Pending }; + bool m_truncated { false }; + bool m_singleShot { true }; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ConsoleMessage.cpp b/Source/JavaScriptCore/inspector/ConsoleMessage.cpp new file mode 100644 index 000000000..ef09fcc1e --- /dev/null +++ b/Source/JavaScriptCore/inspector/ConsoleMessage.cpp @@ -0,0 +1,284 @@ +/* + * Copyright (C) 2007, 2008, 2014, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com> + * Copyright (C) 2009, 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 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 Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ConsoleMessage.h" + +#include "IdentifiersFactory.h" +#include "InjectedScript.h" +#include "InjectedScriptManager.h" +#include "InspectorValues.h" +#include "ScriptArguments.h" +#include "ScriptCallFrame.h" +#include "ScriptCallStack.h" +#include "ScriptCallStackFactory.h" +#include "ScriptValue.h" + +namespace Inspector { + +ConsoleMessage::ConsoleMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned long requestIdentifier) + : m_source(source) + , m_type(type) + , m_level(level) + , m_message(message) + , m_url() + , m_requestId(IdentifiersFactory::requestId(requestIdentifier)) +{ +} + +ConsoleMessage::ConsoleMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& url, unsigned line, unsigned column, JSC::ExecState* state, unsigned long requestIdentifier) + : m_source(source) + , m_type(type) + , m_level(level) + , m_message(message) + , m_url(url) + , m_line(line) + , m_column(column) + , m_requestId(IdentifiersFactory::requestId(requestIdentifier)) +{ + autogenerateMetadata(state); +} + +ConsoleMessage::ConsoleMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, Ref<ScriptCallStack>&& callStack, unsigned long requestIdentifier) + : m_source(source) + , m_type(type) + , m_level(level) + , m_message(message) + , m_callStack(WTFMove(callStack)) + , m_url() + , m_requestId(IdentifiersFactory::requestId(requestIdentifier)) +{ + const ScriptCallFrame* frame = m_callStack ? m_callStack->firstNonNativeCallFrame() : nullptr; + if (frame) { + m_url = frame->sourceURL(); + m_line = frame->lineNumber(); + m_column = frame->columnNumber(); + } +} + +ConsoleMessage::ConsoleMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, Ref<ScriptArguments>&& arguments, JSC::ExecState* state, unsigned long requestIdentifier) + : m_source(source) + , m_type(type) + , m_level(level) + , m_message(message) + , m_arguments(WTFMove(arguments)) + , m_url() + , m_requestId(IdentifiersFactory::requestId(requestIdentifier)) +{ + autogenerateMetadata(state); +} + +ConsoleMessage::~ConsoleMessage() +{ +} + +void ConsoleMessage::autogenerateMetadata(JSC::ExecState* state) +{ + if (!state) + return; + + if (m_type == MessageType::EndGroup) + return; + + // FIXME: Should this really be using "for console" in the generic ConsoleMessage autogeneration? This can skip the first frame. + m_callStack = createScriptCallStackForConsole(state, ScriptCallStack::maxCallStackSizeToCapture); + + if (const ScriptCallFrame* frame = m_callStack->firstNonNativeCallFrame()) { + m_url = frame->sourceURL(); + m_line = frame->lineNumber(); + m_column = frame->columnNumber(); + return; + } +} + +static Inspector::Protocol::Console::ConsoleMessage::Source messageSourceValue(MessageSource source) +{ + switch (source) { + case MessageSource::XML: return Inspector::Protocol::Console::ConsoleMessage::Source::XML; + case MessageSource::JS: return Inspector::Protocol::Console::ConsoleMessage::Source::Javascript; + case MessageSource::Network: return Inspector::Protocol::Console::ConsoleMessage::Source::Network; + case MessageSource::ConsoleAPI: return Inspector::Protocol::Console::ConsoleMessage::Source::ConsoleAPI; + case MessageSource::Storage: return Inspector::Protocol::Console::ConsoleMessage::Source::Storage; + case MessageSource::AppCache: return Inspector::Protocol::Console::ConsoleMessage::Source::Appcache; + case MessageSource::Rendering: return Inspector::Protocol::Console::ConsoleMessage::Source::Rendering; + case MessageSource::CSS: return Inspector::Protocol::Console::ConsoleMessage::Source::CSS; + case MessageSource::Security: return Inspector::Protocol::Console::ConsoleMessage::Source::Security; + case MessageSource::ContentBlocker: return Inspector::Protocol::Console::ConsoleMessage::Source::ContentBlocker; + case MessageSource::Other: return Inspector::Protocol::Console::ConsoleMessage::Source::Other; + } + return Inspector::Protocol::Console::ConsoleMessage::Source::Other; +} + +static Inspector::Protocol::Console::ConsoleMessage::Type messageTypeValue(MessageType type) +{ + switch (type) { + case MessageType::Log: return Inspector::Protocol::Console::ConsoleMessage::Type::Log; + case MessageType::Clear: return Inspector::Protocol::Console::ConsoleMessage::Type::Clear; + case MessageType::Dir: return Inspector::Protocol::Console::ConsoleMessage::Type::Dir; + case MessageType::DirXML: return Inspector::Protocol::Console::ConsoleMessage::Type::DirXML; + case MessageType::Table: return Inspector::Protocol::Console::ConsoleMessage::Type::Table; + case MessageType::Trace: return Inspector::Protocol::Console::ConsoleMessage::Type::Trace; + case MessageType::StartGroup: return Inspector::Protocol::Console::ConsoleMessage::Type::StartGroup; + case MessageType::StartGroupCollapsed: return Inspector::Protocol::Console::ConsoleMessage::Type::StartGroupCollapsed; + case MessageType::EndGroup: return Inspector::Protocol::Console::ConsoleMessage::Type::EndGroup; + case MessageType::Assert: return Inspector::Protocol::Console::ConsoleMessage::Type::Assert; + case MessageType::Timing: return Inspector::Protocol::Console::ConsoleMessage::Type::Timing; + case MessageType::Profile: return Inspector::Protocol::Console::ConsoleMessage::Type::Profile; + case MessageType::ProfileEnd: return Inspector::Protocol::Console::ConsoleMessage::Type::ProfileEnd; + } + return Inspector::Protocol::Console::ConsoleMessage::Type::Log; +} + +static Inspector::Protocol::Console::ConsoleMessage::Level messageLevelValue(MessageLevel level) +{ + switch (level) { + case MessageLevel::Log: return Inspector::Protocol::Console::ConsoleMessage::Level::Log; + case MessageLevel::Info: return Inspector::Protocol::Console::ConsoleMessage::Level::Info; + case MessageLevel::Warning: return Inspector::Protocol::Console::ConsoleMessage::Level::Warning; + case MessageLevel::Error: return Inspector::Protocol::Console::ConsoleMessage::Level::Error; + case MessageLevel::Debug: return Inspector::Protocol::Console::ConsoleMessage::Level::Debug; + } + return Inspector::Protocol::Console::ConsoleMessage::Level::Log; +} + +void ConsoleMessage::addToFrontend(ConsoleFrontendDispatcher& consoleFrontendDispatcher, InjectedScriptManager& injectedScriptManager, bool generatePreview) +{ + Ref<Inspector::Protocol::Console::ConsoleMessage> jsonObj = Inspector::Protocol::Console::ConsoleMessage::create() + .setSource(messageSourceValue(m_source)) + .setLevel(messageLevelValue(m_level)) + .setText(m_message) + .release(); + + // FIXME: only send out type for ConsoleAPI source messages. + jsonObj->setType(messageTypeValue(m_type)); + jsonObj->setLine(static_cast<int>(m_line)); + jsonObj->setColumn(static_cast<int>(m_column)); + jsonObj->setUrl(m_url); + jsonObj->setRepeatCount(static_cast<int>(m_repeatCount)); + + if (m_source == MessageSource::Network && !m_requestId.isEmpty()) + jsonObj->setNetworkRequestId(m_requestId); + + if (m_arguments && m_arguments->argumentCount()) { + InjectedScript injectedScript = injectedScriptManager.injectedScriptFor(m_arguments->globalState()); + if (!injectedScript.hasNoValue()) { + Ref<Inspector::Protocol::Array<Inspector::Protocol::Runtime::RemoteObject>> jsonArgs = Inspector::Protocol::Array<Inspector::Protocol::Runtime::RemoteObject>::create(); + if (m_type == MessageType::Table && generatePreview && m_arguments->argumentCount()) { + Deprecated::ScriptValue table = m_arguments->argumentAt(0); + Deprecated::ScriptValue columns = m_arguments->argumentCount() > 1 ? m_arguments->argumentAt(1) : Deprecated::ScriptValue(); + RefPtr<Inspector::Protocol::Runtime::RemoteObject> inspectorValue = injectedScript.wrapTable(table, columns); + if (!inspectorValue) { + ASSERT_NOT_REACHED(); + return; + } + jsonArgs->addItem(inspectorValue.copyRef()); + if (m_arguments->argumentCount() > 1) + jsonArgs->addItem(injectedScript.wrapObject(columns, ASCIILiteral("console"), true)); + } else { + for (unsigned i = 0; i < m_arguments->argumentCount(); ++i) { + RefPtr<Inspector::Protocol::Runtime::RemoteObject> inspectorValue = injectedScript.wrapObject(m_arguments->argumentAt(i), ASCIILiteral("console"), generatePreview); + if (!inspectorValue) { + ASSERT_NOT_REACHED(); + return; + } + jsonArgs->addItem(inspectorValue.copyRef()); + } + } + jsonObj->setParameters(WTFMove(jsonArgs)); + } + } + + if (m_callStack) + jsonObj->setStackTrace(m_callStack->buildInspectorArray()); + + consoleFrontendDispatcher.messageAdded(WTFMove(jsonObj)); +} + +void ConsoleMessage::updateRepeatCountInConsole(ConsoleFrontendDispatcher& consoleFrontendDispatcher) +{ + consoleFrontendDispatcher.messageRepeatCountUpdated(m_repeatCount); +} + +bool ConsoleMessage::isEqual(ConsoleMessage* msg) const +{ + if (m_arguments) { + if (!m_arguments->isEqual(msg->m_arguments.get())) + return false; + + // Never treat objects as equal - their properties might change over time. + for (size_t i = 0; i < m_arguments->argumentCount(); ++i) { + if (m_arguments->argumentAt(i).isObject()) + return false; + } + } else if (msg->m_arguments) + return false; + + if (m_callStack) { + if (!m_callStack->isEqual(msg->m_callStack.get())) + return false; + } else if (msg->m_callStack) + return false; + + return msg->m_source == m_source + && msg->m_type == m_type + && msg->m_level == m_level + && msg->m_message == m_message + && msg->m_line == m_line + && msg->m_column == m_column + && msg->m_url == m_url + && msg->m_requestId == m_requestId; +} + +void ConsoleMessage::clear() +{ + if (!m_message) + m_message = ASCIILiteral("<message collected>"); + + if (m_arguments) + m_arguments = nullptr; +} + +JSC::ExecState* ConsoleMessage::scriptState() const +{ + if (m_arguments) + return m_arguments->globalState(); + + return nullptr; +} + +unsigned ConsoleMessage::argumentCount() const +{ + if (m_arguments) + return m_arguments->argumentCount(); + + return 0; +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ConsoleMessage.h b/Source/JavaScriptCore/inspector/ConsoleMessage.h new file mode 100644 index 000000000..a4d18b882 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ConsoleMessage.h @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2007, 2008, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com> + * Copyright (C) 2009, 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 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 Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "ConsoleTypes.h" +#include "InspectorFrontendDispatchers.h" +#include <wtf/Forward.h> + +namespace JSC { +class ExecState; +} + +namespace Inspector { + +class InjectedScriptManager; +class ScriptArguments; +class ScriptCallStack; + +class JS_EXPORT_PRIVATE ConsoleMessage { + WTF_MAKE_NONCOPYABLE(ConsoleMessage); + WTF_MAKE_FAST_ALLOCATED; +public: + ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& message, unsigned long requestIdentifier = 0); + ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& message, const String& url, unsigned line, unsigned column, JSC::ExecState* = nullptr, unsigned long requestIdentifier = 0); + ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& message, Ref<ScriptCallStack>&&, unsigned long requestIdentifier = 0); + ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& message, Ref<ScriptArguments>&&, JSC::ExecState*, unsigned long requestIdentifier = 0); + ~ConsoleMessage(); + + void addToFrontend(ConsoleFrontendDispatcher&, InjectedScriptManager&, bool generatePreview); + void updateRepeatCountInConsole(ConsoleFrontendDispatcher&); + + MessageSource source() const { return m_source; } + MessageType type() const { return m_type; } + MessageLevel level() const { return m_level; } + const String& message() const { return m_message; } + const String& url() const { return m_url; } + unsigned line() const { return m_line; } + unsigned column() const { return m_column; } + + JSC::ExecState* scriptState() const; + + void incrementCount() { ++m_repeatCount; } + + unsigned argumentCount() const; + + bool isEqual(ConsoleMessage* msg) const; + + void clear(); + +private: + void autogenerateMetadata(JSC::ExecState* = nullptr); + + MessageSource m_source; + MessageType m_type; + MessageLevel m_level; + String m_message; + RefPtr<ScriptArguments> m_arguments; + RefPtr<ScriptCallStack> m_callStack; + String m_url; + unsigned m_line { 0 }; + unsigned m_column { 0 }; + unsigned m_repeatCount { 1 }; + String m_requestId; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp b/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp index 8f1f91cf1..7f4504235 100644 --- a/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp +++ b/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp @@ -29,14 +29,13 @@ #include "config.h" #include "ContentSearchUtilities.h" -#if ENABLE(INSPECTOR) - -#include "InspectorJSTypeBuilders.h" #include "InspectorValues.h" #include "RegularExpression.h" #include "Yarr.h" +#include "YarrInterpreter.h" #include <wtf/BumpPointerAllocator.h> #include <wtf/StdLibExtras.h> +#include <wtf/text/StringBuilder.h> using namespace JSC::Yarr; @@ -47,17 +46,16 @@ static const char regexSpecialCharacters[] = "[](){}+-*.,?\\^$|"; static String createSearchRegexSource(const String& text) { - String result; - const UChar* characters = text.deprecatedCharacters(); - String specials(regexSpecialCharacters); + StringBuilder result; for (unsigned i = 0; i < text.length(); i++) { - if (specials.find(characters[i]) != notFound) - result.append("\\"); - result.append(characters[i]); + UChar character = text[i]; + if (isASCII(character) && strchr(regexSpecialCharacters, character)) + result.append('\\'); + result.append(character); } - return result; + return result.toString(); } static inline size_t sizetExtractor(const size_t* value) @@ -67,60 +65,64 @@ static inline size_t sizetExtractor(const size_t* value) TextPosition textPositionFromOffset(size_t offset, const Vector<size_t>& lineEndings) { - const size_t* foundLineEnding = approximateBinarySearch<size_t, size_t>(lineEndings, lineEndings.size(), offset, sizetExtractor); - size_t lineIndex = foundLineEnding - &lineEndings.at(0); - if (offset > *foundLineEnding) + const size_t* foundNextStart = approximateBinarySearch<size_t, size_t>(lineEndings, lineEndings.size(), offset, sizetExtractor); + size_t lineIndex = foundNextStart - &lineEndings.at(0); + if (offset >= *foundNextStart) ++lineIndex; - size_t lineStartOffset = lineIndex > 0 ? lineEndings.at(lineIndex - 1) + 1 : 0; + size_t lineStartOffset = lineIndex > 0 ? lineEndings.at(lineIndex - 1) : 0; size_t column = offset - lineStartOffset; return TextPosition(OrdinalNumber::fromZeroBasedInt(lineIndex), OrdinalNumber::fromZeroBasedInt(column)); } -static Vector<std::pair<int, String>> getRegularExpressionMatchesByLines(const JSC::Yarr::RegularExpression& regex, const String& text) +static Vector<std::pair<size_t, String>> getRegularExpressionMatchesByLines(const JSC::Yarr::RegularExpression& regex, const String& text) { - Vector<std::pair<int, String>> result; + Vector<std::pair<size_t, String>> result; if (text.isEmpty()) return result; - OwnPtr<Vector<size_t>> endings(lineEndings(text)); + std::unique_ptr<Vector<size_t>> endings(lineEndings(text)); size_t size = endings->size(); - unsigned start = 0; + size_t start = 0; + for (size_t lineNumber = 0; lineNumber < size; ++lineNumber) { - size_t lineEnd = endings->at(lineNumber); - String line = text.substring(start, lineEnd - start); - if (line.endsWith('\r')) - line = line.left(line.length() - 1); + size_t nextStart = endings->at(lineNumber); + String line = text.substring(start, nextStart - start); int matchLength; if (regex.match(line, 0, &matchLength) != -1) - result.append(std::pair<int, String>(lineNumber, line)); + result.append(std::pair<size_t, String>(lineNumber, line)); - start = lineEnd + 1; + start = nextStart; } + return result; } -PassOwnPtr<Vector<size_t>> lineEndings(const String& text) +std::unique_ptr<Vector<size_t>> lineEndings(const String& text) { - OwnPtr<Vector<size_t>> result(adoptPtr(new Vector<size_t>())); + auto result = std::make_unique<Vector<size_t>>(); - unsigned start = 0; + size_t start = 0; while (start < text.length()) { - size_t lineEnd = text.find('\n', start); - if (lineEnd == notFound) + size_t nextStart = text.find('\n', start); + if (nextStart == notFound || nextStart == (text.length() - 1)) { + result->append(text.length()); break; + } - result->append(lineEnd); - start = lineEnd + 1; + nextStart += 1; + result->append(nextStart); + start = nextStart; } + result->append(text.length()); - return result.release(); + return result; } -static PassRefPtr<Inspector::TypeBuilder::GenericTypes::SearchMatch> buildObjectForSearchMatch(int lineNumber, const String& lineContent) +static Ref<Inspector::Protocol::GenericTypes::SearchMatch> buildObjectForSearchMatch(size_t lineNumber, const String& lineContent) { - return Inspector::TypeBuilder::GenericTypes::SearchMatch::create() + return Inspector::Protocol::GenericTypes::SearchMatch::create() .setLineNumber(lineNumber) .setLineContent(lineContent) .release(); @@ -151,25 +153,21 @@ int countRegularExpressionMatches(const JSC::Yarr::RegularExpression& regex, con return result; } -PassRefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::GenericTypes::SearchMatch>> searchInTextByLines(const String& text, const String& query, const bool caseSensitive, const bool isRegex) +Ref<Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>> searchInTextByLines(const String& text, const String& query, const bool caseSensitive, const bool isRegex) { - RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::GenericTypes::SearchMatch>> result = Inspector::TypeBuilder::Array<Inspector::TypeBuilder::GenericTypes::SearchMatch>::create(); + Ref<Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>> result = Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>::create(); JSC::Yarr::RegularExpression regex = ContentSearchUtilities::createSearchRegex(query, caseSensitive, isRegex); - Vector<std::pair<int, String>> matches = getRegularExpressionMatchesByLines(regex, text); + Vector<std::pair<size_t, String>> matches = getRegularExpressionMatchesByLines(regex, text); - for (Vector<std::pair<int, String>>::const_iterator it = matches.begin(); it != matches.end(); ++it) - result->addItem(buildObjectForSearchMatch(it->first, it->second)); + for (const auto& match : matches) { + Ref<Inspector::Protocol::GenericTypes::SearchMatch> matchObject = buildObjectForSearchMatch(match.first, match.second); + result->addItem(WTFMove(matchObject)); + } return result; } -static String scriptCommentPattern(const String& name) -{ - // "//# <name>=<value>" and deprecated "//@" - return "//[#@][\040\t]" + name + "=[\040\t]*([^\\s\'\"]*)[\040\t]*$"; -} - static String stylesheetCommentPattern(const String& name) { // "/*# <name>=<value> */" and deprecated "/*@" @@ -178,11 +176,12 @@ static String stylesheetCommentPattern(const String& name) static String findMagicComment(const String& content, const String& patternString) { + ASSERT(!content.isNull()); const char* error = nullptr; - JSC::Yarr::YarrPattern pattern(patternString, false, true, &error); + JSC::Yarr::YarrPattern pattern(patternString, JSC::RegExpFlags::FlagMultiline, &error); ASSERT(!error); BumpPointerAllocator regexAllocator; - OwnPtr<JSC::Yarr::BytecodePattern> bytecodePattern = JSC::Yarr::byteCompile(pattern, ®exAllocator); + auto bytecodePattern = JSC::Yarr::byteCompile(pattern, ®exAllocator); ASSERT(bytecodePattern); ASSERT(pattern.m_numSubpatterns == 1); @@ -196,22 +195,10 @@ static String findMagicComment(const String& content, const String& patternStrin return content.substring(matches[2], matches[3] - matches[2]); } -String findScriptSourceURL(const String& content) -{ - return findMagicComment(content, scriptCommentPattern(ASCIILiteral("sourceURL"))); -} - -String findScriptSourceMapURL(const String& content) -{ - return findMagicComment(content, scriptCommentPattern(ASCIILiteral("sourceMappingURL"))); -} - String findStylesheetSourceMapURL(const String& content) { return findMagicComment(content, stylesheetCommentPattern(ASCIILiteral("sourceMappingURL"))); } } // namespace ContentSearchUtilities -} // namespace WebCore - -#endif // ENABLE(INSPECTOR) +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ContentSearchUtilities.h b/Source/JavaScriptCore/inspector/ContentSearchUtilities.h index 3eaa06641..7c01b90da 100644 --- a/Source/JavaScriptCore/inspector/ContentSearchUtilities.h +++ b/Source/JavaScriptCore/inspector/ContentSearchUtilities.h @@ -26,12 +26,9 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ContentSearchUtilities_h -#define ContentSearchUtilities_h +#pragma once -#if ENABLE(INSPECTOR) - -#include "InspectorJSTypeBuilders.h" +#include "InspectorProtocolObjects.h" #include <wtf/Vector.h> #include <wtf/text/TextPosition.h> #include <wtf/text/WTFString.h> @@ -46,18 +43,12 @@ namespace ContentSearchUtilities { JS_EXPORT_PRIVATE JSC::Yarr::RegularExpression createSearchRegex(const String& query, bool caseSensitive, bool isRegex); JS_EXPORT_PRIVATE int countRegularExpressionMatches(const JSC::Yarr::RegularExpression&, const String&); -JS_EXPORT_PRIVATE PassRefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::GenericTypes::SearchMatch>> searchInTextByLines(const String& text, const String& query, const bool caseSensitive, const bool isRegex); +JS_EXPORT_PRIVATE Ref<Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>> searchInTextByLines(const String& text, const String& query, const bool caseSensitive, const bool isRegex); JS_EXPORT_PRIVATE TextPosition textPositionFromOffset(size_t offset, const Vector<size_t>& lineEndings); -JS_EXPORT_PRIVATE PassOwnPtr<Vector<size_t>> lineEndings(const String&); +JS_EXPORT_PRIVATE std::unique_ptr<Vector<size_t>> lineEndings(const String&); -JS_EXPORT_PRIVATE String findScriptSourceURL(const String& content); -JS_EXPORT_PRIVATE String findScriptSourceMapURL(const String& content); JS_EXPORT_PRIVATE String findStylesheetSourceMapURL(const String& content); } // namespace ContentSearchUtilities } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(ContentSearchUtilities_h) diff --git a/Source/JavaScriptCore/inspector/EventLoop.cpp b/Source/JavaScriptCore/inspector/EventLoop.cpp new file mode 100644 index 000000000..1995b1d70 --- /dev/null +++ b/Source/JavaScriptCore/inspector/EventLoop.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2011 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "EventLoop.h" + +#if OS(WINDOWS) +#include <windows.h> +#elif PLATFORM(GTK) +#include <glib.h> +#endif + +namespace Inspector { + +#if USE(CF) && !OS(WINDOWS) +CFStringRef EventLoop::remoteInspectorRunLoopMode() +{ + return CFSTR("com.apple.JavaScriptCore.remote-inspector-runloop-mode"); +} +#endif + +void EventLoop::cycle() +{ +#if OS(WINDOWS) + MSG msg; + if (!GetMessage(&msg, 0, 0, 0)) { + m_ended = true; + return; + } + TranslateMessage(&msg); + DispatchMessage(&msg); +#elif PLATFORM(WATCHOS) + // FIXME: <rdar://problem/25972777>. In order for auto-attach to work, we need to + // run in the default run loop mode otherwise we do not receive the XPC messages + // necessary to setup the relay connection and negotiate an auto-attach debugger. + CFTimeInterval timeInterval = 0.05; + CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeInterval, true); +#elif USE(CF) + // Run the RunLoop in a custom run loop mode to prevent default observers + // to run and potentially evaluate JavaScript in this context while we are + // nested. Only the debugger should control things until we continue. + // FIXME: This is not a perfect solution, as background threads are not + // paused and can still access and evalute script in the JSContext. + CFTimeInterval timeInterval = 0.05; + CFRunLoopRunInMode(remoteInspectorRunLoopMode(), timeInterval, true); +#elif PLATFORM(GTK) + g_main_context_iteration(NULL, FALSE); +#endif +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/EventLoop.h b/Source/JavaScriptCore/inspector/EventLoop.h new file mode 100644 index 000000000..1625a6b6b --- /dev/null +++ b/Source/JavaScriptCore/inspector/EventLoop.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <wtf/Noncopyable.h> + +#if USE(CF) && !OS(WINDOWS) +#include <CoreFoundation/CFRunLoop.h> +#endif + +namespace Inspector { + +class EventLoop { + WTF_MAKE_NONCOPYABLE(EventLoop); +public: + EventLoop() + : m_ended(false) + { + } + + void cycle(); + bool ended() const { return m_ended; } + +#if USE(CF) && !OS(WINDOWS) + static CFStringRef remoteInspectorRunLoopMode(); +#endif + +private: + bool m_ended; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/IdentifiersFactory.cpp b/Source/JavaScriptCore/inspector/IdentifiersFactory.cpp new file mode 100644 index 000000000..7e145be3e --- /dev/null +++ b/Source/JavaScriptCore/inspector/IdentifiersFactory.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "IdentifiersFactory.h" + +#include <wtf/text/StringBuilder.h> + +namespace Inspector { + +namespace { +static long s_lastUsedIdentifier = 0; +} + +long IdentifiersFactory::s_processId = 0; + +String IdentifiersFactory::createIdentifier() +{ + return addProcessIdPrefixTo(String::number(++s_lastUsedIdentifier)); +} + +String IdentifiersFactory::requestId(unsigned long identifier) +{ + if (identifier) + return addProcessIdPrefixTo(String::number(identifier)); + return String(); +} + +String IdentifiersFactory::addProcessIdPrefixTo(const String& id) +{ + StringBuilder builder; + builder.appendNumber(s_processId); + builder.append('.'); + builder.append(id); + return builder.toString(); +} + +} // namespace Inspector + diff --git a/Source/JavaScriptCore/inspector/IdentifiersFactory.h b/Source/JavaScriptCore/inspector/IdentifiersFactory.h new file mode 100644 index 000000000..3a3b75ab9 --- /dev/null +++ b/Source/JavaScriptCore/inspector/IdentifiersFactory.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class JS_EXPORT_PRIVATE IdentifiersFactory { +public: + static void setProcessId(long processId) { s_processId = processId; } + static String createIdentifier(); + static String requestId(unsigned long identifier); + +private: + static String addProcessIdPrefixTo(const String& id); + + static long s_processId; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InjectedScript.cpp b/Source/JavaScriptCore/inspector/InjectedScript.cpp index a02f85fb4..f7691afa4 100644 --- a/Source/JavaScriptCore/inspector/InjectedScript.cpp +++ b/Source/JavaScriptCore/inspector/InjectedScript.cpp @@ -32,14 +32,13 @@ #include "config.h" #include "InjectedScript.h" -#if ENABLE(INSPECTOR) - #include "InspectorValues.h" +#include "JSCInlines.h" #include "ScriptFunctionCall.h" #include "ScriptObject.h" #include <wtf/text/WTFString.h> -using Inspector::TypeBuilder::Array; +using Inspector::Protocol::Array; namespace Inspector { @@ -57,7 +56,7 @@ InjectedScript::~InjectedScript() { } -void InjectedScript::evaluate(ErrorString* errorString, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>* result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) +void InjectedScript::evaluate(ErrorString& errorString, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, bool saveResult, RefPtr<Inspector::Protocol::Runtime::RemoteObject>* result, Inspector::Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex) { Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("evaluate"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(expression); @@ -65,10 +64,11 @@ void InjectedScript::evaluate(ErrorString* errorString, const String& expression function.appendArgument(includeCommandLineAPI); function.appendArgument(returnByValue); function.appendArgument(generatePreview); - makeEvalCall(errorString, function, result, wasThrown); + function.appendArgument(saveResult); + makeEvalCall(errorString, function, result, wasThrown, savedResultIndex); } -void InjectedScript::callFunctionOn(ErrorString* errorString, const String& objectId, const String& expression, const String& arguments, bool returnByValue, bool generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>* result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) +void InjectedScript::callFunctionOn(ErrorString& errorString, const String& objectId, const String& expression, const String& arguments, bool returnByValue, bool generatePreview, RefPtr<Inspector::Protocol::Runtime::RemoteObject>* result, Inspector::Protocol::OptOutput<bool>* wasThrown) { Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("callFunctionOn"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(objectId); @@ -79,7 +79,7 @@ void InjectedScript::callFunctionOn(ErrorString* errorString, const String& obje makeEvalCall(errorString, function, result, wasThrown); } -void InjectedScript::evaluateOnCallFrame(ErrorString* errorString, const Deprecated::ScriptValue& callFrames, const String& callFrameId, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>* result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) +void InjectedScript::evaluateOnCallFrame(ErrorString& errorString, JSC::JSValue callFrames, const String& callFrameId, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, bool saveResult, RefPtr<Inspector::Protocol::Runtime::RemoteObject>* result, Inspector::Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex) { Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("evaluateOnCallFrame"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(callFrames); @@ -89,75 +89,147 @@ void InjectedScript::evaluateOnCallFrame(ErrorString* errorString, const Depreca function.appendArgument(includeCommandLineAPI); function.appendArgument(returnByValue); function.appendArgument(generatePreview); - makeEvalCall(errorString, function, result, wasThrown); + function.appendArgument(saveResult); + makeEvalCall(errorString, function, result, wasThrown, savedResultIndex); } -void InjectedScript::getFunctionDetails(ErrorString* errorString, const String& functionId, RefPtr<Inspector::TypeBuilder::Debugger::FunctionDetails>* result) +void InjectedScript::getFunctionDetails(ErrorString& errorString, const String& functionId, RefPtr<Inspector::Protocol::Debugger::FunctionDetails>* result) { Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("getFunctionDetails"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(functionId); RefPtr<InspectorValue> resultValue; makeCall(function, &resultValue); - if (!resultValue || resultValue->type() != InspectorValue::TypeObject) { + if (!resultValue || resultValue->type() != InspectorValue::Type::Object) { if (!resultValue->asString(errorString)) - *errorString = ASCIILiteral("Internal error"); + errorString = ASCIILiteral("Internal error"); return; } - *result = Inspector::TypeBuilder::Debugger::FunctionDetails::runtimeCast(resultValue); + *result = BindingTraits<Inspector::Protocol::Debugger::FunctionDetails>::runtimeCast(WTFMove(resultValue)); } -void InjectedScript::getProperties(ErrorString* errorString, const String& objectId, bool ownProperties, RefPtr<Array<Inspector::TypeBuilder::Runtime::PropertyDescriptor>>* properties) +void InjectedScript::functionDetails(ErrorString& errorString, JSC::JSValue value, RefPtr<Protocol::Debugger::FunctionDetails>* result) +{ + Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("functionDetails"), inspectorEnvironment()->functionCallHandler()); + function.appendArgument(value); + function.appendArgument(true); // Preview only. + + RefPtr<InspectorValue> resultValue; + makeCall(function, &resultValue); + if (!resultValue || resultValue->type() != InspectorValue::Type::Object) { + if (!resultValue->asString(errorString)) + errorString = ASCIILiteral("Internal error"); + return; + } + + *result = BindingTraits<Inspector::Protocol::Debugger::FunctionDetails>::runtimeCast(WTFMove(resultValue)); +} + +void InjectedScript::getProperties(ErrorString& errorString, const String& objectId, bool ownProperties, bool generatePreview, RefPtr<Array<Inspector::Protocol::Runtime::PropertyDescriptor>>* properties) { Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("getProperties"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(objectId); function.appendArgument(ownProperties); + function.appendArgument(generatePreview); RefPtr<InspectorValue> result; makeCall(function, &result); - if (!result || result->type() != InspectorValue::TypeArray) { - *errorString = ASCIILiteral("Internal error"); + if (!result || result->type() != InspectorValue::Type::Array) { + errorString = ASCIILiteral("Internal error"); return; } - *properties = Array<Inspector::TypeBuilder::Runtime::PropertyDescriptor>::runtimeCast(result); + *properties = BindingTraits<Array<Inspector::Protocol::Runtime::PropertyDescriptor>>::runtimeCast(WTFMove(result)); } -void InjectedScript::getInternalProperties(ErrorString* errorString, const String& objectId, RefPtr<Array<Inspector::TypeBuilder::Runtime::InternalPropertyDescriptor>>* properties) +void InjectedScript::getDisplayableProperties(ErrorString& errorString, const String& objectId, bool generatePreview, RefPtr<Array<Inspector::Protocol::Runtime::PropertyDescriptor>>* properties) +{ + Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("getDisplayableProperties"), inspectorEnvironment()->functionCallHandler()); + function.appendArgument(objectId); + function.appendArgument(generatePreview); + + RefPtr<InspectorValue> result; + makeCall(function, &result); + if (!result || result->type() != InspectorValue::Type::Array) { + errorString = ASCIILiteral("Internal error"); + return; + } + + *properties = BindingTraits<Array<Inspector::Protocol::Runtime::PropertyDescriptor>>::runtimeCast(WTFMove(result)); +} + +void InjectedScript::getInternalProperties(ErrorString& errorString, const String& objectId, bool generatePreview, RefPtr<Array<Inspector::Protocol::Runtime::InternalPropertyDescriptor>>* properties) { Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("getInternalProperties"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(objectId); + function.appendArgument(generatePreview); RefPtr<InspectorValue> result; makeCall(function, &result); - if (!result || result->type() != InspectorValue::TypeArray) { - *errorString = ASCIILiteral("Internal error"); + if (!result || result->type() != InspectorValue::Type::Array) { + errorString = ASCIILiteral("Internal error"); return; } - RefPtr<Array<Inspector::TypeBuilder::Runtime::InternalPropertyDescriptor>> array = Array<Inspector::TypeBuilder::Runtime::InternalPropertyDescriptor>::runtimeCast(result); - if (array->length() > 0) - *properties = array; + auto array = BindingTraits<Array<Inspector::Protocol::Runtime::InternalPropertyDescriptor>>::runtimeCast(WTFMove(result)); + *properties = array->length() > 0 ? array : nullptr; } -PassRefPtr<Array<Inspector::TypeBuilder::Debugger::CallFrame>> InjectedScript::wrapCallFrames(const Deprecated::ScriptValue& callFrames) +void InjectedScript::getCollectionEntries(ErrorString& errorString, const String& objectId, const String& objectGroup, int startIndex, int numberToFetch, RefPtr<Protocol::Array<Protocol::Runtime::CollectionEntry>>* entries) +{ + Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("getCollectionEntries"), inspectorEnvironment()->functionCallHandler()); + function.appendArgument(objectId); + function.appendArgument(objectGroup); + function.appendArgument(startIndex); + function.appendArgument(numberToFetch); + + RefPtr<InspectorValue> result; + makeCall(function, &result); + if (!result || result->type() != InspectorValue::Type::Array) { + errorString = ASCIILiteral("Internal error"); + return; + } + + *entries = BindingTraits<Array<Protocol::Runtime::CollectionEntry>>::runtimeCast(WTFMove(result)); +} + +void InjectedScript::saveResult(ErrorString& errorString, const String& callArgumentJSON, Inspector::Protocol::OptOutput<int>* savedResultIndex) +{ + Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("saveResult"), inspectorEnvironment()->functionCallHandler()); + function.appendArgument(callArgumentJSON); + + RefPtr<InspectorValue> result; + makeCall(function, &result); + if (!result || result->type() != InspectorValue::Type::Integer) { + errorString = ASCIILiteral("Internal error"); + return; + } + + int savedResultIndexInt = 0; + if (result->asInteger(savedResultIndexInt) && savedResultIndexInt > 0) + *savedResultIndex = savedResultIndexInt; +} + +Ref<Array<Inspector::Protocol::Debugger::CallFrame>> InjectedScript::wrapCallFrames(JSC::JSValue callFrames) const { ASSERT(!hasNoValue()); Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("wrapCallFrames"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(callFrames); bool hadException = false; - Deprecated::ScriptValue callFramesValue = callFunctionWithEvalEnabled(function, hadException); + auto callFramesValue = callFunctionWithEvalEnabled(function, hadException); + if (!callFramesValue) + return Array<Inspector::Protocol::Debugger::CallFrame>::create(); ASSERT(!hadException); - RefPtr<InspectorValue> result = callFramesValue.toInspectorValue(scriptState()); - if (result->type() == InspectorValue::TypeArray) - return Array<Inspector::TypeBuilder::Debugger::CallFrame>::runtimeCast(result); + RefPtr<InspectorValue> result = toInspectorValue(*scriptState(), callFramesValue); + if (result->type() == InspectorValue::Type::Array) + return BindingTraits<Array<Inspector::Protocol::Debugger::CallFrame>>::runtimeCast(WTFMove(result)).releaseNonNull(); - return Array<Inspector::TypeBuilder::Debugger::CallFrame>::create(); + return Array<Inspector::Protocol::Debugger::CallFrame>::create(); } -PassRefPtr<Inspector::TypeBuilder::Runtime::RemoteObject> InjectedScript::wrapObject(const Deprecated::ScriptValue& value, const String& groupName, bool generatePreview) const +RefPtr<Inspector::Protocol::Runtime::RemoteObject> InjectedScript::wrapObject(JSC::JSValue value, const String& groupName, bool generatePreview) const { ASSERT(!hasNoValue()); Deprecated::ScriptFunctionCall wrapFunction(injectedScriptObject(), ASCIILiteral("wrapObject"), inspectorEnvironment()->functionCallHandler()); @@ -167,48 +239,89 @@ PassRefPtr<Inspector::TypeBuilder::Runtime::RemoteObject> InjectedScript::wrapOb wrapFunction.appendArgument(generatePreview); bool hadException = false; - Deprecated::ScriptValue r = callFunctionWithEvalEnabled(wrapFunction, hadException); + auto r = callFunctionWithEvalEnabled(wrapFunction, hadException); if (hadException) return nullptr; - RefPtr<InspectorObject> rawResult = r.toInspectorValue(scriptState())->asObject(); - return Inspector::TypeBuilder::Runtime::RemoteObject::runtimeCast(rawResult); + RefPtr<InspectorObject> resultObject; + bool castSucceeded = toInspectorValue(*scriptState(), r)->asObject(resultObject); + ASSERT_UNUSED(castSucceeded, castSucceeded); + + return BindingTraits<Inspector::Protocol::Runtime::RemoteObject>::runtimeCast(resultObject); } -PassRefPtr<Inspector::TypeBuilder::Runtime::RemoteObject> InjectedScript::wrapTable(const Deprecated::ScriptValue& table, const Deprecated::ScriptValue& columns) const +RefPtr<Inspector::Protocol::Runtime::RemoteObject> InjectedScript::wrapTable(JSC::JSValue table, JSC::JSValue columns) const { ASSERT(!hasNoValue()); Deprecated::ScriptFunctionCall wrapFunction(injectedScriptObject(), ASCIILiteral("wrapTable"), inspectorEnvironment()->functionCallHandler()); wrapFunction.appendArgument(hasAccessToInspectedScriptState()); wrapFunction.appendArgument(table); - if (columns.hasNoValue()) + if (!columns) wrapFunction.appendArgument(false); else wrapFunction.appendArgument(columns); bool hadException = false; - Deprecated::ScriptValue r = callFunctionWithEvalEnabled(wrapFunction, hadException); + auto r = callFunctionWithEvalEnabled(wrapFunction, hadException); + if (hadException) + return nullptr; + + RefPtr<InspectorObject> resultObject; + bool castSucceeded = toInspectorValue(*scriptState(), r)->asObject(resultObject); + ASSERT_UNUSED(castSucceeded, castSucceeded); + + return BindingTraits<Inspector::Protocol::Runtime::RemoteObject>::runtimeCast(resultObject); +} + +RefPtr<Inspector::Protocol::Runtime::ObjectPreview> InjectedScript::previewValue(JSC::JSValue value) const +{ + ASSERT(!hasNoValue()); + Deprecated::ScriptFunctionCall wrapFunction(injectedScriptObject(), ASCIILiteral("previewValue"), inspectorEnvironment()->functionCallHandler()); + wrapFunction.appendArgument(value); + + bool hadException = false; + auto r = callFunctionWithEvalEnabled(wrapFunction, hadException); if (hadException) return nullptr; - RefPtr<InspectorObject> rawResult = r.toInspectorValue(scriptState())->asObject(); - return Inspector::TypeBuilder::Runtime::RemoteObject::runtimeCast(rawResult); + RefPtr<InspectorObject> resultObject; + bool castSucceeded = toInspectorValue(*scriptState(), r)->asObject(resultObject); + ASSERT_UNUSED(castSucceeded, castSucceeded); + + return BindingTraits<Inspector::Protocol::Runtime::ObjectPreview>::runtimeCast(resultObject); +} + +void InjectedScript::setExceptionValue(JSC::JSValue value) +{ + ASSERT(!hasNoValue()); + Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("setExceptionValue"), inspectorEnvironment()->functionCallHandler()); + function.appendArgument(value); + RefPtr<InspectorValue> result; + makeCall(function, &result); +} + +void InjectedScript::clearExceptionValue() +{ + ASSERT(!hasNoValue()); + Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("clearExceptionValue"), inspectorEnvironment()->functionCallHandler()); + RefPtr<InspectorValue> result; + makeCall(function, &result); } -Deprecated::ScriptValue InjectedScript::findObjectById(const String& objectId) const +JSC::JSValue InjectedScript::findObjectById(const String& objectId) const { ASSERT(!hasNoValue()); Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("findObjectById"), inspectorEnvironment()->functionCallHandler()); function.appendArgument(objectId); bool hadException = false; - Deprecated::ScriptValue resultValue = callFunctionWithEvalEnabled(function, hadException); + auto resultValue = callFunctionWithEvalEnabled(function, hadException); ASSERT(!hadException); return resultValue; } -void InjectedScript::inspectObject(Deprecated::ScriptValue value) +void InjectedScript::inspectObject(JSC::JSValue value) { ASSERT(!hasNoValue()); Deprecated::ScriptFunctionCall function(injectedScriptObject(), ASCIILiteral("inspectObject"), inspectorEnvironment()->functionCallHandler()); @@ -238,4 +351,3 @@ void InjectedScript::releaseObjectGroup(const String& objectGroup) } // namespace Inspector -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/InjectedScript.h b/Source/JavaScriptCore/inspector/InjectedScript.h index 4c58b19e5..4d227114e 100644 --- a/Source/JavaScriptCore/inspector/InjectedScript.h +++ b/Source/JavaScriptCore/inspector/InjectedScript.h @@ -29,16 +29,11 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InjectedScript_h -#define InjectedScript_h - -#if ENABLE(INSPECTOR) +#pragma once #include "InjectedScriptBase.h" -#include "InspectorJSTypeBuilders.h" #include <wtf/Forward.h> #include <wtf/Noncopyable.h> -#include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> namespace Deprecated { @@ -56,19 +51,27 @@ public: InjectedScript(Deprecated::ScriptObject, InspectorEnvironment*); virtual ~InjectedScript(); - void evaluate(ErrorString*, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>* result, TypeBuilder::OptOutput<bool>* wasThrown); - void callFunctionOn(ErrorString*, const String& objectId, const String& expression, const String& arguments, bool returnByValue, bool generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>* result, TypeBuilder::OptOutput<bool>* wasThrown); - void evaluateOnCallFrame(ErrorString*, const Deprecated::ScriptValue& callFrames, const String& callFrameId, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>* result, TypeBuilder::OptOutput<bool>* wasThrown); - void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>* result); - void getProperties(ErrorString*, const String& objectId, bool ownProperties, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::PropertyDescriptor>>* result); - void getInternalProperties(ErrorString*, const String& objectId, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::InternalPropertyDescriptor>>* result); + void evaluate(ErrorString&, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, bool saveResult, RefPtr<Protocol::Runtime::RemoteObject>* result, Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex); + void callFunctionOn(ErrorString&, const String& objectId, const String& expression, const String& arguments, bool returnByValue, bool generatePreview, RefPtr<Protocol::Runtime::RemoteObject>* result, Protocol::OptOutput<bool>* wasThrown); + void evaluateOnCallFrame(ErrorString&, JSC::JSValue callFrames, const String& callFrameId, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, bool saveResult, RefPtr<Protocol::Runtime::RemoteObject>* result, Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex); + void getFunctionDetails(ErrorString&, const String& functionId, RefPtr<Protocol::Debugger::FunctionDetails>* result); + void functionDetails(ErrorString&, JSC::JSValue, RefPtr<Protocol::Debugger::FunctionDetails>* result); + void getProperties(ErrorString&, const String& objectId, bool ownProperties, bool generatePreview, RefPtr<Protocol::Array<Protocol::Runtime::PropertyDescriptor>>* result); + void getDisplayableProperties(ErrorString&, const String& objectId, bool generatePreview, RefPtr<Protocol::Array<Protocol::Runtime::PropertyDescriptor>>* result); + void getInternalProperties(ErrorString&, const String& objectId, bool generatePreview, RefPtr<Protocol::Array<Protocol::Runtime::InternalPropertyDescriptor>>* result); + void getCollectionEntries(ErrorString&, const String& objectId, const String& objectGroup, int startIndex, int numberToFetch, RefPtr<Protocol::Array<Protocol::Runtime::CollectionEntry>>* entries); + void saveResult(ErrorString&, const String& callArgumentJSON, Inspector::Protocol::OptOutput<int>* savedResultIndex); + + Ref<Protocol::Array<Protocol::Debugger::CallFrame>> wrapCallFrames(JSC::JSValue) const; + RefPtr<Protocol::Runtime::RemoteObject> wrapObject(JSC::JSValue, const String& groupName, bool generatePreview = false) const; + RefPtr<Protocol::Runtime::RemoteObject> wrapTable(JSC::JSValue table, JSC::JSValue columns) const; + RefPtr<Protocol::Runtime::ObjectPreview> previewValue(JSC::JSValue) const; - PassRefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame>> wrapCallFrames(const Deprecated::ScriptValue&); - PassRefPtr<TypeBuilder::Runtime::RemoteObject> wrapObject(const Deprecated::ScriptValue&, const String& groupName, bool generatePreview = false) const; - PassRefPtr<TypeBuilder::Runtime::RemoteObject> wrapTable(const Deprecated::ScriptValue& table, const Deprecated::ScriptValue& columns) const; + void setExceptionValue(JSC::JSValue); + void clearExceptionValue(); - Deprecated::ScriptValue findObjectById(const String& objectId) const; - void inspectObject(Deprecated::ScriptValue); + JSC::JSValue findObjectById(const String& objectId) const; + void inspectObject(JSC::JSValue); void releaseObject(const String& objectId); void releaseObjectGroup(const String& objectGroup); @@ -77,7 +80,3 @@ private: }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // InjectedScript_h diff --git a/Source/JavaScriptCore/inspector/InjectedScriptBase.cpp b/Source/JavaScriptCore/inspector/InjectedScriptBase.cpp index c2a494728..9caa4eb93 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptBase.cpp +++ b/Source/JavaScriptCore/inspector/InjectedScriptBase.cpp @@ -32,9 +32,9 @@ #include "config.h" #include "InjectedScriptBase.h" -#if ENABLE(INSPECTOR) - +#include "DebuggerEvalEnabler.h" #include "InspectorValues.h" +#include "JSCInlines.h" #include "JSGlobalObject.h" #include "ScriptFunctionCall.h" #include <wtf/text/WTFString.h> @@ -58,12 +58,6 @@ InjectedScriptBase::~InjectedScriptBase() { } -void InjectedScriptBase::initialize(Deprecated::ScriptObject injectedScriptObject, InspectorEnvironment* environment) -{ - m_injectedScriptObject = injectedScriptObject; - m_environment = environment; -} - bool InjectedScriptBase::hasAccessToInspectedScriptState() const { return m_environment && m_environment->canAccessInspectedScriptState(m_injectedScriptObject.scriptState()); @@ -74,29 +68,11 @@ const Deprecated::ScriptObject& InjectedScriptBase::injectedScriptObject() const return m_injectedScriptObject; } -Deprecated::ScriptValue InjectedScriptBase::callFunctionWithEvalEnabled(Deprecated::ScriptFunctionCall& function, bool& hadException) const +JSC::JSValue InjectedScriptBase::callFunctionWithEvalEnabled(Deprecated::ScriptFunctionCall& function, bool& hadException) const { - if (m_environment) - m_environment->willCallInjectedScriptFunction(m_injectedScriptObject.scriptState(), name(), 1); - JSC::ExecState* scriptState = m_injectedScriptObject.scriptState(); - bool evalIsDisabled = false; - if (scriptState) { - evalIsDisabled = !scriptState->lexicalGlobalObject()->evalEnabled(); - // Temporarily enable allow evals for inspector. - if (evalIsDisabled) - scriptState->lexicalGlobalObject()->setEvalEnabled(true); - } - - Deprecated::ScriptValue resultValue = function.call(hadException); - - if (evalIsDisabled) - scriptState->lexicalGlobalObject()->setEvalEnabled(false); - - if (m_environment) - m_environment->didCallInjectedScriptFunction(); - - return resultValue; + JSC::DebuggerEvalEnabler evalEnabler(scriptState); + return function.call(hadException); } void InjectedScriptBase::makeCall(Deprecated::ScriptFunctionCall& function, RefPtr<InspectorValue>* result) @@ -107,49 +83,59 @@ void InjectedScriptBase::makeCall(Deprecated::ScriptFunctionCall& function, RefP } bool hadException = false; - Deprecated::ScriptValue resultValue = callFunctionWithEvalEnabled(function, hadException); + auto resultValue = callFunctionWithEvalEnabled(function, hadException); ASSERT(!hadException); if (!hadException) { - *result = resultValue.toInspectorValue(m_injectedScriptObject.scriptState()); + *result = toInspectorValue(*m_injectedScriptObject.scriptState(), resultValue); if (!*result) - *result = InspectorString::create(String::format("Object has too long reference chain (must not be longer than %d)", InspectorValue::maxDepth)); + *result = InspectorValue::create(String::format("Object has too long reference chain (must not be longer than %d)", InspectorValue::maxDepth)); } else - *result = InspectorString::create("Exception while making a call."); + *result = InspectorValue::create("Exception while making a call."); } -void InjectedScriptBase::makeEvalCall(ErrorString* errorString, Deprecated::ScriptFunctionCall& function, RefPtr<TypeBuilder::Runtime::RemoteObject>* objectResult, TypeBuilder::OptOutput<bool>* wasThrown) +void InjectedScriptBase::makeEvalCall(ErrorString& errorString, Deprecated::ScriptFunctionCall& function, RefPtr<Protocol::Runtime::RemoteObject>* objectResult, Protocol::OptOutput<bool>* wasThrown, Protocol::OptOutput<int>* savedResultIndex) { RefPtr<InspectorValue> result; makeCall(function, &result); if (!result) { - *errorString = ASCIILiteral("Internal error: result value is empty"); + errorString = ASCIILiteral("Internal error: result value is empty"); return; } - if (result->type() == InspectorValue::TypeString) { + if (result->type() == InspectorValue::Type::String) { result->asString(errorString); - ASSERT(errorString->length()); + ASSERT(errorString.length()); return; } - RefPtr<InspectorObject> resultPair = result->asObject(); - if (!resultPair) { - *errorString = ASCIILiteral("Internal error: result is not an Object"); + RefPtr<InspectorObject> resultTuple; + if (!result->asObject(resultTuple)) { + errorString = ASCIILiteral("Internal error: result is not an Object"); return; } - RefPtr<InspectorObject> resultObj = resultPair->getObject(ASCIILiteral("result")); - bool wasThrownVal = false; - if (!resultObj || !resultPair->getBoolean(ASCIILiteral("wasThrown"), &wasThrownVal)) { - *errorString = ASCIILiteral("Internal error: result is not a pair of value and wasThrown flag"); + RefPtr<InspectorObject> resultObject; + if (!resultTuple->getObject(ASCIILiteral("result"), resultObject)) { + errorString = ASCIILiteral("Internal error: result is not a pair of value and wasThrown flag"); return; } - *objectResult = TypeBuilder::Runtime::RemoteObject::runtimeCast(resultObj); - *wasThrown = wasThrownVal; + bool wasThrownValue = false; + if (!resultTuple->getBoolean(ASCIILiteral("wasThrown"), wasThrownValue)) { + errorString = ASCIILiteral("Internal error: result is not a pair of value and wasThrown flag"); + return; + } + + *objectResult = BindingTraits<Protocol::Runtime::RemoteObject>::runtimeCast(resultObject); + *wasThrown = wasThrownValue; + + if (savedResultIndex) { + int savedIndex = 0; + if (resultTuple->getInteger(ASCIILiteral("savedResultIndex"), savedIndex)) + *savedResultIndex = savedIndex; + } } } // namespace Inspector -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/InjectedScriptBase.h b/Source/JavaScriptCore/inspector/InjectedScriptBase.h index 034e0c20a..55dd0e57d 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptBase.h +++ b/Source/JavaScriptCore/inspector/InjectedScriptBase.h @@ -29,13 +29,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InjectedScriptBase_h -#define InjectedScriptBase_h - -#if ENABLE(INSPECTOR) +#pragma once #include "InspectorEnvironment.h" -#include "InspectorJSTypeBuilders.h" +#include "InspectorProtocolObjects.h" #include "bindings/ScriptObject.h" #include <wtf/Forward.h> #include <wtf/RefPtr.h> @@ -62,13 +59,12 @@ protected: InspectorEnvironment* inspectorEnvironment() const { return m_environment; } - void initialize(Deprecated::ScriptObject, InspectorEnvironment*); bool hasAccessToInspectedScriptState() const; const Deprecated::ScriptObject& injectedScriptObject() const; - Deprecated::ScriptValue callFunctionWithEvalEnabled(Deprecated::ScriptFunctionCall&, bool& hadException) const; + JSC::JSValue callFunctionWithEvalEnabled(Deprecated::ScriptFunctionCall&, bool& hadException) const; void makeCall(Deprecated::ScriptFunctionCall&, RefPtr<InspectorValue>* result); - void makeEvalCall(ErrorString*, Deprecated::ScriptFunctionCall&, RefPtr<TypeBuilder::Runtime::RemoteObject>* result, TypeBuilder::OptOutput<bool>* wasThrown); + void makeEvalCall(ErrorString&, Deprecated::ScriptFunctionCall&, RefPtr<Protocol::Runtime::RemoteObject>* result, Protocol::OptOutput<bool>* wasThrown, Protocol::OptOutput<int>* savedResult = nullptr); private: String m_name; @@ -77,7 +73,3 @@ private: }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // InjectedScriptBase_h diff --git a/Source/JavaScriptCore/inspector/InjectedScriptHost.cpp b/Source/JavaScriptCore/inspector/InjectedScriptHost.cpp index 46b3c4e37..433174ff9 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptHost.cpp +++ b/Source/JavaScriptCore/inspector/InjectedScriptHost.cpp @@ -26,8 +26,7 @@ #include "config.h" #include "InjectedScriptHost.h" -#if ENABLE(INSPECTOR) - +#include "JSCInlines.h" #include "JSInjectedScriptHost.h" using namespace JSC; @@ -38,46 +37,23 @@ InjectedScriptHost::~InjectedScriptHost() { } -JSValue InjectedScriptHost::jsWrapper(ExecState* exec, JSGlobalObject* globalObject) +JSValue InjectedScriptHost::wrapper(ExecState* exec, JSGlobalObject* globalObject) { - auto key = std::make_pair(exec, globalObject); - auto it = m_wrappers.find(key); - if (it != m_wrappers.end()) - return it->value.get(); - - JSValue jsValue = toJS(exec, globalObject, this); - if (!jsValue.isObject()) - return jsValue; - - JSObject* jsObject = jsValue.toObject(exec, globalObject); - Strong<JSObject> wrapper(exec->vm(), jsObject); - m_wrappers.add(key, wrapper); - - return jsValue; -} + JSValue value = m_wrappers.getWrapper(globalObject); + if (value) + return value; -static void clearWrapperFromValue(JSValue value) -{ - JSInjectedScriptHost* jsInjectedScriptHost = toJSInjectedScriptHost(value); - ASSERT(jsInjectedScriptHost); - if (jsInjectedScriptHost) - jsInjectedScriptHost->releaseImpl(); -} + JSObject* prototype = JSInjectedScriptHost::createPrototype(exec->vm(), globalObject); + Structure* structure = JSInjectedScriptHost::createStructure(exec->vm(), globalObject, prototype); + JSInjectedScriptHost* injectedScriptHost = JSInjectedScriptHost::create(exec->vm(), structure, makeRef(*this)); + m_wrappers.addWrapper(globalObject, injectedScriptHost); -void InjectedScriptHost::clearWrapper(ExecState* exec, JSGlobalObject* globalObject) -{ - auto key = std::make_pair(exec, globalObject); - clearWrapperFromValue(m_wrappers.take(key).get()); + return injectedScriptHost; } void InjectedScriptHost::clearAllWrappers() { - for (auto wrapper : m_wrappers) - clearWrapperFromValue(wrapper.value.get()); - - m_wrappers.clear(); + m_wrappers.clearAllWrappers(); } } // namespace Inspector - -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/InjectedScriptHost.h b/Source/JavaScriptCore/inspector/InjectedScriptHost.h index db93f8631..d58d97d59 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptHost.h +++ b/Source/JavaScriptCore/inspector/InjectedScriptHost.h @@ -23,14 +23,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InjectedScriptHost_h -#define InjectedScriptHost_h - -#if ENABLE(INSPECTOR) +#pragma once #include "JSCJSValueInlines.h" -#include "Strong.h" -#include "StrongInlines.h" +#include "inspector/PerGlobalObjectWrapperWorld.h" #include <wtf/HashMap.h> #include <wtf/RefCounted.h> @@ -38,22 +34,17 @@ namespace Inspector { class JS_EXPORT_PRIVATE InjectedScriptHost : public RefCounted<InjectedScriptHost> { public: - static PassRefPtr<InjectedScriptHost> create() { return adoptRef(new InjectedScriptHost); } + static Ref<InjectedScriptHost> create() { return adoptRef(*new InjectedScriptHost); } virtual ~InjectedScriptHost(); - virtual JSC::JSValue type(JSC::ExecState*, JSC::JSValue) { return JSC::jsUndefined(); } - virtual bool isHTMLAllCollection(JSC::JSValue) { return false; } + virtual JSC::JSValue subtype(JSC::ExecState*, JSC::JSValue) { return JSC::jsUndefined(); } + virtual bool isHTMLAllCollection(JSC::VM&, JSC::JSValue) { return false; } - JSC::JSValue jsWrapper(JSC::ExecState*, JSC::JSGlobalObject*); - void clearWrapper(JSC::ExecState*, JSC::JSGlobalObject*); + JSC::JSValue wrapper(JSC::ExecState*, JSC::JSGlobalObject*); void clearAllWrappers(); private: - HashMap<std::pair<JSC::ExecState*, JSC::JSGlobalObject*>, JSC::Strong<JSC::JSObject>> m_wrappers; + PerGlobalObjectWrapperWorld m_wrappers; }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(InjectedScriptHost_h) diff --git a/Source/JavaScriptCore/inspector/InjectedScriptManager.cpp b/Source/JavaScriptCore/inspector/InjectedScriptManager.cpp index 72d20df3e..097615b10 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptManager.cpp +++ b/Source/JavaScriptCore/inspector/InjectedScriptManager.cpp @@ -12,7 +12,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -31,12 +31,11 @@ #include "config.h" #include "InjectedScriptManager.h" -#if ENABLE(INSPECTOR) - #include "Completion.h" #include "InjectedScriptHost.h" #include "InjectedScriptSource.h" #include "InspectorValues.h" +#include "JSCInlines.h" #include "JSInjectedScriptHost.h" #include "JSLock.h" #include "ScriptObject.h" @@ -46,9 +45,9 @@ using namespace JSC; namespace Inspector { -InjectedScriptManager::InjectedScriptManager(InspectorEnvironment& environment, PassRefPtr<InjectedScriptHost> injectedScriptHost) +InjectedScriptManager::InjectedScriptManager(InspectorEnvironment& environment, Ref<InjectedScriptHost>&& injectedScriptHost) : m_environment(environment) - , m_injectedScriptHost(injectedScriptHost) + , m_injectedScriptHost(WTFMove(injectedScriptHost)) , m_nextInjectedScriptId(1) { } @@ -60,10 +59,16 @@ InjectedScriptManager::~InjectedScriptManager() void InjectedScriptManager::disconnect() { discardInjectedScripts(); - m_injectedScriptHost = nullptr; } -InjectedScriptHost* InjectedScriptManager::injectedScriptHost() +void InjectedScriptManager::discardInjectedScripts() +{ + m_injectedScriptHost->clearAllWrappers(); + m_idToInjectedScript.clear(); + m_scriptStateToId.clear(); +} + +InjectedScriptHost& InjectedScriptManager::injectedScriptHost() { return m_injectedScriptHost.get(); } @@ -95,64 +100,67 @@ int InjectedScriptManager::injectedScriptIdFor(ExecState* scriptState) InjectedScript InjectedScriptManager::injectedScriptForObjectId(const String& objectId) { - RefPtr<InspectorValue> parsedObjectId = InspectorValue::parseJSON(objectId); - if (parsedObjectId && parsedObjectId->type() == InspectorValue::TypeObject) { - long injectedScriptId = 0; - bool success = parsedObjectId->asObject()->getNumber(ASCIILiteral("injectedScriptId"), &injectedScriptId); - if (success) - return m_idToInjectedScript.get(injectedScriptId); - } + RefPtr<InspectorValue> parsedObjectId; + if (!InspectorValue::parseJSON(objectId, parsedObjectId)) + return InjectedScript(); - return InjectedScript(); + RefPtr<InspectorObject> resultObject; + if (!parsedObjectId->asObject(resultObject)) + return InjectedScript(); + + long injectedScriptId = 0; + if (!resultObject->getInteger(ASCIILiteral("injectedScriptId"), injectedScriptId)) + return InjectedScript(); + + return m_idToInjectedScript.get(injectedScriptId); } -void InjectedScriptManager::discardInjectedScripts() +void InjectedScriptManager::releaseObjectGroup(const String& objectGroup) { - m_injectedScriptHost->clearAllWrappers(); - m_idToInjectedScript.clear(); - m_scriptStateToId.clear(); + for (auto& injectedScript : m_idToInjectedScript.values()) + injectedScript.releaseObjectGroup(objectGroup); } -void InjectedScriptManager::releaseObjectGroup(const String& objectGroup) +void InjectedScriptManager::clearExceptionValue() { - for (auto it = m_idToInjectedScript.begin(); it != m_idToInjectedScript.end(); ++it) - it->value.releaseObjectGroup(objectGroup); + for (auto& injectedScript : m_idToInjectedScript.values()) + injectedScript.clearExceptionValue(); } String InjectedScriptManager::injectedScriptSource() { - return String(reinterpret_cast<const char*>(InjectedScriptSource_js), sizeof(InjectedScriptSource_js)); + return StringImpl::createWithoutCopying(InjectedScriptSource_js, sizeof(InjectedScriptSource_js)); } -Deprecated::ScriptObject InjectedScriptManager::createInjectedScript(const String& source, ExecState* scriptState, int id) +JSC::JSObject* InjectedScriptManager::createInjectedScript(const String& source, ExecState* scriptState, int id) { - JSLockHolder lock(scriptState); + VM& vm = scriptState->vm(); + JSLockHolder lock(vm); + auto scope = DECLARE_CATCH_SCOPE(vm); - SourceCode sourceCode = makeSource(source); + SourceCode sourceCode = makeSource(source, { }); JSGlobalObject* globalObject = scriptState->lexicalGlobalObject(); JSValue globalThisValue = scriptState->globalThisValue(); - JSValue evaluationException; + NakedPtr<Exception> evaluationException; InspectorEvaluateHandler evaluateHandler = m_environment.evaluateHandler(); - JSValue functionValue = evaluateHandler(scriptState, sourceCode, globalThisValue, &evaluationException); + JSValue functionValue = evaluateHandler(scriptState, sourceCode, globalThisValue, evaluationException); if (evaluationException) - return Deprecated::ScriptObject(); + return nullptr; CallData callData; CallType callType = getCallData(functionValue, callData); - if (callType == CallTypeNone) - return Deprecated::ScriptObject(); + if (callType == CallType::None) + return nullptr; MarkedArgumentBuffer args; - args.append(m_injectedScriptHost->jsWrapper(scriptState, globalObject)); + args.append(m_injectedScriptHost->wrapper(scriptState, globalObject)); args.append(globalThisValue); args.append(jsNumber(id)); JSValue result = JSC::call(scriptState, functionValue, callType, callData, globalThisValue, args); - if (result.isObject()) - return Deprecated::ScriptObject(scriptState, result.getObject()); - - return Deprecated::ScriptObject(); + scope.clearException(); + return result.getObject(); } InjectedScript InjectedScriptManager::injectedScriptFor(ExecState* inspectedExecState) @@ -168,18 +176,23 @@ InjectedScript InjectedScriptManager::injectedScriptFor(ExecState* inspectedExec return InjectedScript(); int id = injectedScriptIdFor(inspectedExecState); - Deprecated::ScriptObject injectedScriptObject = createInjectedScript(injectedScriptSource(), inspectedExecState, id); - InjectedScript result(injectedScriptObject, &m_environment); + auto injectedScriptObject = createInjectedScript(injectedScriptSource(), inspectedExecState, id); + if (!injectedScriptObject) { + WTFLogAlways("Failed to parse/execute InjectedScriptSource.js!"); + WTFLogAlways("%s\n", injectedScriptSource().ascii().data()); + RELEASE_ASSERT_NOT_REACHED(); + } + + InjectedScript result({ inspectedExecState, injectedScriptObject }, &m_environment); m_idToInjectedScript.set(id, result); didCreateInjectedScript(result); return result; } -void InjectedScriptManager::didCreateInjectedScript(InjectedScript) +void InjectedScriptManager::didCreateInjectedScript(const InjectedScript&) { // Intentionally empty. This allows for subclasses to inject additional scripts. } } // namespace Inspector -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/InjectedScriptManager.h b/Source/JavaScriptCore/inspector/InjectedScriptManager.h index bcc64e2a4..8475e42f7 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptManager.h +++ b/Source/JavaScriptCore/inspector/InjectedScriptManager.h @@ -11,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -27,8 +27,7 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InjectedScriptManager_h -#define InjectedScriptManager_h +#pragma once #include "InjectedScript.h" #include "InjectedScriptHost.h" @@ -50,36 +49,35 @@ namespace Inspector { class JS_EXPORT_PRIVATE InjectedScriptManager { WTF_MAKE_NONCOPYABLE(InjectedScriptManager); WTF_MAKE_FAST_ALLOCATED; public: - InjectedScriptManager(InspectorEnvironment&, PassRefPtr<InjectedScriptHost>); + InjectedScriptManager(InspectorEnvironment&, Ref<InjectedScriptHost>&&); virtual ~InjectedScriptManager(); virtual void disconnect(); + virtual void discardInjectedScripts(); - InjectedScriptHost* injectedScriptHost(); + InjectedScriptHost& injectedScriptHost(); InspectorEnvironment& inspectorEnvironment() const { return m_environment; } InjectedScript injectedScriptFor(JSC::ExecState*); InjectedScript injectedScriptForId(int); int injectedScriptIdFor(JSC::ExecState*); InjectedScript injectedScriptForObjectId(const String& objectId); - void discardInjectedScripts(); void releaseObjectGroup(const String& objectGroup); + void clearExceptionValue(); protected: - virtual void didCreateInjectedScript(InjectedScript); + virtual void didCreateInjectedScript(const InjectedScript&); HashMap<int, InjectedScript> m_idToInjectedScript; HashMap<JSC::ExecState*, int> m_scriptStateToId; private: String injectedScriptSource(); - Deprecated::ScriptObject createInjectedScript(const String& source, JSC::ExecState*, int id); + JSC::JSObject* createInjectedScript(const String& source, JSC::ExecState*, int id); InspectorEnvironment& m_environment; - RefPtr<InjectedScriptHost> m_injectedScriptHost; + Ref<InjectedScriptHost> m_injectedScriptHost; int m_nextInjectedScriptId; }; } // namespace Inspector - -#endif // !defined(InjectedScriptManager_h) diff --git a/Source/JavaScriptCore/inspector/InjectedScriptModule.cpp b/Source/JavaScriptCore/inspector/InjectedScriptModule.cpp index f2b29d255..7e05fc90b 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptModule.cpp +++ b/Source/JavaScriptCore/inspector/InjectedScriptModule.cpp @@ -32,8 +32,6 @@ #include "config.h" #include "InjectedScriptModule.h" -#if ENABLE(INSPECTOR) - #include "InjectedScript.h" #include "InjectedScriptManager.h" #include "ScriptFunctionCall.h" @@ -56,36 +54,30 @@ void InjectedScriptModule::ensureInjected(InjectedScriptManager* injectedScriptM ensureInjected(injectedScriptManager, injectedScript); } -void InjectedScriptModule::ensureInjected(InjectedScriptManager* injectedScriptManager, InjectedScript injectedScript) +void InjectedScriptModule::ensureInjected(InjectedScriptManager* injectedScriptManager, const InjectedScript& injectedScript) { ASSERT(!injectedScript.hasNoValue()); if (injectedScript.hasNoValue()) return; // FIXME: Make the InjectedScript a module itself. + JSC::JSLockHolder locker(injectedScript.scriptState()); Deprecated::ScriptFunctionCall function(injectedScript.injectedScriptObject(), ASCIILiteral("module"), injectedScriptManager->inspectorEnvironment().functionCallHandler()); function.appendArgument(name()); bool hadException = false; - Deprecated::ScriptValue resultValue = injectedScript.callFunctionWithEvalEnabled(function, hadException); + auto resultValue = injectedScript.callFunctionWithEvalEnabled(function, hadException); ASSERT(!hadException); - if (hadException || resultValue.hasNoValue() || !resultValue.isObject()) { + if (hadException || !resultValue || !resultValue.isObject()) { Deprecated::ScriptFunctionCall function(injectedScript.injectedScriptObject(), ASCIILiteral("injectModule"), injectedScriptManager->inspectorEnvironment().functionCallHandler()); function.appendArgument(name()); function.appendArgument(source()); function.appendArgument(host(injectedScriptManager, injectedScript.scriptState())); resultValue = injectedScript.callFunctionWithEvalEnabled(function, hadException); - if (hadException || (returnsObject() && (resultValue.hasNoValue() || !resultValue.isObject()))) { + if (hadException) { ASSERT_NOT_REACHED(); return; } } - - if (returnsObject()) { - Deprecated::ScriptObject moduleObject(injectedScript.scriptState(), resultValue); - initialize(moduleObject, &injectedScriptManager->inspectorEnvironment()); - } } } // namespace Inspector - -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/InjectedScriptModule.h b/Source/JavaScriptCore/inspector/InjectedScriptModule.h index a170e798d..1efc0acd8 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptModule.h +++ b/Source/JavaScriptCore/inspector/InjectedScriptModule.h @@ -29,14 +29,11 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InjectedScriptModule_h -#define InjectedScriptModule_h +#pragma once #include "InjectedScriptBase.h" #include <wtf/text/WTFString.h> -#if ENABLE(INSPECTOR) - namespace JSC { class JSValue; } @@ -51,19 +48,14 @@ public: virtual ~InjectedScriptModule(); virtual String source() const = 0; virtual JSC::JSValue host(InjectedScriptManager*, JSC::ExecState*) const = 0; - virtual bool returnsObject() const = 0; protected: // Do not expose constructor in the child classes as well. Instead provide // a static factory method that would create a new instance of the class // and call its ensureInjected() method immediately. - InjectedScriptModule(const String& name); + explicit InjectedScriptModule(const String& name); void ensureInjected(InjectedScriptManager*, JSC::ExecState*); - void ensureInjected(InjectedScriptManager*, InjectedScript); + void ensureInjected(InjectedScriptManager*, const InjectedScript&); }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // InjectedScriptModule_h diff --git a/Source/JavaScriptCore/inspector/InjectedScriptSource.js b/Source/JavaScriptCore/inspector/InjectedScriptSource.js index 7bff7f6d4..1ef43ebcc 100644 --- a/Source/JavaScriptCore/inspector/InjectedScriptSource.js +++ b/Source/JavaScriptCore/inspector/InjectedScriptSource.js @@ -1,5 +1,6 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2014-2015 Apple Inc. All rights reserved. + * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -10,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -26,21 +27,46 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -//# sourceURL=__WebInspectorInjectedScript__ +//# sourceURL=__InjectedScript_InjectedScriptSource.js -/** - * @param {InjectedScriptHost} InjectedScriptHost - * @param {GlobalObject} inspectedGlobalObject - * @param {number} injectedScriptId - */ (function (InjectedScriptHost, inspectedGlobalObject, injectedScriptId) { -// Protect against Object overwritten by the user code. +// FIXME: <https://webkit.org/b/152294> Web Inspector: Parse InjectedScriptSource as a built-in to get guaranteed non-user-overriden built-ins + var Object = {}.constructor; -/** - * @constructor - */ +function toString(obj) +{ + return String(obj); +} + +function toStringDescription(obj) +{ + if (obj === 0 && 1 / obj < 0) + return "-0"; + + return toString(obj); +} + +function isUInt32(obj) +{ + if (typeof obj === "number") + return obj >>> 0 === obj && (obj > 0 || 1 / obj > 0); + return "" + (obj >>> 0) === obj; +} + +function isSymbol(obj) +{ + return typeof obj === "symbol"; +} + +function isEmptyObject(object) +{ + for (let key in object) + return false; + return true; +} + var InjectedScript = function() { this._lastBoundObjectId = 1; @@ -48,37 +74,60 @@ var InjectedScript = function() this._idToObjectGroupName = {}; this._objectGroups = {}; this._modules = {}; + this._nextSavedResultIndex = 1; + this._savedResults = []; } -/** - * @type {Object.<string, boolean>} - * @const - */ InjectedScript.primitiveTypes = { undefined: true, boolean: true, number: true, - string: true + string: true, +} + +InjectedScript.CollectionMode = { + OwnProperties: 1 << 0, // own properties. + NativeGetterProperties: 1 << 1, // native getter properties in the prototype chain. + AllProperties: 1 << 2, // all properties in the prototype chain. } InjectedScript.prototype = { - /** - * @param {*} object - * @return {boolean} - */ isPrimitiveValue: function(object) { // FIXME(33716): typeof document.all is always 'undefined'. return InjectedScript.primitiveTypes[typeof object] && !this._isHTMLAllCollection(object); }, - /** - * @param {*} object - * @param {string} groupName - * @param {boolean} canAccessInspectedGlobalObject - * @param {boolean} generatePreview - * @return {!RuntimeAgent.RemoteObject} - */ + previewValue: function(value) + { + return InjectedScript.RemoteObject.createObjectPreviewForValue(value, true); + }, + + functionDetails: function(func, previewOnly) + { + var details = InjectedScriptHost.functionDetails(func); + if (!details) + return "Cannot resolve function details."; + + // FIXME: provide function scope data in "scopesRaw" property when JSC supports it. + // <https://webkit.org/b/87192> [JSC] expose function (closure) inner context to debugger + if ("rawScopes" in details) { + if (previewOnly) + delete details.rawScopes; + else { + var objectGroupName = this._idToObjectGroupName[parsedFunctionId.id]; + var rawScopes = details.rawScopes; + var scopes = []; + delete details.rawScopes; + for (var i = 0; i < rawScopes.length; i++) + scopes.push(InjectedScript.CallFrameProxy._createScopeJson(rawScopes[i].type, rawScopes[i].object, objectGroupName)); + details.scopeChain = scopes; + } + } + + return details; + }, + wrapObject: function(object, groupName, canAccessInspectedGlobalObject, generatePreview) { if (canAccessInspectedGlobalObject) @@ -86,10 +135,16 @@ InjectedScript.prototype = { return this._fallbackWrapper(object); }, - /** - * @param {*} object - * @return {!RuntimeAgent.RemoteObject} - */ + setExceptionValue: function(value) + { + this._exceptionValue = value; + }, + + clearExceptionValue: function() + { + delete this._exceptionValue; + }, + _fallbackWrapper: function(object) { var result = {}; @@ -97,50 +152,38 @@ InjectedScript.prototype = { if (this.isPrimitiveValue(object)) result.value = object; else - result.description = this._toString(object); - return /** @type {!RuntimeAgent.RemoteObject} */ (result); + result.description = toString(object); + return result; }, - /** - * @param {boolean} canAccessInspectedGlobalObject - * @param {Object} table - * @param {Array.<string>|string|boolean} columns - * @return {!RuntimeAgent.RemoteObject} - */ wrapTable: function(canAccessInspectedGlobalObject, table, columns) { if (!canAccessInspectedGlobalObject) return this._fallbackWrapper(table); + + // FIXME: Currently columns are ignored. Instead, the frontend filters all + // properties based on the provided column names and in the provided order. + // We could filter here to avoid sending very large preview objects. + var columnNames = null; if (typeof columns === "string") columns = [columns]; - if (InjectedScriptHost.type(columns) == "array") { + + if (InjectedScriptHost.subtype(columns) === "array") { columnNames = []; for (var i = 0; i < columns.length; ++i) - columnNames.push(String(columns[i])); + columnNames.push(toString(columns[i])); } + return this._wrapObject(table, "console", false, true, columnNames); }, - /** - * @param {*} object - */ inspectObject: function(object) { if (this._commandLineAPIImpl) this._commandLineAPIImpl.inspect(object); }, - /** - * This method cannot throw. - * @param {*} object - * @param {string=} objectGroupName - * @param {boolean=} forceValueType - * @param {boolean=} generatePreview - * @param {?Array.<string>=} columnNames - * @return {!RuntimeAgent.RemoteObject} - * @suppress {checkTypes} - */ _wrapObject: function(object, objectGroupName, forceValueType, generatePreview, columnNames) { try { @@ -155,11 +198,6 @@ InjectedScript.prototype = { } }, - /** - * @param {*} object - * @param {string=} objectGroupName - * @return {string} - */ _bind: function(object, objectGroupName) { var id = this._lastBoundObjectId++; @@ -177,39 +215,34 @@ InjectedScript.prototype = { return objectId; }, - /** - * @param {string} objectId - * @return {Object} - */ _parseObjectId: function(objectId) { return InjectedScriptHost.evaluate("(" + objectId + ")"); }, - /** - * @param {string} objectGroupName - */ releaseObjectGroup: function(objectGroupName) { + if (objectGroupName === "console") { + delete this._lastResult; + this._nextSavedResultIndex = 1; + this._savedResults = []; + } + var group = this._objectGroups[objectGroupName]; if (!group) return; + for (var i = 0; i < group.length; i++) this._releaseObject(group[i]); + delete this._objectGroups[objectGroupName]; }, - /** - * @param {string} methodName - * @param {string} args - * @return {*} - */ dispatch: function(methodName, args) { var argsArray = InjectedScriptHost.evaluate("(" + args + ")"); var result = this[methodName].apply(this, argsArray); if (typeof result === "undefined") { - // FIXME: JS Context inspection currently does not have a global.console object. if (inspectedGlobalObject.console) inspectedGlobalObject.console.error("Web Inspector error: InjectedScript.%s returns undefined", methodName); result = null; @@ -217,12 +250,7 @@ InjectedScript.prototype = { return result; }, - /** - * @param {string} objectId - * @param {boolean} ownProperties - * @return {Array.<RuntimeAgent.PropertyDescriptor>|boolean} - */ - getProperties: function(objectId, ownProperties) + _getProperties: function(objectId, collectionMode, generatePreview, nativeGettersAsValues) { var parsedObjectId = this._parseObjectId(objectId); var object = this._objectForId(parsedObjectId); @@ -230,7 +258,11 @@ InjectedScript.prototype = { if (!this._isDefined(object)) return false; - var descriptors = this._propertyDescriptors(object, ownProperties); + + if (isSymbol(object)) + return false; + + var descriptors = this._propertyDescriptors(object, collectionMode, nativeGettersAsValues); // Go over properties, wrap object values. for (var i = 0; i < descriptors.length; ++i) { @@ -240,156 +272,119 @@ InjectedScript.prototype = { if ("set" in descriptor) descriptor.set = this._wrapObject(descriptor.set, objectGroupName); if ("value" in descriptor) - descriptor.value = this._wrapObject(descriptor.value, objectGroupName); + descriptor.value = this._wrapObject(descriptor.value, objectGroupName, false, generatePreview); if (!("configurable" in descriptor)) descriptor.configurable = false; if (!("enumerable" in descriptor)) descriptor.enumerable = false; + if ("symbol" in descriptor) + descriptor.symbol = this._wrapObject(descriptor.symbol, objectGroupName); } + return descriptors; }, - /** - * @param {string} objectId - * @return {Array.<Object>|boolean} - */ - getInternalProperties: function(objectId, ownProperties) + getProperties: function(objectId, ownProperties, generatePreview) + { + var nativeGettersAsValues = false; + var collectionMode = ownProperties ? InjectedScript.CollectionMode.OwnProperties : InjectedScript.CollectionMode.AllProperties; + return this._getProperties(objectId, collectionMode, generatePreview, nativeGettersAsValues); + }, + + getDisplayableProperties: function(objectId, generatePreview) + { + var nativeGettersAsValues = true; + var collectionMode = InjectedScript.CollectionMode.OwnProperties | InjectedScript.CollectionMode.NativeGetterProperties; + return this._getProperties(objectId, collectionMode, generatePreview, nativeGettersAsValues); + }, + + getInternalProperties: function(objectId, generatePreview) { var parsedObjectId = this._parseObjectId(objectId); var object = this._objectForId(parsedObjectId); var objectGroupName = this._idToObjectGroupName[parsedObjectId.id]; + if (!this._isDefined(object)) return false; - var descriptors = []; - var internalProperties = InjectedScriptHost.getInternalProperties(object); - if (internalProperties) { - for (var i = 0; i < internalProperties.length; i++) { - var property = internalProperties[i]; - var descriptor = { - name: property.name, - value: this._wrapObject(property.value, objectGroupName) - }; - descriptors.push(descriptor); - } + + if (isSymbol(object)) + return false; + + var descriptors = this._internalPropertyDescriptors(object); + if (!descriptors) + return []; + + // Go over properties, wrap object values. + for (var i = 0; i < descriptors.length; ++i) { + var descriptor = descriptors[i]; + if ("value" in descriptor) + descriptor.value = this._wrapObject(descriptor.value, objectGroupName, false, generatePreview); } + return descriptors; }, - /** - * @param {string} functionId - * @return {!DebuggerAgent.FunctionDetails|string} - */ + getCollectionEntries: function(objectId, objectGroupName, startIndex, numberToFetch) + { + var parsedObjectId = this._parseObjectId(objectId); + var object = this._objectForId(parsedObjectId); + var objectGroupName = objectGroupName || this._idToObjectGroupName[parsedObjectId.id]; + + if (!this._isDefined(object)) + return; + + if (typeof object !== "object") + return; + + var entries = this._entries(object, InjectedScriptHost.subtype(object), startIndex, numberToFetch); + return entries.map(function(entry) { + entry.value = injectedScript._wrapObject(entry.value, objectGroupName, false, true); + if ("key" in entry) + entry.key = injectedScript._wrapObject(entry.key, objectGroupName, false, true); + return entry; + }); + }, + + saveResult: function(callArgumentJSON) + { + this._savedResultIndex = 0; + + try { + var callArgument = InjectedScriptHost.evaluate("(" + callArgumentJSON + ")"); + var value = this._resolveCallArgument(callArgument); + this._saveResult(value); + } catch (e) {} + + return this._savedResultIndex; + }, + getFunctionDetails: function(functionId) { var parsedFunctionId = this._parseObjectId(functionId); var func = this._objectForId(parsedFunctionId); if (typeof func !== "function") return "Cannot resolve function by id."; - var details = InjectedScriptHost.functionDetails(func); - if (!details) - return "Cannot resolve function details."; - if ("rawScopes" in details) { - var objectGroupName = this._idToObjectGroupName[parsedFunctionId.id]; - var rawScopes = details.rawScopes; - var scopes = []; - delete details.rawScopes; - for (var i = 0; i < rawScopes.length; i++) - scopes.push(InjectedScript.CallFrameProxy._createScopeJson(rawScopes[i].type, rawScopes[i].object, objectGroupName)); - details.scopeChain = scopes; - } - return details; + return injectedScript.functionDetails(func); }, - /** - * @param {string} objectId - */ releaseObject: function(objectId) { var parsedObjectId = this._parseObjectId(objectId); this._releaseObject(parsedObjectId.id); }, - /** - * @param {string} id - */ _releaseObject: function(id) { delete this._idToWrappedObject[id]; delete this._idToObjectGroupName[id]; }, - /** - * @param {Object} object - * @param {boolean} ownProperties - * @return {Array.<Object>} - */ - _propertyDescriptors: function(object, ownProperties) + evaluate: function(expression, objectGroup, injectCommandLineAPI, returnByValue, generatePreview, saveResult) { - var descriptors = []; - var nameProcessed = {}; - nameProcessed["__proto__"] = null; - for (var o = object; this._isDefined(o); o = o.__proto__) { - var names = Object.getOwnPropertyNames(/** @type {!Object} */ (o)); - for (var i = 0; i < names.length; ++i) { - var name = names[i]; - if (nameProcessed[name]) - continue; - - try { - nameProcessed[name] = true; - var descriptor = Object.getOwnPropertyDescriptor(/** @type {!Object} */ (object), name); - if (!descriptor) { - // Not all bindings provide proper descriptors. Fall back to the writable, configurable property. - try { - descriptor = { name: name, value: object[name], writable: false, configurable: false, enumerable: false}; - if (o === object) - descriptor.isOwn = true; - descriptors.push(descriptor); - } catch (e) { - // Silent catch. - } - continue; - } - } catch (e) { - var descriptor = {}; - descriptor.value = e; - descriptor.wasThrown = true; - } - - descriptor.name = name; - if (o === object) - descriptor.isOwn = true; - descriptors.push(descriptor); - } - if (ownProperties) { - if (object.__proto__) - descriptors.push({ name: "__proto__", value: object.__proto__, writable: true, configurable: true, enumerable: false, isOwn: true}); - break; - } - } - return descriptors; - }, - - /** - * @param {string} expression - * @param {string} objectGroup - * @param {boolean} injectCommandLineAPI - * @param {boolean} returnByValue - * @param {boolean} generatePreview - * @return {*} - */ - evaluate: function(expression, objectGroup, injectCommandLineAPI, returnByValue, generatePreview) - { - return this._evaluateAndWrap(InjectedScriptHost.evaluate, InjectedScriptHost, expression, objectGroup, false, injectCommandLineAPI, returnByValue, generatePreview); + return this._evaluateAndWrap(InjectedScriptHost.evaluateWithScopeExtension, InjectedScriptHost, expression, objectGroup, false, injectCommandLineAPI, returnByValue, generatePreview, saveResult); }, - /** - * @param {string} objectId - * @param {string} expression - * @param {boolean} returnByValue - * @return {Object|string} - */ - callFunctionOn: function(objectId, expression, args, returnByValue) + callFunctionOn: function(objectId, expression, args, returnByValue, generatePreview) { var parsedObjectId = this._parseObjectId(objectId); var object = this._objectForId(parsedObjectId); @@ -398,15 +393,13 @@ InjectedScript.prototype = { if (args) { var resolvedArgs = []; - args = InjectedScriptHost.evaluate(args); - for (var i = 0; i < args.length; ++i) { - var resolvedCallArgument; + var callArgs = InjectedScriptHost.evaluate(args); + for (var i = 0; i < callArgs.length; ++i) { try { - resolvedCallArgument = this._resolveCallArgument(args[i]); + resolvedArgs[i] = this._resolveCallArgument(callArgs[i]); } catch (e) { return String(e); } - resolvedArgs.push(resolvedCallArgument) } } @@ -416,21 +409,21 @@ InjectedScript.prototype = { if (typeof func !== "function") return "Given expression does not evaluate to a function"; - return { wasThrown: false, - result: this._wrapObject(func.apply(object, resolvedArgs), objectGroup, returnByValue) }; + return { + wasThrown: false, + result: this._wrapObject(func.apply(object, resolvedArgs), objectGroup, returnByValue, generatePreview) + }; } catch (e) { return this._createThrownValue(e, objectGroup); } }, - /** - * Resolves a value from CallArgument description. - * @param {RuntimeAgent.CallArgument} callArgumentJson - * @return {*} resolved value - * @throws {string} error message - */ - _resolveCallArgument: function(callArgumentJson) { - var objectId = callArgumentJson.objectId; + _resolveCallArgument: function(callArgumentJSON) + { + if ("value" in callArgumentJSON) + return callArgumentJSON.value; + + var objectId = callArgumentJSON.objectId; if (objectId) { var parsedArgId = this._parseObjectId(objectId); if (!parsedArgId || parsedArgId["injectedScriptId"] !== injectedScriptId) @@ -441,140 +434,58 @@ InjectedScript.prototype = { throw "Could not find object with given id"; return resolvedArg; - } else if ("value" in callArgumentJson) - return callArgumentJson.value; - else - return undefined; + } + + return undefined; }, - /** - * @param {Function} evalFunction - * @param {Object} object - * @param {string} objectGroup - * @param {boolean} isEvalOnCallFrame - * @param {boolean} injectCommandLineAPI - * @param {boolean} returnByValue - * @param {boolean} generatePreview - * @return {*} - */ - _evaluateAndWrap: function(evalFunction, object, expression, objectGroup, isEvalOnCallFrame, injectCommandLineAPI, returnByValue, generatePreview) + _evaluateAndWrap: function(evalFunction, object, expression, objectGroup, isEvalOnCallFrame, injectCommandLineAPI, returnByValue, generatePreview, saveResult) { try { - return { wasThrown: false, - result: this._wrapObject(this._evaluateOn(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI), objectGroup, returnByValue, generatePreview) }; + this._savedResultIndex = 0; + + var returnObject = { + wasThrown: false, + result: this._wrapObject(this._evaluateOn(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI, saveResult), objectGroup, returnByValue, generatePreview) + }; + + if (saveResult && this._savedResultIndex) + returnObject.savedResultIndex = this._savedResultIndex; + + return returnObject; } catch (e) { return this._createThrownValue(e, objectGroup); } }, - /** - * @param {*} value - * @param {string} objectGroup - * @return {Object} - */ _createThrownValue: function(value, objectGroup) { var remoteObject = this._wrapObject(value, objectGroup); try { - remoteObject.description = this._toString(value); + remoteObject.description = toStringDescription(value); } catch (e) {} - return { wasThrown: true, - result: remoteObject }; + return { + wasThrown: true, + result: remoteObject + }; }, - /** - * @param {Function} evalFunction - * @param {Object} object - * @param {string} objectGroup - * @param {string} expression - * @param {boolean} isEvalOnCallFrame - * @param {boolean} injectCommandLineAPI - * @return {*} - */ - _evaluateOn: function(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI) + _evaluateOn: function(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI, saveResult) { var commandLineAPI = null; if (injectCommandLineAPI) { if (this.CommandLineAPI) commandLineAPI = new this.CommandLineAPI(this._commandLineAPIImpl, isEvalOnCallFrame ? object : null); else - commandLineAPI = new BasicCommandLineAPI; + commandLineAPI = new BasicCommandLineAPI(isEvalOnCallFrame ? object : null); } - if (isEvalOnCallFrame) { - // We can only use this approach if the evaluate function is the true 'eval'. That allows us to use it with - // the 'eval' identifier when calling it. Using 'eval' grants access to the local scope of the closure we - // create that provides the command line APIs. - - var parameters = [InjectedScriptHost.evaluate, expression]; - var expressionFunctionBody = "" + - "var global = Function('return this')() || (1, eval)('this');" + - "var __originalEval = global.eval; global.eval = __eval;" + - "try { return eval(__currentExpression); }" + - "finally { global.eval = __originalEval; }"; - - if (commandLineAPI) { - // To avoid using a 'with' statement (which fails in strict mode and requires injecting the API object) - // we instead create a closure where we evaluate the expression. The command line APIs are passed as - // parameters to the closure so they are in scope but not injected. This allows the code evaluated in - // the console to stay in strict mode (if is was already set), or to get strict mode by prefixing - // expressions with 'use strict';. - - var parameterNames = Object.getOwnPropertyNames(commandLineAPI); - for (var i = 0; i < parameterNames.length; ++i) - parameters.push(commandLineAPI[parameterNames[i]]); - - var expressionFunctionString = "(function(__eval, __currentExpression, " + parameterNames.join(", ") + ") { " + expressionFunctionBody + " })"; - } else { - // Use a closure in this case too to keep the same behavior of 'var' being captured by the closure instead - // of leaking out into the calling scope. - var expressionFunctionString = "(function(__eval, __currentExpression) { " + expressionFunctionBody + " })"; - } - - // Bind 'this' to the function expression using another closure instead of Function.prototype.bind. This ensures things will work if the page replaces bind. - var boundExpressionFunctionString = "(function(__function, __thisObject) { return function() { return __function.apply(__thisObject, arguments) }; })(" + expressionFunctionString + ", this)"; - var expressionFunction = evalFunction.call(object, boundExpressionFunctionString); - var result = expressionFunction.apply(null, parameters); - - if (objectGroup === "console") - this._lastResult = result; - - return result; - } - - // When not evaluating on a call frame we use a 'with' statement to allow var and function statements to leak - // into the global scope. This allow them to stick around between evaluations. - - // FIXME: JS Context inspection currently does not have a global.console object. - try { - if (commandLineAPI) { - if (inspectedGlobalObject.console) - inspectedGlobalObject.console.__commandLineAPI = commandLineAPI; - else - inspectedGlobalObject.__commandLineAPI = commandLineAPI; - expression = "with ((this && (this.console ? this.console.__commandLineAPI : this.__commandLineAPI)) || {}) { " + expression + "\n}"; - } - - var result = evalFunction.call(inspectedGlobalObject, expression); - - if (objectGroup === "console") - this._lastResult = result; - - return result; - } finally { - if (commandLineAPI) { - if (inspectedGlobalObject.console) - delete inspectedGlobalObject.console.__commandLineAPI; - else - delete inspectedGlobalObject.__commandLineAPI; - } - } + var result = evalFunction.call(object, expression, commandLineAPI); + if (saveResult) + this._saveResult(result); + return result; }, - /** - * @param {Object} callFrame - * @return {Array.<InjectedScript.CallFrameProxy>|boolean} - */ wrapCallFrames: function(callFrame) { if (!callFrame) @@ -589,29 +500,14 @@ InjectedScript.prototype = { return result; }, - /** - * @param {Object} topCallFrame - * @param {string} callFrameId - * @param {string} expression - * @param {string} objectGroup - * @param {boolean} injectCommandLineAPI - * @param {boolean} returnByValue - * @param {boolean} generatePreview - * @return {*} - */ - evaluateOnCallFrame: function(topCallFrame, callFrameId, expression, objectGroup, injectCommandLineAPI, returnByValue, generatePreview) + evaluateOnCallFrame: function(topCallFrame, callFrameId, expression, objectGroup, injectCommandLineAPI, returnByValue, generatePreview, saveResult) { var callFrame = this._callFrameForId(topCallFrame, callFrameId); if (!callFrame) return "Could not find call frame with given id"; - return this._evaluateAndWrap(callFrame.evaluate, callFrame, expression, objectGroup, true, injectCommandLineAPI, returnByValue, generatePreview); + return this._evaluateAndWrap(callFrame.evaluateWithScopeExtension, callFrame, expression, objectGroup, true, injectCommandLineAPI, returnByValue, generatePreview, saveResult); }, - /** - * @param {Object} topCallFrame - * @param {string} callFrameId - * @return {Object} - */ _callFrameForId: function(topCallFrame, callFrameId) { var parsedCallFrameId = InjectedScriptHost.evaluate("(" + callFrameId + ")"); @@ -622,89 +518,215 @@ InjectedScript.prototype = { return callFrame; }, - /** - * @param {Object} objectId - * @return {Object} - */ _objectForId: function(objectId) { return this._idToWrappedObject[objectId.id]; }, - /** - * @param {string} objectId - * @return {Object} - */ findObjectById: function(objectId) { var parsedObjectId = this._parseObjectId(objectId); return this._objectForId(parsedObjectId); }, - /** - * @param {string} name - * @return {Object} - */ module: function(name) { return this._modules[name]; }, - /** - * @param {string} name - * @param {string} source - * @return {Object} - */ injectModule: function(name, source, host) { delete this._modules[name]; + var moduleFunction = InjectedScriptHost.evaluate("(" + source + ")"); if (typeof moduleFunction !== "function") { - // FIXME: JS Context inspection currently does not have a global.console object. if (inspectedGlobalObject.console) inspectedGlobalObject.console.error("Web Inspector error: A function was expected for module %s evaluation", name); return null; } + var module = moduleFunction.call(inspectedGlobalObject, InjectedScriptHost, inspectedGlobalObject, injectedScriptId, this, host); this._modules[name] = module; return module; }, - /** - * @param {*} object - * @return {boolean} - */ + _internalPropertyDescriptors: function(object, completeDescriptor) + { + var internalProperties = InjectedScriptHost.getInternalProperties(object); + if (!internalProperties) + return null; + + var descriptors = []; + for (var i = 0; i < internalProperties.length; i++) { + var property = internalProperties[i]; + var descriptor = {name: property.name, value: property.value}; + if (completeDescriptor) { + descriptor.writable = false; + descriptor.configurable = false; + descriptor.enumerable = false; + descriptor.isOwn = true; + } + descriptors.push(descriptor); + } + return descriptors; + }, + + _propertyDescriptors: function(object, collectionMode, nativeGettersAsValues) + { + if (InjectedScriptHost.subtype(object) === "proxy") + return []; + + var descriptors = []; + var nameProcessed = new Set; + + function createFakeValueDescriptor(name, symbol, descriptor, isOwnProperty, possibleNativeBindingGetter) + { + try { + var descriptor = {name, value: object[name], writable: descriptor.writable || false, configurable: descriptor.configurable || false, enumerable: descriptor.enumerable || false}; + if (possibleNativeBindingGetter) + descriptor.nativeGetter = true; + if (isOwnProperty) + descriptor.isOwn = true; + if (symbol) + descriptor.symbol = symbol; + return descriptor; + } catch (e) { + var errorDescriptor = {name, value: e, wasThrown: true}; + if (isOwnProperty) + errorDescriptor.isOwn = true; + if (symbol) + errorDescriptor.symbol = symbol; + return errorDescriptor; + } + } + + function processDescriptor(descriptor, isOwnProperty, possibleNativeBindingGetter) + { + // All properties. + if (collectionMode & InjectedScript.CollectionMode.AllProperties) { + descriptors.push(descriptor); + return; + } + + // Own properties. + if (collectionMode & InjectedScript.CollectionMode.OwnProperties && isOwnProperty) { + descriptors.push(descriptor); + return; + } + + // Native Getter properties. + if (collectionMode & InjectedScript.CollectionMode.NativeGetterProperties) { + if (possibleNativeBindingGetter) { + descriptors.push(descriptor); + return; + } + } + } + + function processProperties(o, properties, isOwnProperty) + { + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + if (nameProcessed.has(property) || property === "__proto__") + continue; + + nameProcessed.add(property); + + var name = toString(property); + var symbol = isSymbol(property) ? property : null; + + var descriptor = Object.getOwnPropertyDescriptor(o, property); + if (!descriptor) { + // FIXME: Bad descriptor. Can we get here? + // Fall back to very restrictive settings. + var fakeDescriptor = createFakeValueDescriptor(name, symbol, {writable: false, configurable: false, enumerable: false}, isOwnProperty); + processDescriptor(fakeDescriptor, isOwnProperty); + continue; + } + + if (nativeGettersAsValues) { + if (String(descriptor.get).endsWith("[native code]\n}") || (!descriptor.get && descriptor.hasOwnProperty("get") && !descriptor.set && descriptor.hasOwnProperty("set"))) { + // Developers may create such a descriptor, so we should be resilient: + // var x = {}; Object.defineProperty(x, "p", {get:undefined}); Object.getOwnPropertyDescriptor(x, "p") + var fakeDescriptor = createFakeValueDescriptor(name, symbol, descriptor, isOwnProperty, true); + processDescriptor(fakeDescriptor, isOwnProperty, true); + continue; + } + } + + descriptor.name = name; + if (isOwnProperty) + descriptor.isOwn = true; + if (symbol) + descriptor.symbol = symbol; + processDescriptor(descriptor, isOwnProperty); + } + } + + function arrayIndexPropertyNames(o, length) + { + var array = []; + for (var i = 0; i < length; ++i) { + if (i in o) + array.push("" + i); + } + return array; + } + + // FIXME: <https://webkit.org/b/143589> Web Inspector: Better handling for large collections in Object Trees + // For array types with a large length we attempt to skip getOwnPropertyNames and instead just sublist of indexes. + var isArrayLike = false; + try { + isArrayLike = injectedScript._subtype(object) === "array" && isFinite(object.length) && object.length > 0; + } catch(e) {} + + for (var o = object; this._isDefined(o); o = Object.getPrototypeOf(o)) { + var isOwnProperty = o === object; + + if (isArrayLike && isOwnProperty) + processProperties(o, arrayIndexPropertyNames(o, Math.min(object.length, 100)), isOwnProperty); + else { + processProperties(o, Object.getOwnPropertyNames(o), isOwnProperty); + if (Object.getOwnPropertySymbols) + processProperties(o, Object.getOwnPropertySymbols(o), isOwnProperty); + } + + if (collectionMode === InjectedScript.CollectionMode.OwnProperties) + break; + } + + // Always include __proto__ at the end. + try { + if (object.__proto__) + descriptors.push({name: "__proto__", value: object.__proto__, writable: true, configurable: true, enumerable: false, isOwn: true}); + } catch (e) {} + + return descriptors; + }, + _isDefined: function(object) { return !!object || this._isHTMLAllCollection(object); }, - /** - * @param {*} object - * @return {boolean} - */ _isHTMLAllCollection: function(object) { // document.all is reported as undefined, but we still want to process it. return (typeof object === "undefined") && InjectedScriptHost.isHTMLAllCollection(object); }, - /** - * @param {Object=} obj - * @return {string?} - */ _subtype: function(obj) { if (obj === null) return "null"; - if (this.isPrimitiveValue(obj)) + if (this.isPrimitiveValue(obj) || isSymbol(obj)) return null; if (this._isHTMLAllCollection(obj)) return "array"; - var preciseType = InjectedScriptHost.type(obj); + var preciseType = InjectedScriptHost.subtype(obj); if (preciseType) return preciseType; @@ -712,322 +734,663 @@ InjectedScript.prototype = { try { if (typeof obj.splice === "function" && isFinite(obj.length)) return "array"; - if (Object.prototype.toString.call(obj) === "[object Arguments]" && isFinite(obj.length)) // arguments. - return "array"; - } catch (e) { - } + } catch (e) {} - // If owning frame has navigated to somewhere else window properties will be undefined. return null; }, - /** - * @param {*} obj - * @return {string?} - */ + _classPreview: function(classConstructorValue) + { + return "class " + classConstructorValue.name; + }, + + _nodePreview: function(node) + { + var isXMLDocument = node.ownerDocument && !!node.ownerDocument.xmlVersion; + var nodeName = isXMLDocument ? node.nodeName : node.nodeName.toLowerCase(); + + switch (node.nodeType) { + case 1: // Node.ELEMENT_NODE + if (node.id) + return "<" + nodeName + " id=\"" + node.id + "\">"; + if (node.classList.length) + return "<" + nodeName + " class=\"" + node.classList.toString().replace(/\s+/, " ") + "\">"; + if (nodeName === "input" && node.type) + return "<" + nodeName + " type=\"" + node.type + "\">"; + return "<" + nodeName + ">"; + + case 3: // Node.TEXT_NODE + return nodeName + " \"" + node.nodeValue + "\""; + + case 8: // Node.COMMENT_NODE + return "<!--" + node.nodeValue + "-->"; + + case 10: // Node.DOCUMENT_TYPE_NODE + return "<!DOCTYPE " + nodeName + ">"; + + default: + return nodeName; + } + }, + _describe: function(obj) { if (this.isPrimitiveValue(obj)) return null; - obj = /** @type {Object} */ (obj); + if (isSymbol(obj)) + return toString(obj); - // Type is object, get subtype. var subtype = this._subtype(obj); if (subtype === "regexp") - return this._toString(obj); + return toString(obj); if (subtype === "date") - return this._toString(obj); - - if (subtype === "node") { - var description = obj.nodeName.toLowerCase(); - switch (obj.nodeType) { - case 1 /* Node.ELEMENT_NODE */: - description += obj.id ? "#" + obj.id : ""; - var className = obj.className; - description += className ? "." + className : ""; - break; - case 10 /*Node.DOCUMENT_TYPE_NODE */: - description = "<!DOCTYPE " + description + ">"; - break; - } - return description; - } + return toString(obj); + + if (subtype === "error") + return toString(obj); + + if (subtype === "proxy") + return "Proxy"; + + if (subtype === "node") + return this._nodePreview(obj); var className = InjectedScriptHost.internalConstructorName(obj); - if (subtype === "array") { - if (typeof obj.length === "number") - className += "[" + obj.length + "]"; + if (subtype === "array") return className; - } + + if (subtype === "iterator" && Symbol.toStringTag in obj) + return obj[Symbol.toStringTag]; // NodeList in JSC is a function, check for array prior to this. if (typeof obj === "function") - return this._toString(obj); + return obj.toString(); + // If Object, try for a better name from the constructor. if (className === "Object") { - // In Chromium DOM wrapper prototypes will have Object as their constructor name, - // get the real DOM wrapper name from the constructor property. var constructorName = obj.constructor && obj.constructor.name; if (constructorName) return constructorName; } + return className; }, - /** - * @param {*} obj - * @return {string} - */ - _toString: function(obj) + _getSetEntries: function(object, skip, numberToFetch) + { + var entries = []; + + for (var value of object) { + if (skip > 0) { + skip--; + continue; + } + + entries.push({value}); + + if (numberToFetch && entries.length === numberToFetch) + break; + } + + return entries; + }, + + _getMapEntries: function(object, skip, numberToFetch) + { + var entries = []; + + for (var [key, value] of object) { + if (skip > 0) { + skip--; + continue; + } + + entries.push({key, value}); + + if (numberToFetch && entries.length === numberToFetch) + break; + } + + return entries; + }, + + _getWeakMapEntries: function(object, numberToFetch) + { + return InjectedScriptHost.weakMapEntries(object, numberToFetch); + }, + + _getWeakSetEntries: function(object, numberToFetch) + { + return InjectedScriptHost.weakSetEntries(object, numberToFetch); + }, + + _getIteratorEntries: function(object, numberToFetch) + { + return InjectedScriptHost.iteratorEntries(object, numberToFetch); + }, + + _entries: function(object, subtype, startIndex, numberToFetch) + { + if (subtype === "set") + return this._getSetEntries(object, startIndex, numberToFetch); + if (subtype === "map") + return this._getMapEntries(object, startIndex, numberToFetch); + if (subtype === "weakmap") + return this._getWeakMapEntries(object, numberToFetch); + if (subtype === "weakset") + return this._getWeakSetEntries(object, numberToFetch); + if (subtype === "iterator") + return this._getIteratorEntries(object, numberToFetch); + + throw "unexpected type"; + }, + + _saveResult: function(result) { - // We don't use String(obj) because inspectedGlobalObject.String is undefined if owning frame navigated to another page. - return "" + obj; + this._lastResult = result; + + if (result === undefined || result === null) + return; + + var existingIndex = this._savedResults.indexOf(result); + if (existingIndex !== -1) { + this._savedResultIndex = existingIndex; + return; + } + + this._savedResultIndex = this._nextSavedResultIndex; + this._savedResults[this._nextSavedResultIndex++] = result; + + // $n is limited from $1-$99. $0 is special. + if (this._nextSavedResultIndex >= 100) + this._nextSavedResultIndex = 1; + }, + + _savedResult: function(index) + { + return this._savedResults[index]; } } -/** - * @type {InjectedScript} - * @const - */ -var injectedScript = new InjectedScript(); - -/** - * @constructor - * @param {*} object - * @param {string=} objectGroupName - * @param {boolean=} forceValueType - * @param {boolean=} generatePreview - * @param {?Array.<string>=} columnNames - */ +var injectedScript = new InjectedScript; + + InjectedScript.RemoteObject = function(object, objectGroupName, forceValueType, generatePreview, columnNames) { this.type = typeof object; + + if (this.type === "undefined" && injectedScript._isHTMLAllCollection(object)) + this.type = "object"; + if (injectedScript.isPrimitiveValue(object) || object === null || forceValueType) { // We don't send undefined values over JSON. - if (typeof object !== "undefined") + if (this.type !== "undefined") this.value = object; - // Null object is object with 'null' subtype' + // Null object is object with 'null' subtype. if (object === null) this.subtype = "null"; // Provide user-friendly number values. - if (typeof object === "number") - this.description = object + ""; + if (this.type === "number") + this.description = toStringDescription(object); return; } - object = /** @type {Object} */ (object); - this.objectId = injectedScript._bind(object, objectGroupName); + var subtype = injectedScript._subtype(object); if (subtype) this.subtype = subtype; + this.className = InjectedScriptHost.internalConstructorName(object); this.description = injectedScript._describe(object); - if (generatePreview && (this.type === "object" || injectedScript._isHTMLAllCollection(object))) - this.preview = this._generatePreview(object, undefined, columnNames); -} + if (subtype === "array") + this.size = typeof object.length === "number" ? object.length : 0; + else if (subtype === "set" || subtype === "map") + this.size = object.size; + else if (subtype === "weakmap") + this.size = InjectedScriptHost.weakMapSize(object); + else if (subtype === "weakset") + this.size = InjectedScriptHost.weakSetSize(object); + else if (subtype === "class") { + this.classPrototype = injectedScript._wrapObject(object.prototype, objectGroupName); + this.className = object.name; + } + + if (generatePreview && this.type === "object") { + if (subtype === "proxy") { + this.preview = this._generatePreview(InjectedScriptHost.proxyTargetValue(object)); + this.preview.lossless = false; + } else + this.preview = this._generatePreview(object, undefined, columnNames); + } +}; + +InjectedScript.RemoteObject.createObjectPreviewForValue = function(value, generatePreview, columnNames) +{ + var remoteObject = new InjectedScript.RemoteObject(value, undefined, false, generatePreview, columnNames); + if (remoteObject.objectId) + injectedScript.releaseObject(remoteObject.objectId); + if (remoteObject.classPrototype && remoteObject.classPrototype.objectId) + injectedScript.releaseObject(remoteObject.classPrototype.objectId); + return remoteObject.preview || remoteObject._emptyPreview(); +}; InjectedScript.RemoteObject.prototype = { - /** - * @param {Object} object - * @param {Array.<string>=} firstLevelKeys - * @param {?Array.<string>=} secondLevelKeys - * @return {Object} preview - */ - _generatePreview: function(object, firstLevelKeys, secondLevelKeys) + _initialPreview: function() { - var preview = {}; - preview.lossless = true; - preview.overflow = false; - preview.properties = []; + var preview = { + type: this.type, + description: this.description || toString(this.value), + lossless: true, + }; + if (this.subtype) { + preview.subtype = this.subtype; + if (this.subtype !== "null") { + preview.overflow = false; + preview.properties = []; + } + } + + if ("size" in this) + preview.size = this.size; + + return preview; + }, + + _emptyPreview: function() + { + var preview = this._initialPreview(); + + if (this.subtype === "map" || this.subtype === "set" || this.subtype === "weakmap" || this.subtype === "weakset" || this.subtype === "iterator") { + if (this.size) { + preview.entries = []; + preview.lossless = false; + preview.overflow = true; + } + } + + return preview; + }, + + _generatePreview: function(object, firstLevelKeys, secondLevelKeys) + { + var preview = this._initialPreview(); var isTableRowsRequest = secondLevelKeys === null || secondLevelKeys; var firstLevelKeysCount = firstLevelKeys ? firstLevelKeys.length : 0; var propertiesThreshold = { properties: isTableRowsRequest ? 1000 : Math.max(5, firstLevelKeysCount), - indexes: isTableRowsRequest ? 1000 : Math.max(100, firstLevelKeysCount) + indexes: isTableRowsRequest ? 1000 : Math.max(10, firstLevelKeysCount) }; - for (var o = object; injectedScript._isDefined(o); o = o.__proto__) - this._generateProtoPreview(o, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys); + + try { + // Maps, Sets, and Iterators have entries. + if (this.subtype === "map" || this.subtype === "set" || this.subtype === "weakmap" || this.subtype === "weakset" || this.subtype === "iterator") + this._appendEntryPreviews(object, preview); + + preview.properties = []; + + // Internal Properties. + var internalPropertyDescriptors = injectedScript._internalPropertyDescriptors(object, true); + if (internalPropertyDescriptors) { + this._appendPropertyPreviews(object, preview, internalPropertyDescriptors, true, propertiesThreshold, firstLevelKeys, secondLevelKeys); + if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) + return preview; + } + + if (preview.entries) + return preview; + + // Properties. + var nativeGettersAsValues = true; + var descriptors = injectedScript._propertyDescriptors(object, InjectedScript.CollectionMode.AllProperties, nativeGettersAsValues); + this._appendPropertyPreviews(object, preview, descriptors, false, propertiesThreshold, firstLevelKeys, secondLevelKeys); + if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) + return preview; + } catch (e) { + preview.lossless = false; + } + return preview; }, - /** - * @param {Object} object - * @param {Object} preview - * @param {Object} propertiesThreshold - * @param {Array.<string>=} firstLevelKeys - * @param {Array.<string>=} secondLevelKeys - */ - _generateProtoPreview: function(object, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys) + _appendPropertyPreviews: function(object, preview, descriptors, internal, propertiesThreshold, firstLevelKeys, secondLevelKeys) { - var propertyNames = firstLevelKeys ? firstLevelKeys : Object.keys(/** @type {!Object} */(object)); - try { - for (var i = 0; i < propertyNames.length; ++i) { - if (!propertiesThreshold.properties || !propertiesThreshold.indexes) { - preview.overflow = true; - preview.lossless = false; - break; - } - var name = propertyNames[i]; - if (this.subtype === "array" && name === "length") - continue; + for (var descriptor of descriptors) { + // Seen enough. + if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) + break; + + // Error in descriptor. + if (descriptor.wasThrown) { + preview.lossless = false; + continue; + } - var descriptor = Object.getOwnPropertyDescriptor(/** @type {!Object} */(object), name); - if (!("value" in descriptor) || !descriptor.enumerable) { + // Do not show "__proto__" in preview. + var name = descriptor.name; + if (name === "__proto__") { + // Non basic __proto__ objects may have interesting, non-enumerable, methods to show. + if (descriptor.value && descriptor.value.constructor + && descriptor.value.constructor !== Object + && descriptor.value.constructor !== Array + && descriptor.value.constructor !== RegExp) preview.lossless = false; - continue; - } + continue; + } - var value = descriptor.value; - if (value === null) { - this._appendPropertyPreview(preview, { name: name, type: "object", value: "null" }, propertiesThreshold); - continue; - } + // For arrays, only allow indexes. + if (this.subtype === "array" && !isUInt32(name)) + continue; - const maxLength = 100; - var type = typeof value; + // Do not show non-enumerable non-own properties. + // Special case to allow array indexes that may be on the prototype. + // Special case to allow native getters on non-RegExp objects. + if (!descriptor.enumerable && !descriptor.isOwn && !(this.subtype === "array" || (this.subtype !== "regexp" && descriptor.nativeGetter))) + continue; - if (InjectedScript.primitiveTypes[type]) { - if (type === "string") { - if (value.length > maxLength) { - value = this._abbreviateString(value, maxLength, true); - preview.lossless = false; - } - value = value.replace(/\n/g, "\u21B5"); - } - this._appendPropertyPreview(preview, { name: name, type: type, value: value + "" }, propertiesThreshold); - continue; - } + // If we have a filter, only show properties in the filter. + // FIXME: Currently these filters do nothing on the backend. + if (firstLevelKeys && !firstLevelKeys.includes(name)) + continue; - if (secondLevelKeys === null || secondLevelKeys) { - var subPreview = this._generatePreview(value, secondLevelKeys || undefined); - var property = { name: name, type: type, valuePreview: subPreview }; - this._appendPropertyPreview(preview, property, propertiesThreshold); - if (!subPreview.lossless) - preview.lossless = false; - if (subPreview.overflow) - preview.overflow = true; - continue; + // Getter/setter. + if (!("value" in descriptor)) { + preview.lossless = false; + this._appendPropertyPreview(preview, internal, {name, type: "accessor"}, propertiesThreshold); + continue; + } + + // Null value. + var value = descriptor.value; + if (value === null) { + this._appendPropertyPreview(preview, internal, {name, type: "object", subtype: "null", value: "null"}, propertiesThreshold); + continue; + } + + // Ignore non-enumerable functions. + var type = typeof value; + if (!descriptor.enumerable && type === "function") + continue; + + // Fix type of document.all. + if (type === "undefined" && injectedScript._isHTMLAllCollection(value)) + type = "object"; + + // Primitive. + const maxLength = 100; + if (InjectedScript.primitiveTypes[type]) { + if (type === "string" && value.length > maxLength) { + value = this._abbreviateString(value, maxLength, true); + preview.lossless = false; } + this._appendPropertyPreview(preview, internal, {name, type, value: toStringDescription(value)}, propertiesThreshold); + continue; + } - preview.lossless = false; + // Symbol. + if (isSymbol(value)) { + var symbolString = toString(value); + if (symbolString.length > maxLength) { + symbolString = this._abbreviateString(symbolString, maxLength, true); + preview.lossless = false; + } + this._appendPropertyPreview(preview, internal, {name, type, value: symbolString}, propertiesThreshold); + continue; + } - var subtype = injectedScript._subtype(value); + // Object. + var property = {name, type}; + var subtype = injectedScript._subtype(value); + if (subtype) + property.subtype = subtype; + + // Second level. + if ((secondLevelKeys === null || secondLevelKeys) || this._isPreviewableObject(value, object)) { + // FIXME: If we want secondLevelKeys filter to continue we would need some refactoring. + var subPreview = InjectedScript.RemoteObject.createObjectPreviewForValue(value, value !== object, secondLevelKeys); + property.valuePreview = subPreview; + if (!subPreview.lossless) + preview.lossless = false; + if (subPreview.overflow) + preview.overflow = true; + } else { var description = ""; - if (type !== "function") - description = this._abbreviateString(/** @type {string} */ (injectedScript._describe(value)), maxLength, subtype === "regexp"); - - var property = { name: name, type: type, value: description }; - if (subtype) - property.subtype = subtype; - this._appendPropertyPreview(preview, property, propertiesThreshold); + if (type !== "function" || subtype === "class") { + var fullDescription; + if (subtype === "class") + fullDescription = "class " + value.name; + else if (subtype === "node") + fullDescription = injectedScript._nodePreview(value); + else + fullDescription = injectedScript._describe(value); + description = this._abbreviateString(fullDescription, maxLength, subtype === "regexp"); + } + property.value = description; + preview.lossless = false; } - } catch (e) { + + this._appendPropertyPreview(preview, internal, property, propertiesThreshold); } }, - /** - * @param {Object} preview - * @param {Object} property - * @param {Object} propertiesThreshold - */ - _appendPropertyPreview: function(preview, property, propertiesThreshold) + _appendPropertyPreview: function(preview, internal, property, propertiesThreshold) { - if (isNaN(property.name)) - propertiesThreshold.properties--; - else + if (toString(property.name >>> 0) === property.name) propertiesThreshold.indexes--; + else + propertiesThreshold.properties--; + + if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) { + preview.overflow = true; + preview.lossless = false; + return; + } + + if (internal) + property.internal = true; + preview.properties.push(property); }, - /** - * @param {string} string - * @param {number} maxLength - * @param {boolean=} middle - * @returns - */ + _appendEntryPreviews: function(object, preview) + { + // Fetch 6, but only return 5, so we can tell if we overflowed. + var entries = injectedScript._entries(object, this.subtype, 0, 6); + if (!entries) + return; + + if (entries.length > 5) { + entries.pop(); + preview.overflow = true; + preview.lossless = false; + } + + function updateMainPreview(subPreview) { + if (!subPreview.lossless) + preview.lossless = false; + } + + preview.entries = entries.map(function(entry) { + entry.value = InjectedScript.RemoteObject.createObjectPreviewForValue(entry.value, entry.value !== object); + updateMainPreview(entry.value); + if ("key" in entry) { + entry.key = InjectedScript.RemoteObject.createObjectPreviewForValue(entry.key, entry.key !== object); + updateMainPreview(entry.key); + } + return entry; + }, this); + }, + + _isPreviewableObject: function(value, object) + { + return this._isPreviewableObjectInternal(value, new Set([object]), 1); + }, + + _isPreviewableObjectInternal: function(object, knownObjects, depth) + { + // Deep object. + if (depth > 3) + return false; + + // Primitive. + if (injectedScript.isPrimitiveValue(object) || isSymbol(object)) + return true; + + // Null. + if (object === null) + return true; + + // Cyclic objects. + if (knownObjects.has(object)) + return false; + + ++depth; + knownObjects.add(object); + + // Arrays are simple if they have 5 or less simple objects. + var subtype = injectedScript._subtype(object); + if (subtype === "array") { + var length = object.length; + if (length > 5) + return false; + for (var i = 0; i < length; ++i) { + if (!this._isPreviewableObjectInternal(object[i], knownObjects, depth)) + return false; + } + return true; + } + + // Not a basic object. + if (object.__proto__ && object.__proto__.__proto__) + return false; + + // Objects are simple if they have 3 or less simple properties. + var ownPropertyNames = Object.getOwnPropertyNames(object); + if (ownPropertyNames.length > 3) + return false; + for (var propertyName of ownPropertyNames) { + if (!this._isPreviewableObjectInternal(object[propertyName], knownObjects, depth)) + return false; + } + + return true; + }, + _abbreviateString: function(string, maxLength, middle) { if (string.length <= maxLength) return string; + if (middle) { var leftHalf = maxLength >> 1; var rightHalf = maxLength - leftHalf - 1; return string.substr(0, leftHalf) + "\u2026" + string.substr(string.length - rightHalf, rightHalf); } + return string.substr(0, maxLength) + "\u2026"; } } -/** - * @constructor - * @param {number} ordinal - * @param {Object} callFrame - */ + InjectedScript.CallFrameProxy = function(ordinal, callFrame) { this.callFrameId = "{\"ordinal\":" + ordinal + ",\"injectedScriptId\":" + injectedScriptId + "}"; - this.functionName = (callFrame.type === "function" ? callFrame.functionName : ""); - this.location = { scriptId: String(callFrame.sourceID), lineNumber: callFrame.line, columnNumber: callFrame.column }; + this.functionName = callFrame.functionName; + this.location = {scriptId: String(callFrame.sourceID), lineNumber: callFrame.line, columnNumber: callFrame.column}; this.scopeChain = this._wrapScopeChain(callFrame); - this.this = injectedScript._wrapObject(callFrame.thisObject, "backtrace"); + this.this = injectedScript._wrapObject(callFrame.thisObject, "backtrace", false, true); + this.isTailDeleted = callFrame.isTailDeleted; } InjectedScript.CallFrameProxy.prototype = { - /** - * @param {Object} callFrame - * @return {!Array.<DebuggerAgent.Scope>} - */ _wrapScopeChain: function(callFrame) { var scopeChain = callFrame.scopeChain; + var scopeDescriptions = callFrame.scopeDescriptions(); + var scopeChainProxy = []; - for (var i = 0; i < scopeChain.length; i++) { - var scope = InjectedScript.CallFrameProxy._createScopeJson(callFrame.scopeType(i), scopeChain[i], "backtrace"); - scopeChainProxy.push(scope); - } + for (var i = 0; i < scopeChain.length; i++) + scopeChainProxy[i] = InjectedScript.CallFrameProxy._createScopeJson(scopeChain[i], scopeDescriptions[i], "backtrace"); return scopeChainProxy; } } -/** - * @param {number} scopeTypeCode - * @param {*} scopeObject - * @param {string} groupId - * @return {!DebuggerAgent.Scope} - */ -InjectedScript.CallFrameProxy._createScopeJson = function(scopeTypeCode, scopeObject, groupId) { - const GLOBAL_SCOPE = 0; - const LOCAL_SCOPE = 1; - const WITH_SCOPE = 2; - const CLOSURE_SCOPE = 3; - const CATCH_SCOPE = 4; - - /** @type {!Object.<number, string>} */ - var scopeTypeNames = {}; - scopeTypeNames[GLOBAL_SCOPE] = "global"; - scopeTypeNames[LOCAL_SCOPE] = "local"; - scopeTypeNames[WITH_SCOPE] = "with"; - scopeTypeNames[CLOSURE_SCOPE] = "closure"; - scopeTypeNames[CATCH_SCOPE] = "catch"; - - return { - object: injectedScript._wrapObject(scopeObject, groupId), - type: /** @type {DebuggerAgent.ScopeType} */ (scopeTypeNames[scopeTypeCode]) +InjectedScript.CallFrameProxy._scopeTypeNames = { + 0: "global", // GLOBAL_SCOPE + 1: "with", // WITH_SCOPE + 2: "closure", // CLOSURE_SCOPE + 3: "catch", // CATCH_SCOPE + 4: "functionName", // FUNCTION_NAME_SCOPE + 5: "globalLexicalEnvironment", // GLOBAL_LEXICAL_ENVIRONMENT_SCOPE + 6: "nestedLexical", // NESTED_LEXICAL_SCOPE +}; + +InjectedScript.CallFrameProxy._createScopeJson = function(object, {name, type, location}, groupId) +{ + let scope = { + object: injectedScript._wrapObject(object, groupId), + type: InjectedScript.CallFrameProxy._scopeTypeNames[type], + }; + + if (name) + scope.name = name; + + if (location) + scope.location = location; + + if (isEmptyObject(object)) + scope.empty = true; + + return scope; +} + + +function bind(func, thisObject, ...outerArgs) +{ + return function(...innerArgs) { + return func.apply(thisObject, outerArgs.concat(innerArgs)); }; } -function BasicCommandLineAPI() +function BasicCommandLineAPI(callFrame) { this.$_ = injectedScript._lastResult; + this.$exception = injectedScript._exceptionValue; + + // $1-$99 + for (let i = 1; i <= injectedScript._savedResults.length; ++i) + this.__defineGetter__("$" + i, bind(injectedScript._savedResult, injectedScript, i)); + + // Command Line API methods. + for (let method of BasicCommandLineAPI.methods) + this[method.name] = method; } +BasicCommandLineAPI.methods = [ + function dir() { return inspectedGlobalObject.console.dir(...arguments); }, + function clear() { return inspectedGlobalObject.console.clear(...arguments); }, + function table() { return inspectedGlobalObject.console.table(...arguments); }, + function profile() { return inspectedGlobalObject.console.profile(...arguments); }, + function profileEnd() { return inspectedGlobalObject.console.profileEnd(...arguments); }, + + function keys(object) { return Object.keys(object); }, + function values(object) { + let result = []; + for (let key in object) + result.push(object[key]); + return result; + }, +]; + +for (let method of BasicCommandLineAPI.methods) + method.toString = function() { return "function " + method.name + "() { [Command Line API] }"; }; + return injectedScript; }) diff --git a/Source/JavaScriptCore/inspector/InspectorAgentBase.h b/Source/JavaScriptCore/inspector/InspectorAgentBase.h index f6b6c55cb..4edf78305 100644 --- a/Source/JavaScriptCore/inspector/InspectorAgentBase.h +++ b/Source/JavaScriptCore/inspector/InspectorAgentBase.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All Rights Reserved. + * Copyright (C) 2013, 2015 Apple Inc. All Rights Reserved. * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -24,27 +24,53 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorAgentBase_h -#define InspectorAgentBase_h +#pragma once #include <wtf/text/WTFString.h> +namespace JSC { +class JSGlobalObject; +} + namespace Inspector { -class InspectorBackendDispatcher; -class InspectorFrontendChannel; +class BackendDispatcher; +class FrontendRouter; +class InjectedScriptManager; +class InspectorEnvironment; + +struct AgentContext { + InspectorEnvironment& environment; + InjectedScriptManager& injectedScriptManager; + FrontendRouter& frontendRouter; + BackendDispatcher& backendDispatcher; +}; + +struct JSAgentContext : public AgentContext { + JSAgentContext(AgentContext& context, JSC::JSGlobalObject& globalObject) + : AgentContext(context) + , inspectedGlobalObject(globalObject) + { + } -enum class InspectorDisconnectReason { + JSC::JSGlobalObject& inspectedGlobalObject; +}; + +enum class DisconnectReason { InspectedTargetDestroyed, InspectorDestroyed }; class InspectorAgentBase { + WTF_MAKE_FAST_ALLOCATED; public: virtual ~InspectorAgentBase() { } - virtual void didCreateFrontendAndBackend(InspectorFrontendChannel*, InspectorBackendDispatcher*) = 0; - virtual void willDestroyFrontendAndBackend(InspectorDisconnectReason reason) = 0; + String domainName() const { return m_name; } + + virtual void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) = 0; + virtual void willDestroyFrontendAndBackend(DisconnectReason) = 0; + virtual void discardValues() { } virtual void discardAgent() { } protected: @@ -55,7 +81,5 @@ protected: String m_name; }; - -} // namespace Inspector -#endif // !defined(InspectorAgentBase_h) +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InspectorAgentRegistry.cpp b/Source/JavaScriptCore/inspector/InspectorAgentRegistry.cpp index e0d9ede15..b5e34741c 100644 --- a/Source/JavaScriptCore/inspector/InspectorAgentRegistry.cpp +++ b/Source/JavaScriptCore/inspector/InspectorAgentRegistry.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -27,39 +27,52 @@ #include "config.h" #include "InspectorAgentRegistry.h" -#if ENABLE(INSPECTOR) - #include "InspectorAgentBase.h" namespace Inspector { -InspectorAgentRegistry::InspectorAgentRegistry() +AgentRegistry::AgentRegistry() { } -void InspectorAgentRegistry::append(std::unique_ptr<InspectorAgentBase> agent) +AgentRegistry::~AgentRegistry() { - m_agents.append(std::move(agent)); + // Allow agents to remove cross-references to other agents that would otherwise + // make it difficult to establish a correct destruction order for all agents. + for (auto& agent : m_agents) + agent->discardAgent(); } -void InspectorAgentRegistry::didCreateFrontendAndBackend(InspectorFrontendChannel* frontendChannel, InspectorBackendDispatcher* backendDispatcher) +void AgentRegistry::append(std::unique_ptr<InspectorAgentBase> agent) { - for (size_t i = 0; i < m_agents.size(); i++) - m_agents[i]->didCreateFrontendAndBackend(frontendChannel, backendDispatcher); + m_agents.append(WTFMove(agent)); } -void InspectorAgentRegistry::willDestroyFrontendAndBackend(InspectorDisconnectReason reason) +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +void AgentRegistry::appendExtraAgent(std::unique_ptr<InspectorAgentBase> agent) { - for (size_t i = 0; i < m_agents.size(); i++) - m_agents[i]->willDestroyFrontendAndBackend(reason); + m_extraDomains.append(agent->domainName()); + + append(WTFMove(agent)); } +#endif -void InspectorAgentRegistry::discardAgents() +void AgentRegistry::didCreateFrontendAndBackend(FrontendRouter* frontendRouter, BackendDispatcher* backendDispatcher) { - for (size_t i = 0; i < m_agents.size(); i++) - m_agents[i]->discardAgent(); + for (auto& agent : m_agents) + agent->didCreateFrontendAndBackend(frontendRouter, backendDispatcher); } -} // namespace Inspector +void AgentRegistry::willDestroyFrontendAndBackend(DisconnectReason reason) +{ + for (auto& agent : m_agents) + agent->willDestroyFrontendAndBackend(reason); +} -#endif // ENABLE(INSPECTOR) +void AgentRegistry::discardValues() +{ + for (auto& agent : m_agents) + agent->discardValues(); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InspectorAgentRegistry.h b/Source/JavaScriptCore/inspector/InspectorAgentRegistry.h index 17d65e71a..7f7017c00 100644 --- a/Source/JavaScriptCore/inspector/InspectorAgentRegistry.h +++ b/Source/JavaScriptCore/inspector/InspectorAgentRegistry.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2013, 2015 Apple Inc. All rights reserved. * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -24,37 +24,45 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorAgentRegistry_h -#define InspectorAgentRegistry_h +#pragma once #include <wtf/Vector.h> +#include <wtf/text/WTFString.h> namespace Inspector { +class BackendDispatcher; +class FrontendRouter; class InspectorAgentBase; -class InspectorBackendDispatcher; -class InspectorFrontendChannel; -enum class InspectorDisconnectReason; -class JS_EXPORT_PRIVATE InspectorAgentRegistry { +enum class DisconnectReason; + +class JS_EXPORT_PRIVATE AgentRegistry { public: - InspectorAgentRegistry(); + AgentRegistry(); + ~AgentRegistry(); void append(std::unique_ptr<InspectorAgentBase>); - void didCreateFrontendAndBackend(InspectorFrontendChannel*, InspectorBackendDispatcher*); - void willDestroyFrontendAndBackend(InspectorDisconnectReason reason); - void discardAgents(); + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*); + void willDestroyFrontendAndBackend(DisconnectReason); + void discardValues(); + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + void appendExtraAgent(std::unique_ptr<InspectorAgentBase>); + Vector<String> extraDomains() const { return m_extraDomains; } +#endif private: // These are declared here to avoid MSVC from trying to create default iplementations which would // involve generating a copy constructor and copy assignment operator for the Vector of std::unique_ptrs. - InspectorAgentRegistry(const InspectorAgentRegistry&) = delete; - InspectorAgentRegistry& operator=(const InspectorAgentRegistry&) = delete; + AgentRegistry(const AgentRegistry&) = delete; + AgentRegistry& operator=(const AgentRegistry&) = delete; Vector<std::unique_ptr<InspectorAgentBase>> m_agents; +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + Vector<String> m_extraDomains; +#endif }; } // namespace Inspector - -#endif // !defined(InspectorAgentRegistry_h) diff --git a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp index 30a66f7b3..b1984a835 100644 --- a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp +++ b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All Rights Reserved. + * Copyright (C) 2013, 2015 Apple Inc. All Rights Reserved. * Copyright (C) 2011 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -27,133 +27,179 @@ #include "config.h" #include "InspectorBackendDispatcher.h" -#if ENABLE(INSPECTOR) - -#include "InspectorFrontendChannel.h" +#include "InspectorFrontendRouter.h" #include "InspectorValues.h" +#include <wtf/SetForScope.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> namespace Inspector { -InspectorBackendDispatcher::CallbackBase::CallbackBase(PassRefPtr<InspectorBackendDispatcher> backendDispatcher, int id) +SupplementalBackendDispatcher::SupplementalBackendDispatcher(BackendDispatcher& backendDispatcher) : m_backendDispatcher(backendDispatcher) - , m_id(id) - , m_alreadySent(false) { } -bool InspectorBackendDispatcher::CallbackBase::isActive() const +SupplementalBackendDispatcher::~SupplementalBackendDispatcher() +{ +} + +BackendDispatcher::CallbackBase::CallbackBase(Ref<BackendDispatcher>&& backendDispatcher, long requestId) + : m_backendDispatcher(WTFMove(backendDispatcher)) + , m_requestId(requestId) +{ +} + +bool BackendDispatcher::CallbackBase::isActive() const { return !m_alreadySent && m_backendDispatcher->isActive(); } -void InspectorBackendDispatcher::CallbackBase::sendFailure(const ErrorString& error) +void BackendDispatcher::CallbackBase::sendFailure(const ErrorString& error) { ASSERT(error.length()); - sendIfActive(nullptr, error); + + if (m_alreadySent) + return; + + m_alreadySent = true; + + // Immediately send an error message since this is an async response with a single error. + m_backendDispatcher->reportProtocolError(m_requestId, ServerError, error); + m_backendDispatcher->sendPendingErrors(); } -void InspectorBackendDispatcher::CallbackBase::sendIfActive(PassRefPtr<InspectorObject> partialMessage, const ErrorString& invocationError) +void BackendDispatcher::CallbackBase::sendSuccess(RefPtr<InspectorObject>&& partialMessage) { if (m_alreadySent) return; - m_backendDispatcher->sendResponse(m_id, partialMessage, invocationError); m_alreadySent = true; + m_backendDispatcher->sendResponse(m_requestId, WTFMove(partialMessage)); } -PassRefPtr<InspectorBackendDispatcher> InspectorBackendDispatcher::create(InspectorFrontendChannel* inspectorFrontendChannel) +BackendDispatcher::BackendDispatcher(Ref<FrontendRouter>&& router) + : m_frontendRouter(WTFMove(router)) { - return adoptRef(new InspectorBackendDispatcher(inspectorFrontendChannel)); } -void InspectorBackendDispatcher::registerDispatcherForDomain(const String& domain, InspectorSupplementalBackendDispatcher* dispatcher) +Ref<BackendDispatcher> BackendDispatcher::create(Ref<FrontendRouter>&& router) { - auto result = m_dispatchers.add(domain, dispatcher); - ASSERT_UNUSED(result, result.isNewEntry); + return adoptRef(*new BackendDispatcher(WTFMove(router))); } -void InspectorBackendDispatcher::dispatch(const String& message) +bool BackendDispatcher::isActive() const { - Ref<InspectorBackendDispatcher> protect(*this); - - RefPtr<InspectorValue> parsedMessage = InspectorValue::parseJSON(message); - if (!parsedMessage) { - reportProtocolError(nullptr, ParseError, ASCIILiteral("Message must be in JSON format")); - return; - } - - RefPtr<InspectorObject> messageObject = parsedMessage->asObject(); - if (!messageObject) { - reportProtocolError(nullptr, InvalidRequest, ASCIILiteral("Message must be a JSONified object")); - return; - } - - RefPtr<InspectorValue> callIdValue = messageObject->get("id"); - if (!callIdValue) { - reportProtocolError(nullptr, InvalidRequest, ASCIILiteral("'id' property was not found")); - return; - } - - long callId = 0; - if (!callIdValue->asNumber(&callId)) { - reportProtocolError(nullptr, InvalidRequest, ASCIILiteral("The type of 'id' property must be number")); - return; - } - - RefPtr<InspectorValue> methodValue = messageObject->get("method"); - if (!methodValue) { - reportProtocolError(&callId, InvalidRequest, ASCIILiteral("'method' property wasn't found")); - return; - } - - String method; - if (!methodValue->asString(&method)) { - reportProtocolError(&callId, InvalidRequest, ASCIILiteral("The type of 'method' property must be string")); - return; - } - - size_t position = method.find('.'); - if (position == WTF::notFound) { - reportProtocolError(&callId, InvalidRequest, ASCIILiteral("The 'method' property was formatted incorrectly. It should be 'Domain.method'")); - return; - } + return m_frontendRouter->hasFrontends(); +} - String domain = method.substring(0, position); - InspectorSupplementalBackendDispatcher* domainDispatcher = m_dispatchers.get(domain); - if (!domainDispatcher) { - reportProtocolError(&callId, MethodNotFound, "'" + domain + "' domain was not found"); - return; - } +void BackendDispatcher::registerDispatcherForDomain(const String& domain, SupplementalBackendDispatcher* dispatcher) +{ + ASSERT_ARG(dispatcher, dispatcher); - String domainMethod = method.substring(position + 1); - domainDispatcher->dispatch(callId, domainMethod, messageObject.release()); + // FIXME: <https://webkit.org/b/148492> Agents should only register with the backend once, + // and we should re-add the assertion that only one dispatcher is registered per domain. + m_dispatchers.set(domain, dispatcher); } -void InspectorBackendDispatcher::sendResponse(long callId, PassRefPtr<InspectorObject> result, const ErrorString& invocationError) +void BackendDispatcher::dispatch(const String& message) { - if (!m_inspectorFrontendChannel) - return; - - if (invocationError.length()) { - reportProtocolError(&callId, ServerError, invocationError); - return; + Ref<BackendDispatcher> protect(*this); + + ASSERT(!m_protocolErrors.size()); + + long requestId = 0; + RefPtr<InspectorObject> messageObject; + + { + // In case this is a re-entrant call from a nested run loop, we don't want to lose + // the outer request's id just because the inner request is bogus. + SetForScope<std::optional<long>> scopedRequestId(m_currentRequestId, std::nullopt); + + RefPtr<InspectorValue> parsedMessage; + if (!InspectorValue::parseJSON(message, parsedMessage)) { + reportProtocolError(ParseError, ASCIILiteral("Message must be in JSON format")); + sendPendingErrors(); + return; + } + + if (!parsedMessage->asObject(messageObject)) { + reportProtocolError(InvalidRequest, ASCIILiteral("Message must be a JSONified object")); + sendPendingErrors(); + return; + } + + RefPtr<InspectorValue> requestIdValue; + if (!messageObject->getValue(ASCIILiteral("id"), requestIdValue)) { + reportProtocolError(InvalidRequest, ASCIILiteral("'id' property was not found")); + sendPendingErrors(); + return; + } + + if (!requestIdValue->asInteger(requestId)) { + reportProtocolError(InvalidRequest, ASCIILiteral("The type of 'id' property must be integer")); + sendPendingErrors(); + return; + } } - RefPtr<InspectorObject> responseMessage = InspectorObject::create(); - responseMessage->setObject(ASCIILiteral("result"), result); - responseMessage->setNumber(ASCIILiteral("id"), callId); - m_inspectorFrontendChannel->sendMessageToFrontend(responseMessage->toJSONString()); + { + // We could be called re-entrantly from a nested run loop, so restore the previous id. + SetForScope<std::optional<long>> scopedRequestId(m_currentRequestId, requestId); + + RefPtr<InspectorValue> methodValue; + if (!messageObject->getValue(ASCIILiteral("method"), methodValue)) { + reportProtocolError(InvalidRequest, ASCIILiteral("'method' property wasn't found")); + sendPendingErrors(); + return; + } + + String methodString; + if (!methodValue->asString(methodString)) { + reportProtocolError(InvalidRequest, ASCIILiteral("The type of 'method' property must be string")); + sendPendingErrors(); + return; + } + + Vector<String> domainAndMethod; + methodString.split('.', true, domainAndMethod); + if (domainAndMethod.size() != 2 || !domainAndMethod[0].length() || !domainAndMethod[1].length()) { + reportProtocolError(InvalidRequest, ASCIILiteral("The 'method' property was formatted incorrectly. It should be 'Domain.method'")); + sendPendingErrors(); + return; + } + + String domain = domainAndMethod[0]; + SupplementalBackendDispatcher* domainDispatcher = m_dispatchers.get(domain); + if (!domainDispatcher) { + reportProtocolError(MethodNotFound, "'" + domain + "' domain was not found"); + sendPendingErrors(); + return; + } + + String method = domainAndMethod[1]; + domainDispatcher->dispatch(requestId, method, messageObject.releaseNonNull()); + + if (m_protocolErrors.size()) + sendPendingErrors(); + } } -void InspectorBackendDispatcher::reportProtocolError(const long* const callId, CommonErrorCode errorCode, const String& errorMessage) const +void BackendDispatcher::sendResponse(long requestId, RefPtr<InspectorObject>&& result) { - reportProtocolError(callId, errorCode, errorMessage, nullptr); + ASSERT(!m_protocolErrors.size()); + + // The JSON-RPC 2.0 specification requires that the "error" member have the value 'null' + // if no error occurred during an invocation, but we do not include it at all. + Ref<InspectorObject> responseMessage = InspectorObject::create(); + responseMessage->setObject(ASCIILiteral("result"), WTFMove(result)); + responseMessage->setInteger(ASCIILiteral("id"), requestId); + m_frontendRouter->sendResponse(responseMessage->toJSONString()); } -void InspectorBackendDispatcher::reportProtocolError(const long* const callId, CommonErrorCode errorCode, const String& errorMessage, PassRefPtr<InspectorArray> data) const +void BackendDispatcher::sendPendingErrors() { + // These error codes are specified in JSON-RPC 2.0, Section 5.1. static const int errorCodes[] = { -32700, // ParseError -32600, // InvalidRequest @@ -163,102 +209,141 @@ void InspectorBackendDispatcher::reportProtocolError(const long* const callId, C -32000, // ServerError }; - ASSERT(errorCode >= 0); - ASSERT((unsigned)errorCode < WTF_ARRAY_LENGTH(errorCodes)); - ASSERT(errorCodes[errorCode]); + // To construct the error object, only use the last error's code and message. + // Per JSON-RPC 2.0, Section 5.1, the 'data' member may contain nested errors, + // but only one top-level Error object should be sent per request. + CommonErrorCode errorCode = InternalError; + String errorMessage; + Ref<InspectorArray> payload = InspectorArray::create(); + + for (auto& data : m_protocolErrors) { + errorCode = std::get<0>(data); + errorMessage = std::get<1>(data); + + ASSERT_ARG(errorCode, (unsigned)errorCode < WTF_ARRAY_LENGTH(errorCodes)); + ASSERT_ARG(errorCode, errorCodes[errorCode]); + + Ref<InspectorObject> error = InspectorObject::create(); + error->setInteger(ASCIILiteral("code"), errorCodes[errorCode]); + error->setString(ASCIILiteral("message"), errorMessage); + payload->pushObject(WTFMove(error)); + } - if (!m_inspectorFrontendChannel) - return; + Ref<InspectorObject> topLevelError = InspectorObject::create(); + topLevelError->setInteger(ASCIILiteral("code"), errorCodes[errorCode]); + topLevelError->setString(ASCIILiteral("message"), errorMessage); + topLevelError->setArray(ASCIILiteral("data"), WTFMove(payload)); + + Ref<InspectorObject> message = InspectorObject::create(); + message->setObject(ASCIILiteral("error"), WTFMove(topLevelError)); + if (m_currentRequestId) + message->setInteger(ASCIILiteral("id"), m_currentRequestId.value()); + else { + // The 'null' value for an unknown id is specified in JSON-RPC 2.0, Section 5. + message->setValue(ASCIILiteral("id"), InspectorValue::null()); + } - RefPtr<InspectorObject> error = InspectorObject::create(); - error->setNumber(ASCIILiteral("code"), errorCodes[errorCode]); - error->setString(ASCIILiteral("message"), errorMessage); - if (data) - error->setArray(ASCIILiteral("data"), data); + m_frontendRouter->sendResponse(message->toJSONString()); - RefPtr<InspectorObject> message = InspectorObject::create(); - message->setObject(ASCIILiteral("error"), error.release()); - if (callId) - message->setNumber(ASCIILiteral("id"), *callId); - else - message->setValue(ASCIILiteral("id"), InspectorValue::null()); + m_protocolErrors.clear(); + m_currentRequestId = std::nullopt; +} + +void BackendDispatcher::reportProtocolError(CommonErrorCode errorCode, const String& errorMessage) +{ + reportProtocolError(m_currentRequestId, errorCode, errorMessage); +} + +void BackendDispatcher::reportProtocolError(std::optional<long> relatedRequestId, CommonErrorCode errorCode, const String& errorMessage) +{ + ASSERT_ARG(errorCode, errorCode >= 0); + + // If the error was reported from an async callback, then no request id will be registered yet. + if (!m_currentRequestId) + m_currentRequestId = relatedRequestId; - m_inspectorFrontendChannel->sendMessageToFrontend(message->toJSONString()); + m_protocolErrors.append(std::tuple<CommonErrorCode, String>(errorCode, errorMessage)); } -template<typename ReturnValueType, typename ValueType, typename DefaultValueType> -static ReturnValueType getPropertyValue(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors, DefaultValueType defaultValue, bool (*asMethod)(InspectorValue*, ValueType*), const char* typeName) +#if PLATFORM(MAC) +void BackendDispatcher::reportProtocolError(WTF::DeprecatedOptional<long> relatedRequestId, CommonErrorCode errorCode, const String& errorMessage) { - ASSERT(protocolErrors); + if (relatedRequestId) + reportProtocolError(relatedRequestId.value(), errorCode, errorMessage); + else + reportProtocolError(std::nullopt, errorCode, errorMessage); +} +#endif - ValueType value = defaultValue; - if (valueFound) - *valueFound = false; +template<typename T> +T BackendDispatcher::getPropertyValue(InspectorObject* object, const String& name, bool* out_optionalValueFound, T defaultValue, std::function<bool(InspectorValue&, T&)> asMethod, const char* typeName) +{ + T result(defaultValue); + // out_optionalValueFound signals to the caller whether an optional property was found. + // if out_optionalValueFound == nullptr, then this is a required property. + if (out_optionalValueFound) + *out_optionalValueFound = false; if (!object) { - if (!valueFound) - protocolErrors->pushString(String::format("'params' object must contain required parameter '%s' with type '%s'.", name.utf8().data(), typeName)); - return value; + if (!out_optionalValueFound) + reportProtocolError(BackendDispatcher::InvalidParams, String::format("'params' object must contain required parameter '%s' with type '%s'.", name.utf8().data(), typeName)); + return result; } - InspectorObject::const_iterator end = object->end(); - InspectorObject::const_iterator valueIterator = object->find(name); - if (valueIterator == end) { - if (!valueFound) - protocolErrors->pushString(String::format("Parameter '%s' with type '%s' was not found.", name.utf8().data(), typeName)); - return value; + auto findResult = object->find(name); + if (findResult == object->end()) { + if (!out_optionalValueFound) + reportProtocolError(BackendDispatcher::InvalidParams, String::format("Parameter '%s' with type '%s' was not found.", name.utf8().data(), typeName)); + return result; } - if (!asMethod(valueIterator->value.get(), &value)) { - protocolErrors->pushString(String::format("Parameter '%s' has wrong type. It must be '%s'.", name.utf8().data(), typeName)); - return value; + if (!asMethod(*findResult->value, result)) { + reportProtocolError(BackendDispatcher::InvalidParams, String::format("Parameter '%s' has wrong type. It must be '%s'.", name.utf8().data(), typeName)); + return result; } - if (valueFound) - *valueFound = true; + if (out_optionalValueFound) + *out_optionalValueFound = true; - return value; + return result; } -struct AsMethodBridges { - static bool asInt(InspectorValue* value, int* output) { return value->asNumber(output); } - static bool asDouble(InspectorValue* value, double* output) { return value->asNumber(output); } - static bool asString(InspectorValue* value, String* output) { return value->asString(output); } - static bool asBoolean(InspectorValue* value, bool* output) { return value->asBoolean(output); } - static bool asObject(InspectorValue* value, RefPtr<InspectorObject>* output) { return value->asObject(output); } - static bool asArray(InspectorValue* value, RefPtr<InspectorArray>* output) { return value->asArray(output); } -}; +static bool castToInteger(InspectorValue& value, int& result) { return value.asInteger(result); } +static bool castToNumber(InspectorValue& value, double& result) { return value.asDouble(result); } -int InspectorBackendDispatcher::getInt(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) +int BackendDispatcher::getInteger(InspectorObject* object, const String& name, bool* valueFound) { - return getPropertyValue<int, int, int>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asInt, "Number"); + return getPropertyValue<int>(object, name, valueFound, 0, &castToInteger, "Integer"); } -double InspectorBackendDispatcher::getDouble(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) +double BackendDispatcher::getDouble(InspectorObject* object, const String& name, bool* valueFound) { - return getPropertyValue<double, double, double>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asDouble, "Number"); + return getPropertyValue<double>(object, name, valueFound, 0, &castToNumber, "Number"); } -String InspectorBackendDispatcher::getString(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) +String BackendDispatcher::getString(InspectorObject* object, const String& name, bool* valueFound) { - return getPropertyValue<String, String, String>(object, name, valueFound, protocolErrors, "", AsMethodBridges::asString, "String"); + return getPropertyValue<String>(object, name, valueFound, "", &InspectorValue::asString, "String"); } -bool InspectorBackendDispatcher::getBoolean(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) +bool BackendDispatcher::getBoolean(InspectorObject* object, const String& name, bool* valueFound) { - return getPropertyValue<bool, bool, bool>(object, name, valueFound, protocolErrors, false, AsMethodBridges::asBoolean, "Boolean"); + return getPropertyValue<bool>(object, name, valueFound, false, &InspectorValue::asBoolean, "Boolean"); } -PassRefPtr<InspectorObject> InspectorBackendDispatcher::getObject(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) +RefPtr<InspectorObject> BackendDispatcher::getObject(InspectorObject* object, const String& name, bool* valueFound) { - return getPropertyValue<PassRefPtr<InspectorObject>, RefPtr<InspectorObject>, InspectorObject*>(object, name, valueFound, protocolErrors, nullptr, AsMethodBridges::asObject, "Object"); + return getPropertyValue<RefPtr<InspectorObject>>(object, name, valueFound, nullptr, &InspectorValue::asObject, "Object"); } -PassRefPtr<InspectorArray> InspectorBackendDispatcher::getArray(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) +RefPtr<InspectorArray> BackendDispatcher::getArray(InspectorObject* object, const String& name, bool* valueFound) { - return getPropertyValue<PassRefPtr<InspectorArray>, RefPtr<InspectorArray>, InspectorArray*>(object, name, valueFound, protocolErrors, nullptr, AsMethodBridges::asArray, "Array"); + return getPropertyValue<RefPtr<InspectorArray>>(object, name, valueFound, nullptr, &InspectorValue::asArray, "Array"); } -} // namespace Inspector +RefPtr<InspectorValue> BackendDispatcher::getValue(InspectorObject* object, const String& name, bool* valueFound) +{ + return getPropertyValue<RefPtr<InspectorValue>>(object, name, valueFound, nullptr, &InspectorValue::asValue, "Value"); +} -#endif // ENABLE(INSPECTOR) +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h index 0a55a1c96..db976bd96 100644 --- a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h +++ b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All Rights Reserved. + * Copyright (C) 2013, 2015 Apple Inc. All Rights Reserved. * Copyright (C) 2011 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -24,52 +24,53 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorBackendDispatcher_h -#define InspectorBackendDispatcher_h +#pragma once -#include "InspectorValues.h" -#include <wtf/PassRefPtr.h> +#include "InspectorFrontendRouter.h" +#include "InspectorProtocolTypes.h" +#include <wtf/DeprecatedOptional.h> +#include <wtf/Optional.h> #include <wtf/RefCounted.h> #include <wtf/text/WTFString.h> namespace Inspector { -class InspectorBackendDispatcher; -class InspectorFrontendChannel; +class BackendDispatcher; + typedef String ErrorString; -class InspectorSupplementalBackendDispatcher : public RefCounted<InspectorSupplementalBackendDispatcher> { +class JS_EXPORT_PRIVATE SupplementalBackendDispatcher : public RefCounted<SupplementalBackendDispatcher> { public: - InspectorSupplementalBackendDispatcher(InspectorBackendDispatcher* backendDispatcher) : m_backendDispatcher(backendDispatcher) { } - virtual ~InspectorSupplementalBackendDispatcher() { } - virtual void dispatch(long callId, const String& method, PassRefPtr<InspectorObject> message) = 0; + SupplementalBackendDispatcher(BackendDispatcher&); + virtual ~SupplementalBackendDispatcher(); + virtual void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) = 0; protected: - RefPtr<InspectorBackendDispatcher> m_backendDispatcher; + Ref<BackendDispatcher> m_backendDispatcher; }; -class JS_EXPORT_PRIVATE InspectorBackendDispatcher : public RefCounted<InspectorBackendDispatcher> { +class JS_EXPORT_PRIVATE BackendDispatcher : public RefCounted<BackendDispatcher> { public: - static PassRefPtr<InspectorBackendDispatcher> create(InspectorFrontendChannel*); + static Ref<BackendDispatcher> create(Ref<FrontendRouter>&&); class JS_EXPORT_PRIVATE CallbackBase : public RefCounted<CallbackBase> { public: - CallbackBase(PassRefPtr<InspectorBackendDispatcher>, int id); + CallbackBase(Ref<BackendDispatcher>&&, long requestId); bool isActive() const; - void sendFailure(const ErrorString&); void disable() { m_alreadySent = true; } - protected: - void sendIfActive(PassRefPtr<InspectorObject> partialMessage, const ErrorString& invocationError); + void sendSuccess(RefPtr<InspectorObject>&&); + void sendFailure(const ErrorString&); private: - RefPtr<InspectorBackendDispatcher> m_backendDispatcher; - int m_id; - bool m_alreadySent; + Ref<BackendDispatcher> m_backendDispatcher; + long m_requestId; + bool m_alreadySent { false }; }; - void clearFrontend() { m_inspectorFrontendChannel = nullptr; } - bool isActive() const { return !!m_inspectorFrontendChannel; } + bool isActive() const; + + bool hasProtocolErrors() const { return m_protocolErrors.size() > 0; } enum CommonErrorCode { ParseError = 0, @@ -80,26 +81,46 @@ public: ServerError }; - void registerDispatcherForDomain(const String& domain, InspectorSupplementalBackendDispatcher*); + void registerDispatcherForDomain(const String& domain, SupplementalBackendDispatcher*); void dispatch(const String& message); - void sendResponse(long callId, PassRefPtr<InspectorObject> result, const ErrorString& invocationError); - void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage) const; - void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage, PassRefPtr<InspectorArray> data) const; - static int getInt(InspectorObject*, const String& name, bool* valueFound, InspectorArray* protocolErrors); - static double getDouble(InspectorObject*, const String& name, bool* valueFound, InspectorArray* protocolErrors); - static String getString(InspectorObject*, const String& name, bool* valueFound, InspectorArray* protocolErrors); - static bool getBoolean(InspectorObject*, const String& name, bool* valueFound, InspectorArray* protocolErrors); - static PassRefPtr<InspectorObject> getObject(InspectorObject*, const String& name, bool* valueFound, InspectorArray* protocolErrors); - static PassRefPtr<InspectorArray> getArray(InspectorObject*, const String& name, bool* valueFound, InspectorArray* protocolErrors); + void sendResponse(long requestId, RefPtr<InspectorObject>&& result); + void sendPendingErrors(); + + void reportProtocolError(CommonErrorCode, const String& errorMessage); + void reportProtocolError(std::optional<long> relatedRequestId, CommonErrorCode, const String& errorMessage); + + template<typename T> + WTF_HIDDEN_DECLARATION + T getPropertyValue(InspectorObject*, const String& name, bool* out_optionalValueFound, T defaultValue, std::function<bool(InspectorValue&, T&)>, const char* typeName); + + int getInteger(InspectorObject*, const String& name, bool* valueFound); + double getDouble(InspectorObject*, const String& name, bool* valueFound); + String getString(InspectorObject*, const String& name, bool* valueFound); + bool getBoolean(InspectorObject*, const String& name, bool* valueFound); + RefPtr<InspectorValue> getValue(InspectorObject*, const String& name, bool* valueFound); + RefPtr<InspectorObject> getObject(InspectorObject*, const String& name, bool* valueFound); + RefPtr<InspectorArray> getArray(InspectorObject*, const String& name, bool* valueFound); private: - InspectorBackendDispatcher(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { } + BackendDispatcher(Ref<FrontendRouter>&&); + +#if PLATFORM(MAC) + // This is necessary for some versions of Safari. Remove it when those versions of Safari are no longer supported. + void reportProtocolError(WTF::DeprecatedOptional<long> relatedRequestId, CommonErrorCode, const String& errorMessage); +#endif + + Ref<FrontendRouter> m_frontendRouter; + HashMap<String, SupplementalBackendDispatcher*> m_dispatchers; - InspectorFrontendChannel* m_inspectorFrontendChannel; - HashMap<String, InspectorSupplementalBackendDispatcher*> m_dispatchers; + // Protocol errors reported for the top-level request being processed. + // If processing a request triggers async responses, then any related errors will + // be attributed to the top-level request, but generate separate error messages. + Vector<std::tuple<CommonErrorCode, String>> m_protocolErrors; + + // For synchronously handled requests, avoid plumbing requestId through every + // call that could potentially fail with a protocol error. + std::optional<long> m_currentRequestId { std::nullopt }; }; } // namespace Inspector - -#endif // !defined(InspectorBackendDispatcher_h) diff --git a/Source/JavaScriptCore/inspector/InspectorEnvironment.h b/Source/JavaScriptCore/inspector/InspectorEnvironment.h index 327a9f89a..3b60c1b4f 100644 --- a/Source/JavaScriptCore/inspector/InspectorEnvironment.h +++ b/Source/JavaScriptCore/inspector/InspectorEnvironment.h @@ -23,19 +23,25 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorEnvironment_h -#define InspectorEnvironment_h +#pragma once #include "CallData.h" +namespace WTF { +class Stopwatch; +} + namespace JSC { +class Exception; class SourceCode; +class VM; } namespace Inspector { -typedef JSC::JSValue (*InspectorFunctionCallHandler)(JSC::ExecState* exec, JSC::JSValue functionObject, JSC::CallType callType, const JSC::CallData& callData, JSC::JSValue thisValue, const JSC::ArgList& args); -typedef JSC::JSValue (*InspectorEvaluateHandler)(JSC::ExecState*, const JSC::SourceCode&, JSC::JSValue thisValue, JSC::JSValue* exception); +class ScriptDebugServer; +typedef JSC::JSValue (*InspectorFunctionCallHandler)(JSC::ExecState* exec, JSC::JSValue functionObject, JSC::CallType callType, const JSC::CallData& callData, JSC::JSValue thisValue, const JSC::ArgList& args, NakedPtr<JSC::Exception>& returnedException); +typedef JSC::JSValue (*InspectorEvaluateHandler)(JSC::ExecState*, const JSC::SourceCode&, JSC::JSValue thisValue, NakedPtr<JSC::Exception>& returnedException); class InspectorEnvironment { public: @@ -44,10 +50,10 @@ public: virtual bool canAccessInspectedScriptState(JSC::ExecState*) const = 0; virtual InspectorFunctionCallHandler functionCallHandler() const = 0; virtual InspectorEvaluateHandler evaluateHandler() const = 0; - virtual void willCallInjectedScriptFunction(JSC::ExecState*, const String& scriptName, int scriptLine) = 0; - virtual void didCallInjectedScriptFunction() = 0; + virtual void frontendInitialized() = 0; + virtual Ref<WTF::Stopwatch> executionStopwatch() = 0; + virtual ScriptDebugServer& scriptDebugServer() = 0; + virtual JSC::VM& vm() = 0; }; } // namespace Inspector - -#endif // !defined(InspectorEnvironment_h) diff --git a/Source/JavaScriptCore/inspector/InspectorFrontendChannel.h b/Source/JavaScriptCore/inspector/InspectorFrontendChannel.h index fa0a8eae8..3abc1d285 100644 --- a/Source/JavaScriptCore/inspector/InspectorFrontendChannel.h +++ b/Source/JavaScriptCore/inspector/InspectorFrontendChannel.h @@ -23,19 +23,26 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorFrontendChannel_h -#define InspectorFrontendChannel_h +#pragma once #include <wtf/text/WTFString.h> namespace Inspector { -class InspectorFrontendChannel { +// Represents a one-way connection from an Inspection or Automation target to +// a local or remote controller (such as a debugger or UI automation script). + +class FrontendChannel { public: - virtual ~InspectorFrontendChannel() { } - virtual bool sendMessageToFrontend(const String& message) = 0; + + enum class ConnectionType { + Remote, + Local + }; + + virtual ~FrontendChannel() { } + virtual ConnectionType connectionType() const = 0; + virtual void sendMessageToFrontend(const String& message) = 0; }; } // namespace Inspector - -#endif // !defined(InspectorFrontendChannel_h) diff --git a/Source/JavaScriptCore/inspector/InspectorFrontendRouter.cpp b/Source/JavaScriptCore/inspector/InspectorFrontendRouter.cpp new file mode 100644 index 000000000..65f8525a2 --- /dev/null +++ b/Source/JavaScriptCore/inspector/InspectorFrontendRouter.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InspectorFrontendRouter.h" + +#include "InspectorFrontendChannel.h" +#include <wtf/Assertions.h> + +namespace Inspector { + +Ref<FrontendRouter> FrontendRouter::create() +{ + return adoptRef(*new FrontendRouter); +} + +void FrontendRouter::connectFrontend(FrontendChannel* connection) +{ + ASSERT_ARG(connection, connection); + + if (m_connections.contains(connection)) { + ASSERT_NOT_REACHED(); + return; + } + + m_connections.append(connection); +} + +void FrontendRouter::disconnectFrontend(FrontendChannel* connection) +{ + ASSERT_ARG(connection, connection); + + if (!m_connections.contains(connection)) { + ASSERT_NOT_REACHED(); + return; + } + + m_connections.removeFirst(connection); +} + +void FrontendRouter::disconnectAllFrontends() +{ + m_connections.clear(); +} + +bool FrontendRouter::hasLocalFrontend() const +{ + for (auto* connection : m_connections) { + if (connection->connectionType() == FrontendChannel::ConnectionType::Local) + return true; + } + + return false; +} + +bool FrontendRouter::hasRemoteFrontend() const +{ + for (auto* connection : m_connections) { + if (connection->connectionType() == FrontendChannel::ConnectionType::Remote) + return true; + } + + return false; +} + +void FrontendRouter::sendEvent(const String& message) const +{ + for (auto* connection : m_connections) + connection->sendMessageToFrontend(message); +} + +void FrontendRouter::sendResponse(const String& message) const +{ + // FIXME: send responses to the appropriate frontend. + for (auto* connection : m_connections) + connection->sendMessageToFrontend(message); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InspectorFrontendRouter.h b/Source/JavaScriptCore/inspector/InspectorFrontendRouter.h new file mode 100644 index 000000000..5872b6da8 --- /dev/null +++ b/Source/JavaScriptCore/inspector/InspectorFrontendRouter.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendChannel; + +class JS_EXPORT_PRIVATE FrontendRouter : public RefCounted<FrontendRouter> { +public: + static Ref<FrontendRouter> create(); + + bool hasFrontends() const { return !m_connections.isEmpty(); } + bool hasLocalFrontend() const; + bool hasRemoteFrontend() const; + + unsigned frontendCount() const { return m_connections.size(); } + + void connectFrontend(FrontendChannel*); + void disconnectFrontend(FrontendChannel*); + void disconnectAllFrontends(); + + void sendEvent(const String& message) const; + void sendResponse(const String& message) const; + +private: + Vector<FrontendChannel*, 2> m_connections; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InspectorProtocolTypes.h b/Source/JavaScriptCore/inspector/InspectorProtocolTypes.h new file mode 100644 index 000000000..248e58a96 --- /dev/null +++ b/Source/JavaScriptCore/inspector/InspectorProtocolTypes.h @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2013 Apple Inc. All Rights Reserved. + * Copyright (C) 2011 The Chromium Authors. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorValues.h" +#include <wtf/Assertions.h> + +namespace Inspector { + +namespace Protocol { + +template<typename T> struct BindingTraits; + +template<typename T> +class OptOutput { +public: + OptOutput() : m_assigned(false) { } + + void operator=(T value) + { + m_value = value; + m_assigned = true; + } + + bool isAssigned() const { return m_assigned; } + + T getValue() + { + ASSERT(isAssigned()); + return m_value; + } + +private: + T m_value; + bool m_assigned; + + WTF_MAKE_NONCOPYABLE(OptOutput); +}; + +template<typename T> +class Array : public InspectorArrayBase { +private: + Array() { } + + InspectorArray& openAccessors() + { + COMPILE_ASSERT(sizeof(InspectorArray) == sizeof(Array<T>), cannot_cast); + return *static_cast<InspectorArray*>(static_cast<InspectorArrayBase*>(this)); + } + +public: + void addItem(Ref<T>&& value) + { + openAccessors().pushValue(&value.get()); + } + + void addItem(RefPtr<T>&& value) + { + openAccessors().pushValue(WTFMove(value)); + } + + void addItem(const String& value) + { + openAccessors().pushString(value); + } + + void addItem(int value) + { + openAccessors().pushInteger(value); + } + + void addItem(double value) + { + openAccessors().pushDouble(value); + } + + static Ref<Array<T>> create() + { + return adoptRef(*new Array<T>()); + } +}; + +// Helper methods for Protocol and other Inspector types are provided by +// specializations of BindingTraits<T>. Some are generated for protocol types. + +template<typename T> +struct BindingTraits { + typedef T BindingType; + + static void push(InspectorArray&, BindingType&); + static InspectorValue::Type typeTag(); + static RefPtr<T> runtimeCast(RefPtr<InspectorObject>&&); +#if !ASSERT_DISABLED + static void assertValueHasExpectedType(InspectorValue*); +#endif // !ASSERT_DISABLED +}; + +template<InspectorValue::Type TYPE> +struct PrimitiveBindingTraits { +#if !ASSERT_DISABLED + static void assertValueHasExpectedType(InspectorValue* value) + { + ASSERT_ARG(value, value && value->type() == TYPE); + } +#endif // !ASSERT_DISABLED +}; + +template<typename T> +struct BindingTraits<Protocol::Array<T>> { + static RefPtr<Array<T>> runtimeCast(RefPtr<InspectorValue>&& value) + { + ASSERT_ARG(value, value); + RefPtr<InspectorArray> array; + bool castSucceeded = value->asArray(array); + ASSERT_UNUSED(castSucceeded, castSucceeded); +#if !ASSERT_DISABLED + assertValueHasExpectedType(array.get()); +#endif // !ASSERT_DISABLED + COMPILE_ASSERT(sizeof(Array<T>) == sizeof(InspectorArray), type_cast_problem); + return static_cast<Array<T>*>(static_cast<InspectorArrayBase*>(array.get())); + } + +#if !ASSERT_DISABLED + static void assertValueHasExpectedType(InspectorValue* value) + { + ASSERT_ARG(value, value); + RefPtr<InspectorArray> array; + bool castSucceeded = value->asArray(array); + ASSERT_UNUSED(castSucceeded, castSucceeded); + for (unsigned i = 0; i < array->length(); i++) + BindingTraits<T>::assertValueHasExpectedType(array->get(i).get()); + } +#endif // !ASSERT_DISABLED +}; + +template<> +struct BindingTraits<InspectorValue> { +#if !ASSERT_DISABLED + static void assertValueHasExpectedType(InspectorValue*) + { + } +#endif // !ASSERT_DISABLED +}; + +template<> struct BindingTraits<InspectorArray> : public PrimitiveBindingTraits<InspectorValue::Type::Array> { }; +template<> struct BindingTraits<InspectorObject> : public PrimitiveBindingTraits<InspectorValue::Type::Object> { }; +template<> struct BindingTraits<String> : public PrimitiveBindingTraits<InspectorValue::Type::String> { }; +template<> struct BindingTraits<bool> : public PrimitiveBindingTraits<InspectorValue::Type::Boolean> { }; +template<> struct BindingTraits<double> : public PrimitiveBindingTraits<InspectorValue::Type::Double> { }; +template<> struct BindingTraits<int> : public PrimitiveBindingTraits<InspectorValue::Type::Integer> { }; + +} // namespace Protocol + +using Protocol::BindingTraits; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InspectorTypeBuilder.h b/Source/JavaScriptCore/inspector/InspectorTypeBuilder.h deleted file mode 100644 index 8ea76ec90..000000000 --- a/Source/JavaScriptCore/inspector/InspectorTypeBuilder.h +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All Rights Reserved. - * Copyright (C) 2011 The Chromium Authors. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 InspectorTypeBuilder_h -#define InspectorTypeBuilder_h - -#if ENABLE(INSPECTOR) - -#include "InspectorValues.h" -#include <wtf/Assertions.h> -#include <wtf/PassRefPtr.h> - -namespace Inspector { - -namespace TypeBuilder { - -template<typename T> -class OptOutput { -public: - OptOutput() : m_assigned(false) { } - - void operator=(T value) - { - m_value = value; - m_assigned = true; - } - - bool isAssigned() const { return m_assigned; } - - T getValue() - { - ASSERT(isAssigned()); - return m_value; - } - -private: - T m_value; - bool m_assigned; - - WTF_MAKE_NONCOPYABLE(OptOutput); -}; - - -// A small transient wrapper around int type, that can be used as a funciton parameter type -// cleverly disallowing C++ implicit casts from float or double. -class ExactlyInt { -public: - template<typename T> - ExactlyInt(T t) : m_value(cast_to_int<T>(t)) { } - ExactlyInt() { } - - operator int() { return m_value; } - -private: - int m_value; - - template<typename T> - static int cast_to_int(T) { return T::default_case_cast_is_not_supported(); } -}; - -template<> -inline int ExactlyInt::cast_to_int<int>(int i) { return i; } - -template<> -inline int ExactlyInt::cast_to_int<unsigned int>(unsigned int i) { return i; } - -#if !ASSERT_DISABLED -class RuntimeCastHelper { -public: - template<InspectorValue::Type TYPE> - static void assertType(InspectorValue* value) - { - ASSERT(value->type() == TYPE); - } - - static void assertAny(InspectorValue*) - { - } - - static void assertInt(InspectorValue* value) - { - double v; - bool castRes = value->asNumber(&v); - ASSERT_UNUSED(castRes, castRes); - ASSERT(static_cast<double>(static_cast<int>(v)) == v); - } -}; -#endif - - -// This class provides "Traits" type for the input type T. It is programmed using C++ template specialization -// technique. By default it simply takes "ItemTraits" type from T, but it doesn't work with the base types. -template<typename T> -struct ArrayItemHelper { - typedef typename T::ItemTraits Traits; -}; - -template<typename T> -class Array : public InspectorArrayBase { -private: - Array() { } - - InspectorArray* openAccessors() - { - COMPILE_ASSERT(sizeof(InspectorArray) == sizeof(Array<T>), cannot_cast); - return static_cast<InspectorArray*>(static_cast<InspectorArrayBase*>(this)); - } - -public: - void addItem(PassRefPtr<T> value) - { - ArrayItemHelper<T>::Traits::pushRefPtr(this->openAccessors(), value); - } - - void addItem(T value) - { - ArrayItemHelper<T>::Traits::pushRaw(this->openAccessors(), value); - } - - static PassRefPtr<Array<T>> create() - { - return adoptRef(new Array<T>()); - } - - static PassRefPtr<Array<T>> runtimeCast(PassRefPtr<InspectorValue> value) - { - RefPtr<InspectorArray> array; - bool castRes = value->asArray(&array); - ASSERT_UNUSED(castRes, castRes); -#if !ASSERT_DISABLED - assertCorrectValue(array.get()); -#endif // !ASSERT_DISABLED - COMPILE_ASSERT(sizeof(Array<T>) == sizeof(InspectorArray), type_cast_problem); - return static_cast<Array<T>*>(static_cast<InspectorArrayBase*>(array.get())); - } - -#if !ASSERT_DISABLED - static void assertCorrectValue(InspectorValue* value) - { - RefPtr<InspectorArray> array; - bool castRes = value->asArray(&array); - ASSERT_UNUSED(castRes, castRes); - for (unsigned i = 0; i < array->length(); i++) - ArrayItemHelper<T>::Traits::template assertCorrectValue<T>(array->get(i).get()); - } -#endif // !ASSERT_DISABLED -}; - -struct StructItemTraits { - static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value) - { - array->pushValue(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - T::assertCorrectValue(value); - } -#endif // !ASSERT_DISABLED -}; - -template<> -struct ArrayItemHelper<String> { - struct Traits { - static void pushRaw(InspectorArray* array, const String& value) - { - array->pushString(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - RuntimeCastHelper::assertType<InspectorValue::TypeString>(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -template<> -struct ArrayItemHelper<int> { - struct Traits { - static void pushRaw(InspectorArray* array, int value) - { - array->pushInt(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - RuntimeCastHelper::assertInt(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -template<> -struct ArrayItemHelper<double> { - struct Traits { - static void pushRaw(InspectorArray* array, double value) - { - array->pushNumber(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - RuntimeCastHelper::assertType<InspectorValue::TypeNumber>(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -template<> -struct ArrayItemHelper<bool> { - struct Traits { - static void pushRaw(InspectorArray* array, bool value) - { - array->pushBoolean(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - RuntimeCastHelper::assertType<InspectorValue::TypeBoolean>(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -template<> -struct ArrayItemHelper<InspectorValue> { - struct Traits { - static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value) - { - array->pushValue(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - RuntimeCastHelper::assertAny(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -template<> -struct ArrayItemHelper<InspectorObject> { - struct Traits { - static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value) - { - array->pushValue(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - RuntimeCastHelper::assertType<InspectorValue::TypeObject>(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -template<> -struct ArrayItemHelper<InspectorArray> { - struct Traits { - static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorArray> value) - { - array->pushArray(value); - } - -#if !ASSERT_DISABLED - template<typename T> - static void assertCorrectValue(InspectorValue* value) - { - RuntimeCastHelper::assertType<InspectorValue::TypeArray>(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -template<typename T> -struct ArrayItemHelper<TypeBuilder::Array<T>> { - struct Traits { - static void pushRefPtr(InspectorArray* array, PassRefPtr<TypeBuilder::Array<T>> value) - { - array->pushValue(value); - } - -#if !ASSERT_DISABLED - template<typename S> - static void assertCorrectValue(InspectorValue* value) - { - S::assertCorrectValue(value); - } -#endif // !ASSERT_DISABLED - }; -}; - -} // namespace TypeBuilder - -} // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(InspectorTypeBuilder_h) diff --git a/Source/JavaScriptCore/inspector/InspectorValues.cpp b/Source/JavaScriptCore/inspector/InspectorValues.cpp index 4cdf71e92..14fb7e70d 100644 --- a/Source/JavaScriptCore/inspector/InspectorValues.cpp +++ b/Source/JavaScriptCore/inspector/InspectorValues.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2010 Google Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -63,8 +64,10 @@ const char* const falseString = "false"; bool parseConstToken(const UChar* start, const UChar* end, const UChar** tokenEnd, const char* token) { while (start < end && *token != '\0' && *start++ == *token++) { } + if (*token != '\0') return false; + *tokenEnd = start; return true; } @@ -73,16 +76,20 @@ bool readInt(const UChar* start, const UChar* end, const UChar** tokenEnd, bool { if (start == end) return false; + bool haveLeadingZero = '0' == *start; int length = 0; while (start < end && '0' <= *start && *start <= '9') { ++start; ++length; } + if (!length) return false; + if (!canHaveLeadingZeros && length > 1 && haveLeadingZero) return false; + *tokenEnd = start; return true; } @@ -93,12 +100,14 @@ bool parseNumberToken(const UChar* start, const UChar* end, const UChar** tokenE // According to RFC4627, a valid number is: [minus] int [frac] [exp] if (start == end) return false; + UChar c = *start; if ('-' == c) ++start; if (!readInt(start, end, &start, false)) return false; + if (start == end) { *tokenEnd = start; return true; @@ -140,11 +149,12 @@ bool readHexDigits(const UChar* start, const UChar* end, const UChar** tokenEnd, { if (end - start < digits) return false; + for (int i = 0; i < digits; ++i) { - UChar c = *start++; - if (!(('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'))) + if (!isASCIIHexDigit(*start++)) return false; } + *tokenEnd = start; return true; } @@ -183,6 +193,7 @@ bool parseStringToken(const UChar* start, const UChar* end, const UChar** tokenE return true; } } + return false; } @@ -246,27 +257,16 @@ Token parseToken(const UChar* start, const UChar* end, const UChar** tokenStart, return STRING; break; } - return INVALID_TOKEN; -} -inline int hexToInt(UChar c) -{ - if ('0' <= c && c <= '9') - return c - '0'; - if ('A' <= c && c <= 'F') - return c - 'A' + 10; - if ('a' <= c && c <= 'f') - return c - 'a' + 10; - ASSERT_NOT_REACHED(); - return 0; + return INVALID_TOKEN; } -bool decodeString(const UChar* start, const UChar* end, StringBuilder* output) +bool decodeString(const UChar* start, const UChar* end, StringBuilder& output) { while (start < end) { UChar c = *start++; if ('\\' != c) { - output->append(c); + output.append(c); continue; } c = *start++; @@ -294,45 +294,45 @@ bool decodeString(const UChar* start, const UChar* end, StringBuilder* output) c = '\v'; break; case 'x': - c = (hexToInt(*start) << 4) + - hexToInt(*(start + 1)); + c = toASCIIHexValue(start[0], start[1]); start += 2; break; case 'u': - c = (hexToInt(*start) << 12) + - (hexToInt(*(start + 1)) << 8) + - (hexToInt(*(start + 2)) << 4) + - hexToInt(*(start + 3)); + c = toASCIIHexValue(start[0], start[1]) << 8 | toASCIIHexValue(start[2], start[3]); start += 4; break; default: return false; } - output->append(c); + output.append(c); } + return true; } -bool decodeString(const UChar* start, const UChar* end, String* output) +bool decodeString(const UChar* start, const UChar* end, String& output) { if (start == end) { - *output = ""; + output = emptyString(); return true; } + if (start > end) return false; + StringBuilder buffer; buffer.reserveCapacity(end - start); - if (!decodeString(start, end, &buffer)) + if (!decodeString(start, end, buffer)) return false; - *output = buffer.toString(); + + output = buffer.toString(); return true; } -PassRefPtr<InspectorValue> buildValue(const UChar* start, const UChar* end, const UChar** valueTokenEnd, int depth) +RefPtr<InspectorValue> buildValue(const UChar* start, const UChar* end, const UChar** valueTokenEnd, int depth) { if (depth > stackLimit) - return 0; + return nullptr; RefPtr<InspectorValue> result; const UChar* tokenStart; @@ -340,41 +340,41 @@ PassRefPtr<InspectorValue> buildValue(const UChar* start, const UChar* end, cons Token token = parseToken(start, end, &tokenStart, &tokenEnd); switch (token) { case INVALID_TOKEN: - return 0; + return nullptr; case NULL_TOKEN: result = InspectorValue::null(); break; case BOOL_TRUE: - result = InspectorBasicValue::create(true); + result = InspectorValue::create(true); break; case BOOL_FALSE: - result = InspectorBasicValue::create(false); + result = InspectorValue::create(false); break; case NUMBER: { bool ok; double value = charactersToDouble(tokenStart, tokenEnd - tokenStart, &ok); if (!ok) - return 0; - result = InspectorBasicValue::create(value); + return nullptr; + result = InspectorValue::create(value); break; } case STRING: { String value; - bool ok = decodeString(tokenStart + 1, tokenEnd - 1, &value); + bool ok = decodeString(tokenStart + 1, tokenEnd - 1, value); if (!ok) - return 0; - result = InspectorString::create(value); + return nullptr; + result = InspectorValue::create(value); break; } case ARRAY_BEGIN: { - RefPtr<InspectorArray> array = InspectorArray::create(); + Ref<InspectorArray> array = InspectorArray::create(); start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); while (token != ARRAY_END) { RefPtr<InspectorValue> arrayNode = buildValue(start, end, &tokenEnd, depth + 1); if (!arrayNode) - return 0; - array->pushValue(arrayNode); + return nullptr; + array->pushValue(WTFMove(arrayNode)); // After a list value, we expect a comma or the end of the list. start = tokenEnd; @@ -383,38 +383,38 @@ PassRefPtr<InspectorValue> buildValue(const UChar* start, const UChar* end, cons start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); if (token == ARRAY_END) - return 0; + return nullptr; } else if (token != ARRAY_END) { // Unexpected value after list value. Bail out. - return 0; + return nullptr; } } if (token != ARRAY_END) - return 0; - result = array.release(); + return nullptr; + result = WTFMove(array); break; } case OBJECT_BEGIN: { - RefPtr<InspectorObject> object = InspectorObject::create(); + Ref<InspectorObject> object = InspectorObject::create(); start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); while (token != OBJECT_END) { if (token != STRING) - return 0; + return nullptr; String key; - if (!decodeString(tokenStart + 1, tokenEnd - 1, &key)) - return 0; + if (!decodeString(tokenStart + 1, tokenEnd - 1, key)) + return nullptr; start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); if (token != OBJECT_PAIR_SEPARATOR) - return 0; + return nullptr; start = tokenEnd; RefPtr<InspectorValue> value = buildValue(start, end, &tokenEnd, depth + 1); if (!value) - return 0; - object->setValue(key, value); + return nullptr; + object->setValue(key, WTFMove(value)); start = tokenEnd; // After a key/value pair, we expect a comma or the end of the @@ -424,45 +424,45 @@ PassRefPtr<InspectorValue> buildValue(const UChar* start, const UChar* end, cons start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); if (token == OBJECT_END) - return 0; + return nullptr; } else if (token != OBJECT_END) { // Unexpected value after last object value. Bail out. - return 0; + return nullptr; } } if (token != OBJECT_END) - return 0; - result = object.release(); + return nullptr; + result = WTFMove(object); break; } default: // We got a token that's not a value. - return 0; + return nullptr; } *valueTokenEnd = tokenEnd; - return result.release(); + return result; } -inline bool escapeChar(UChar c, StringBuilder* dst) +inline bool escapeChar(UChar c, StringBuilder& dst) { switch (c) { - case '\b': dst->append("\\b", 2); break; - case '\f': dst->append("\\f", 2); break; - case '\n': dst->append("\\n", 2); break; - case '\r': dst->append("\\r", 2); break; - case '\t': dst->append("\\t", 2); break; - case '\\': dst->append("\\\\", 2); break; - case '"': dst->append("\\\"", 2); break; + case '\b': dst.appendLiteral("\\b"); break; + case '\f': dst.appendLiteral("\\f"); break; + case '\n': dst.appendLiteral("\\n"); break; + case '\r': dst.appendLiteral("\\r"); break; + case '\t': dst.appendLiteral("\\t"); break; + case '\\': dst.appendLiteral("\\\\"); break; + case '"': dst.appendLiteral("\\\""); break; default: return false; } return true; } -inline void doubleQuoteString(const String& str, StringBuilder* dst) +inline void doubleQuoteString(const String& str, StringBuilder& dst) { - dst->append('"'); + dst.append('"'); for (unsigned i = 0; i < str.length(); ++i) { UChar c = str[i]; if (!escapeChar(c, dst)) { @@ -470,285 +470,306 @@ inline void doubleQuoteString(const String& str, StringBuilder* dst) // 1. Escaping <, > to prevent script execution. // 2. Technically, we could also pass through c > 126 as UTF8, but this // is also optional. It would also be a pain to implement here. - unsigned int symbol = static_cast<unsigned int>(c); - String symbolCode = String::format("\\u%04X", symbol); - dst->append(symbolCode.deprecatedCharacters(), symbolCode.length()); + dst.append(String::format("\\u%04X", c)); } else - dst->append(c); + dst.append(c); } } - dst->append('"'); + dst.append('"'); } } // anonymous namespace -bool InspectorValue::asBoolean(bool*) const +Ref<InspectorValue> InspectorValue::null() { - return false; + return adoptRef(*new InspectorValue); } -bool InspectorValue::asNumber(double*) const +Ref<InspectorValue> InspectorValue::create(bool value) { - return false; + return adoptRef(*new InspectorValue(value)); } -bool InspectorValue::asNumber(long*) const +Ref<InspectorValue> InspectorValue::create(int value) { - return false; + return adoptRef(*new InspectorValue(value)); } -bool InspectorValue::asNumber(int*) const +Ref<InspectorValue> InspectorValue::create(double value) { - return false; + return adoptRef(*new InspectorValue(value)); } -bool InspectorValue::asNumber(unsigned long*) const +Ref<InspectorValue> InspectorValue::create(const String& value) { - return false; + return adoptRef(*new InspectorValue(value)); } -bool InspectorValue::asNumber(unsigned int*) const +Ref<InspectorValue> InspectorValue::create(const char* value) { - return false; + return adoptRef(*new InspectorValue(value)); } -bool InspectorValue::asString(String*) const +bool InspectorValue::asValue(RefPtr<Inspector::InspectorValue> & value) { - return false; + value = this; + return true; } -bool InspectorValue::asValue(RefPtr<InspectorValue>* output) +bool InspectorValue::asObject(RefPtr<InspectorObject>&) { - *output = this; - return true; + return false; } -bool InspectorValue::asObject(RefPtr<InspectorObject>*) +bool InspectorValue::asArray(RefPtr<InspectorArray>&) { return false; } -bool InspectorValue::asArray(RefPtr<InspectorArray>*) +bool InspectorValue::parseJSON(const String& jsonInput, RefPtr<InspectorValue>& output) { - return false; + // FIXME: This whole file should just use StringView instead of UChar/length and avoid upconverting. + auto characters = StringView(jsonInput).upconvertedCharacters(); + const UChar* start = characters; + const UChar* end = start + jsonInput.length(); + const UChar* tokenEnd; + auto result = buildValue(start, end, &tokenEnd, 0); + if (!result || tokenEnd != end) + return false; + + output = WTFMove(result); + return true; } -PassRefPtr<InspectorObject> InspectorValue::asObject() +String InspectorValue::toJSONString() const { - return 0; + StringBuilder result; + result.reserveCapacity(512); + writeJSON(result); + return result.toString(); } -PassRefPtr<InspectorArray> InspectorValue::asArray() +bool InspectorValue::asBoolean(bool& output) const { - return 0; + if (type() != Type::Boolean) + return false; + + output = m_value.boolean; + return true; } -PassRefPtr<InspectorValue> InspectorValue::parseJSON(const String& json) +bool InspectorValue::asDouble(double& output) const { - const UChar* start = json.deprecatedCharacters(); - const UChar* end = json.deprecatedCharacters() + json.length(); - const UChar *tokenEnd; - RefPtr<InspectorValue> value = buildValue(start, end, &tokenEnd, 0); - if (!value || tokenEnd != end) - return 0; - return value.release(); + if (type() != Type::Double) + return false; + + output = m_value.number; + return true; } -String InspectorValue::toJSONString() const +bool InspectorValue::asDouble(float& output) const { - StringBuilder result; - result.reserveCapacity(512); - writeJSON(&result); - return result.toString(); + if (type() != Type::Double) + return false; + + output = static_cast<float>(m_value.number); + return true; } -void InspectorValue::writeJSON(StringBuilder* output) const +bool InspectorValue::asInteger(int& output) const { - ASSERT(m_type == TypeNull); - output->append(nullString, 4); + if (type() != Type::Integer && type() != Type::Double) + return false; + + output = static_cast<int>(m_value.number); + return true; } -bool InspectorBasicValue::asBoolean(bool* output) const +bool InspectorValue::asInteger(unsigned& output) const { - if (type() != TypeBoolean) + if (type() != Type::Integer && type() != Type::Double) return false; - *output = m_boolValue; + + output = static_cast<unsigned>(m_value.number); return true; } -bool InspectorBasicValue::asNumber(double* output) const +bool InspectorValue::asInteger(long& output) const { - if (type() != TypeNumber) + if (type() != Type::Integer && type() != Type::Double) return false; - *output = m_doubleValue; + + output = static_cast<long>(m_value.number); return true; } -bool InspectorBasicValue::asNumber(long* output) const +bool InspectorValue::asInteger(long long& output) const { - if (type() != TypeNumber) + if (type() != Type::Integer && type() != Type::Double) return false; - *output = static_cast<long>(m_doubleValue); + + output = static_cast<long long>(m_value.number); return true; } -bool InspectorBasicValue::asNumber(int* output) const +bool InspectorValue::asInteger(unsigned long& output) const { - if (type() != TypeNumber) + if (type() != Type::Integer && type() != Type::Double) return false; - *output = static_cast<int>(m_doubleValue); + + output = static_cast<unsigned long>(m_value.number); return true; } -bool InspectorBasicValue::asNumber(unsigned long* output) const +bool InspectorValue::asInteger(unsigned long long& output) const { - if (type() != TypeNumber) + if (type() != Type::Integer && type() != Type::Double) return false; - *output = static_cast<unsigned long>(m_doubleValue); + + output = static_cast<unsigned long long>(m_value.number); return true; } -bool InspectorBasicValue::asNumber(unsigned int* output) const +bool InspectorValue::asString(String& output) const { - if (type() != TypeNumber) + if (type() != Type::String) return false; - *output = static_cast<unsigned int>(m_doubleValue); + + output = m_value.string; return true; } -void InspectorBasicValue::writeJSON(StringBuilder* output) const +void InspectorValue::writeJSON(StringBuilder& output) const { - ASSERT(type() == TypeBoolean || type() == TypeNumber); - if (type() == TypeBoolean) { - if (m_boolValue) - output->append(trueString, 4); + switch (m_type) { + case Type::Null: + output.appendLiteral("null"); + break; + case Type::Boolean: + if (m_value.boolean) + output.appendLiteral("true"); else - output->append(falseString, 5); - } else if (type() == TypeNumber) { + output.appendLiteral("false"); + break; + case Type::String: + doubleQuoteString(m_value.string, output); + break; + case Type::Double: + case Type::Integer: { NumberToLStringBuffer buffer; - if (!std::isfinite(m_doubleValue)) { - output->append(nullString, 4); + if (!std::isfinite(m_value.number)) { + output.appendLiteral("null"); return; } - DecimalNumber decimal = m_doubleValue; + DecimalNumber decimal = m_value.number; unsigned length = 0; if (decimal.bufferLengthForStringDecimal() > WTF::NumberToStringBufferLength) { // Not enough room for decimal. Use exponential format. if (decimal.bufferLengthForStringExponential() > WTF::NumberToStringBufferLength) { // Fallback for an abnormal case if it's too little even for exponential. - output->append("NaN", 3); + output.appendLiteral("NaN"); return; } length = decimal.toStringExponential(buffer, WTF::NumberToStringBufferLength); } else length = decimal.toStringDecimal(buffer, WTF::NumberToStringBufferLength); - output->append(buffer, length); + output.append(buffer, length); + break; + } + default: + ASSERT_NOT_REACHED(); } -} - -bool InspectorString::asString(String* output) const -{ - *output = m_stringValue; - return true; -} - -void InspectorString::writeJSON(StringBuilder* output) const -{ - ASSERT(type() == TypeString); - doubleQuoteString(m_stringValue, output); } InspectorObjectBase::~InspectorObjectBase() { } -bool InspectorObjectBase::asObject(RefPtr<InspectorObject>* output) +bool InspectorObjectBase::asObject(RefPtr<InspectorObject>& output) { COMPILE_ASSERT(sizeof(InspectorObject) == sizeof(InspectorObjectBase), cannot_cast); - *output = static_cast<InspectorObject*>(this); - return true; -} -PassRefPtr<InspectorObject> InspectorObjectBase::asObject() -{ - return openAccessors(); + output = static_cast<InspectorObject*>(this); + return true; } InspectorObject* InspectorObjectBase::openAccessors() { COMPILE_ASSERT(sizeof(InspectorObject) == sizeof(InspectorObjectBase), cannot_cast); + return static_cast<InspectorObject*>(this); } -bool InspectorObjectBase::getBoolean(const String& name, bool* output) const +bool InspectorObjectBase::getBoolean(const String& name, bool& output) const { - RefPtr<InspectorValue> value = get(name); - if (!value) + RefPtr<InspectorValue> value; + if (!getValue(name, value)) return false; + return value->asBoolean(output); } -bool InspectorObjectBase::getString(const String& name, String* output) const +bool InspectorObjectBase::getString(const String& name, String& output) const { - RefPtr<InspectorValue> value = get(name); - if (!value) + RefPtr<InspectorValue> value; + if (!getValue(name, value)) return false; + return value->asString(output); } -PassRefPtr<InspectorObject> InspectorObjectBase::getObject(const String& name) const +bool InspectorObjectBase::getObject(const String& name, RefPtr<InspectorObject>& output) const { - PassRefPtr<InspectorValue> value = get(name); - if (!value) - return 0; - return value->asObject(); + RefPtr<InspectorValue> value; + if (!getValue(name, value)) + return false; + + return value->asObject(output); } -PassRefPtr<InspectorArray> InspectorObjectBase::getArray(const String& name) const +bool InspectorObjectBase::getArray(const String& name, RefPtr<InspectorArray>& output) const { - PassRefPtr<InspectorValue> value = get(name); - if (!value) - return 0; - return value->asArray(); + RefPtr<InspectorValue> value; + if (!getValue(name, value)) + return false; + + return value->asArray(output); } -PassRefPtr<InspectorValue> InspectorObjectBase::get(const String& name) const +bool InspectorObjectBase::getValue(const String& name, RefPtr<InspectorValue>& output) const { - Dictionary::const_iterator it = m_data.find(name); - if (it == m_data.end()) - return 0; - return it->value; + Dictionary::const_iterator findResult = m_map.find(name); + if (findResult == m_map.end()) + return false; + + output = findResult->value; + return true; } void InspectorObjectBase::remove(const String& name) { - m_data.remove(name); - for (size_t i = 0; i < m_order.size(); ++i) { - if (m_order[i] == name) { - m_order.remove(i); - break; - } - } + m_map.remove(name); + m_order.removeFirst(name); } -void InspectorObjectBase::writeJSON(StringBuilder* output) const +void InspectorObjectBase::writeJSON(StringBuilder& output) const { - output->append('{'); + output.append('{'); for (size_t i = 0; i < m_order.size(); ++i) { - Dictionary::const_iterator it = m_data.find(m_order[i]); - ASSERT(it != m_data.end()); + auto findResult = m_map.find(m_order[i]); + ASSERT(findResult != m_map.end()); if (i) - output->append(','); - doubleQuoteString(it->key, output); - output->append(':'); - it->value->writeJSON(output); + output.append(','); + doubleQuoteString(findResult->key, output); + output.append(':'); + findResult->value->writeJSON(output); } - output->append('}'); + output.append('}'); } InspectorObjectBase::InspectorObjectBase() - : InspectorValue(TypeObject) - , m_data() + : Inspector::InspectorValue(Type::Object) + , m_map() , m_order() { } @@ -757,80 +778,44 @@ InspectorArrayBase::~InspectorArrayBase() { } -bool InspectorArrayBase::asArray(RefPtr<InspectorArray>* output) +bool InspectorArrayBase::asArray(RefPtr<InspectorArray>& output) { COMPILE_ASSERT(sizeof(InspectorArrayBase) == sizeof(InspectorArray), cannot_cast); - *output = static_cast<InspectorArray*>(this); + output = static_cast<InspectorArray*>(this); return true; } -PassRefPtr<InspectorArray> InspectorArrayBase::asArray() -{ - COMPILE_ASSERT(sizeof(InspectorArrayBase) == sizeof(InspectorArray), cannot_cast); - return static_cast<InspectorArray*>(this); -} - -void InspectorArrayBase::writeJSON(StringBuilder* output) const +void InspectorArrayBase::writeJSON(StringBuilder& output) const { - output->append('['); - for (Vector<RefPtr<InspectorValue>>::const_iterator it = m_data.begin(); it != m_data.end(); ++it) { - if (it != m_data.begin()) - output->append(','); + output.append('['); + for (Vector<RefPtr<InspectorValue>>::const_iterator it = m_map.begin(); it != m_map.end(); ++it) { + if (it != m_map.begin()) + output.append(','); (*it)->writeJSON(output); } - output->append(']'); + output.append(']'); } InspectorArrayBase::InspectorArrayBase() - : InspectorValue(TypeArray) - , m_data() -{ -} - -PassRefPtr<InspectorValue> InspectorArrayBase::get(size_t index) -{ - ASSERT_WITH_SECURITY_IMPLICATION(index < m_data.size()); - return m_data[index]; -} - -PassRefPtr<InspectorObject> InspectorObject::create() -{ - return adoptRef(new InspectorObject); -} - -PassRefPtr<InspectorArray> InspectorArray::create() -{ - return adoptRef(new InspectorArray); -} - -PassRefPtr<InspectorValue> InspectorValue::null() -{ - return adoptRef(new InspectorValue); -} - -PassRefPtr<InspectorString> InspectorString::create(const String& value) -{ - return adoptRef(new InspectorString(value)); -} - -PassRefPtr<InspectorString> InspectorString::create(const char* value) + : InspectorValue(Type::Array) + , m_map() { - return adoptRef(new InspectorString(value)); } -PassRefPtr<InspectorBasicValue> InspectorBasicValue::create(bool value) +RefPtr<InspectorValue> InspectorArrayBase::get(size_t index) const { - return adoptRef(new InspectorBasicValue(value)); + ASSERT_WITH_SECURITY_IMPLICATION(index < m_map.size()); + return m_map[index]; } -PassRefPtr<InspectorBasicValue> InspectorBasicValue::create(int value) +Ref<InspectorObject> InspectorObject::create() { - return adoptRef(new InspectorBasicValue(value)); + return adoptRef(*new InspectorObject); } -PassRefPtr<InspectorBasicValue> InspectorBasicValue::create(double value) +Ref<InspectorArray> InspectorArray::create() { - return adoptRef(new InspectorBasicValue(value)); + return adoptRef(*new InspectorArray); } } // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/InspectorValues.h b/Source/JavaScriptCore/inspector/InspectorValues.h index 06c5dfe97..6687bbaf6 100644 --- a/Source/JavaScriptCore/inspector/InspectorValues.h +++ b/Source/JavaScriptCore/inspector/InspectorValues.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2009 Google Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -28,10 +29,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorValues_h -#define InspectorValues_h +#pragma once -#include <wtf/Forward.h> +#include "JSExportMacros.h" +#include <wtf/Assertions.h> #include <wtf/HashMap.h> #include <wtf/RefCounted.h> #include <wtf/Vector.h> @@ -41,96 +42,121 @@ namespace Inspector { class InspectorArray; +class InspectorArrayBase; class InspectorObject; +class InspectorObjectBase; class JS_EXPORT_PRIVATE InspectorValue : public RefCounted<InspectorValue> { public: static const int maxDepth = 1000; - InspectorValue() : m_type(TypeNull) { } - virtual ~InspectorValue() { } - - static PassRefPtr<InspectorValue> null(); + virtual ~InspectorValue() + { + switch (m_type) { + case Type::Null: + case Type::Boolean: + case Type::Double: + case Type::Integer: + break; + case Type::String: + if (m_value.string) + m_value.string->deref(); + break; + case Type::Object: + case Type::Array: + break; + } + } - typedef enum { - TypeNull = 0, - TypeBoolean, - TypeNumber, - TypeString, - TypeObject, - TypeArray - } Type; + static Ref<InspectorValue> null(); + static Ref<InspectorValue> create(bool); + static Ref<InspectorValue> create(int); + static Ref<InspectorValue> create(double); + static Ref<InspectorValue> create(const String&); + static Ref<InspectorValue> create(const char*); + + enum class Type { + Null = 0, + Boolean, + Double, + Integer, + String, + Object, + Array, + }; Type type() const { return m_type; } + bool isNull() const { return m_type == Type::Null; } - bool isNull() const { return m_type == TypeNull; } + bool asBoolean(bool&) const; + bool asInteger(int&) const; + bool asInteger(unsigned&) const; + bool asInteger(long&) const; + bool asInteger(long long&) const; + bool asInteger(unsigned long&) const; + bool asInteger(unsigned long long&) const; + bool asDouble(double&) const; + bool asDouble(float&) const; + bool asString(String&) const; + bool asValue(RefPtr<InspectorValue>&); - virtual bool asBoolean(bool* output) const; - virtual bool asNumber(double* output) const; - virtual bool asNumber(long* output) const; - virtual bool asNumber(int* output) const; - virtual bool asNumber(unsigned long* output) const; - virtual bool asNumber(unsigned int* output) const; - virtual bool asString(String* output) const; - virtual bool asValue(RefPtr<InspectorValue>* output); - virtual bool asObject(RefPtr<InspectorObject>* output); - virtual bool asArray(RefPtr<InspectorArray>* output); - virtual PassRefPtr<InspectorObject> asObject(); - virtual PassRefPtr<InspectorArray> asArray(); + virtual bool asObject(RefPtr<InspectorObject>&); + virtual bool asArray(RefPtr<InspectorArray>&); - static PassRefPtr<InspectorValue> parseJSON(const String& json); + static bool parseJSON(const String& jsonInput, RefPtr<InspectorValue>& output); String toJSONString() const; - virtual void writeJSON(StringBuilder* output) const; + virtual void writeJSON(StringBuilder& output) const; protected: - explicit InspectorValue(Type type) : m_type(type) { } - -private: - Type m_type; -}; - -class JS_EXPORT_PRIVATE InspectorBasicValue : public InspectorValue { -public: - - static PassRefPtr<InspectorBasicValue> create(bool); - static PassRefPtr<InspectorBasicValue> create(int); - static PassRefPtr<InspectorBasicValue> create(double); + InspectorValue() + : m_type(Type::Null) { } - virtual bool asBoolean(bool* output) const override; - virtual bool asNumber(double* output) const override; - virtual bool asNumber(long* output) const override; - virtual bool asNumber(int* output) const override; - virtual bool asNumber(unsigned long* output) const override; - virtual bool asNumber(unsigned* output) const override; + explicit InspectorValue(Type type) + : m_type(type) { } - virtual void writeJSON(StringBuilder* output) const override; - -private: - explicit InspectorBasicValue(bool value) : InspectorValue(TypeBoolean), m_boolValue(value) { } - explicit InspectorBasicValue(int value) : InspectorValue(TypeNumber), m_doubleValue((double)value) { } - explicit InspectorBasicValue(double value) : InspectorValue(TypeNumber), m_doubleValue(value) { } + explicit InspectorValue(bool value) + : m_type(Type::Boolean) + { + m_value.boolean = value; + } - union { - bool m_boolValue; - double m_doubleValue; - }; -}; + explicit InspectorValue(int value) + : m_type(Type::Integer) + { + m_value.number = static_cast<double>(value); + } -class JS_EXPORT_PRIVATE InspectorString : public InspectorValue { -public: - static PassRefPtr<InspectorString> create(const String&); - static PassRefPtr<InspectorString> create(const char*); + explicit InspectorValue(double value) + : m_type(Type::Double) + { + m_value.number = value; + } - virtual bool asString(String* output) const override; + explicit InspectorValue(const String& value) + : m_type(Type::String) + { + m_value.string = value.impl(); + if (m_value.string) + m_value.string->ref(); + } - virtual void writeJSON(StringBuilder* output) const override; + explicit InspectorValue(const char* value) + : m_type(Type::String) + { + String wrapper(value); + m_value.string = wrapper.impl(); + if (m_value.string) + m_value.string->ref(); + } private: - explicit InspectorString(const String& value) : InspectorValue(TypeString), m_stringValue(value) { } - explicit InspectorString(const char* value) : InspectorValue(TypeString), m_stringValue(value) { } - - String m_stringValue; + Type m_type { Type::Null }; + union { + bool boolean; + double number; + StringImpl* string; + } m_value; }; class JS_EXPORT_PRIVATE InspectorObjectBase : public InspectorValue { @@ -141,63 +167,77 @@ public: typedef Dictionary::iterator iterator; typedef Dictionary::const_iterator const_iterator; - virtual PassRefPtr<InspectorObject> asObject() override; InspectorObject* openAccessors(); protected: virtual ~InspectorObjectBase(); - virtual bool asObject(RefPtr<InspectorObject>* output) override; + bool asObject(RefPtr<InspectorObject>& output) override; + // FIXME: use templates to reduce the amount of duplicated set*() methods. void setBoolean(const String& name, bool); - void setNumber(const String& name, double); + void setInteger(const String& name, int); + void setDouble(const String& name, double); void setString(const String& name, const String&); - void setValue(const String& name, PassRefPtr<InspectorValue>); - void setObject(const String& name, PassRefPtr<InspectorObject>); - void setArray(const String& name, PassRefPtr<InspectorArray>); + void setValue(const String& name, RefPtr<InspectorValue>&&); + void setObject(const String& name, RefPtr<InspectorObjectBase>&&); + void setArray(const String& name, RefPtr<InspectorArrayBase>&&); iterator find(const String& name); const_iterator find(const String& name) const; - bool getBoolean(const String& name, bool* output) const; - template<class T> bool getNumber(const String& name, T* output) const + + // FIXME: use templates to reduce the amount of duplicated get*() methods. + bool getBoolean(const String& name, bool& output) const; + template<class T> bool getDouble(const String& name, T& output) const + { + RefPtr<InspectorValue> value; + if (!getValue(name, value)) + return false; + + return value->asDouble(output); + } + template<class T> bool getInteger(const String& name, T& output) const { - RefPtr<InspectorValue> value = get(name); - if (!value) + RefPtr<InspectorValue> value; + if (!getValue(name, value)) return false; - return value->asNumber(output); + + return value->asInteger(output); } - bool getString(const String& name, String* output) const; - PassRefPtr<InspectorObject> getObject(const String& name) const; - PassRefPtr<InspectorArray> getArray(const String& name) const; - PassRefPtr<InspectorValue> get(const String& name) const; + + bool getString(const String& name, String& output) const; + bool getObject(const String& name, RefPtr<InspectorObject>&) const; + bool getArray(const String& name, RefPtr<InspectorArray>&) const; + bool getValue(const String& name, RefPtr<InspectorValue>&) const; void remove(const String& name); - virtual void writeJSON(StringBuilder* output) const override; + void writeJSON(StringBuilder& output) const override; - iterator begin() { return m_data.begin(); } - iterator end() { return m_data.end(); } - const_iterator begin() const { return m_data.begin(); } - const_iterator end() const { return m_data.end(); } + iterator begin() { return m_map.begin(); } + iterator end() { return m_map.end(); } + const_iterator begin() const { return m_map.begin(); } + const_iterator end() const { return m_map.end(); } - int size() const { return m_data.size(); } + int size() const { return m_map.size(); } protected: InspectorObjectBase(); private: - Dictionary m_data; + Dictionary m_map; Vector<String> m_order; }; class InspectorObject : public InspectorObjectBase { public: - static JS_EXPORT_PRIVATE PassRefPtr<InspectorObject> create(); + static JS_EXPORT_PRIVATE Ref<InspectorObject> create(); using InspectorObjectBase::asObject; using InspectorObjectBase::setBoolean; - using InspectorObjectBase::setNumber; + using InspectorObjectBase::setInteger; + using InspectorObjectBase::setDouble; using InspectorObjectBase::setString; using InspectorObjectBase::setValue; using InspectorObjectBase::setObject; @@ -205,11 +245,12 @@ public: using InspectorObjectBase::find; using InspectorObjectBase::getBoolean; - using InspectorObjectBase::getNumber; + using InspectorObjectBase::getInteger; + using InspectorObjectBase::getDouble; using InspectorObjectBase::getString; using InspectorObjectBase::getObject; using InspectorObjectBase::getArray; - using InspectorObjectBase::get; + using InspectorObjectBase::getValue; using InspectorObjectBase::remove; @@ -225,48 +266,46 @@ public: typedef Vector<RefPtr<InspectorValue>>::iterator iterator; typedef Vector<RefPtr<InspectorValue>>::const_iterator const_iterator; - virtual PassRefPtr<InspectorArray> asArray() override; - - unsigned length() const { return m_data.size(); } + unsigned length() const { return static_cast<unsigned>(m_map.size()); } protected: virtual ~InspectorArrayBase(); - virtual bool asArray(RefPtr<InspectorArray>* output) override; + bool asArray(RefPtr<InspectorArray>&) override; void pushBoolean(bool); - void pushInt(int); - void pushNumber(double); + void pushInteger(int); + void pushDouble(double); void pushString(const String&); - void pushValue(PassRefPtr<InspectorValue>); - void pushObject(PassRefPtr<InspectorObject>); - void pushArray(PassRefPtr<InspectorArray>); + void pushValue(RefPtr<InspectorValue>&&); + void pushObject(RefPtr<InspectorObjectBase>&&); + void pushArray(RefPtr<InspectorArrayBase>&&); - PassRefPtr<InspectorValue> get(size_t index); + RefPtr<InspectorValue> get(size_t index) const; - virtual void writeJSON(StringBuilder* output) const override; + void writeJSON(StringBuilder& output) const override; - iterator begin() { return m_data.begin(); } - iterator end() { return m_data.end(); } - const_iterator begin() const { return m_data.begin(); } - const_iterator end() const { return m_data.end(); } + iterator begin() { return m_map.begin(); } + iterator end() { return m_map.end(); } + const_iterator begin() const { return m_map.begin(); } + const_iterator end() const { return m_map.end(); } protected: InspectorArrayBase(); private: - Vector<RefPtr<InspectorValue>> m_data; + Vector<RefPtr<InspectorValue>> m_map; }; class InspectorArray : public InspectorArrayBase { public: - static JS_EXPORT_PRIVATE PassRefPtr<InspectorArray> create(); + static JS_EXPORT_PRIVATE Ref<InspectorArray> create(); using InspectorArrayBase::asArray; using InspectorArrayBase::pushBoolean; - using InspectorArrayBase::pushInt; - using InspectorArrayBase::pushNumber; + using InspectorArrayBase::pushInteger; + using InspectorArrayBase::pushDouble; using InspectorArrayBase::pushString; using InspectorArrayBase::pushValue; using InspectorArrayBase::pushObject; @@ -281,88 +320,91 @@ public: inline InspectorObjectBase::iterator InspectorObjectBase::find(const String& name) { - return m_data.find(name); + return m_map.find(name); } inline InspectorObjectBase::const_iterator InspectorObjectBase::find(const String& name) const { - return m_data.find(name); + return m_map.find(name); } inline void InspectorObjectBase::setBoolean(const String& name, bool value) { - setValue(name, InspectorBasicValue::create(value)); + setValue(name, InspectorValue::create(value)); } -inline void InspectorObjectBase::setNumber(const String& name, double value) +inline void InspectorObjectBase::setInteger(const String& name, int value) { - setValue(name, InspectorBasicValue::create(value)); + setValue(name, InspectorValue::create(value)); +} + +inline void InspectorObjectBase::setDouble(const String& name, double value) +{ + setValue(name, InspectorValue::create(value)); } inline void InspectorObjectBase::setString(const String& name, const String& value) { - setValue(name, InspectorString::create(value)); + setValue(name, InspectorValue::create(value)); } -inline void InspectorObjectBase::setValue(const String& name, PassRefPtr<InspectorValue> value) +inline void InspectorObjectBase::setValue(const String& name, RefPtr<InspectorValue>&& value) { ASSERT(value); - if (m_data.set(name, value).isNewEntry) + if (m_map.set(name, WTFMove(value)).isNewEntry) m_order.append(name); } -inline void InspectorObjectBase::setObject(const String& name, PassRefPtr<InspectorObject> value) +inline void InspectorObjectBase::setObject(const String& name, RefPtr<InspectorObjectBase>&& value) { ASSERT(value); - if (m_data.set(name, value).isNewEntry) + if (m_map.set(name, WTFMove(value)).isNewEntry) m_order.append(name); } -inline void InspectorObjectBase::setArray(const String& name, PassRefPtr<InspectorArray> value) +inline void InspectorObjectBase::setArray(const String& name, RefPtr<InspectorArrayBase>&& value) { ASSERT(value); - if (m_data.set(name, value).isNewEntry) + if (m_map.set(name, WTFMove(value)).isNewEntry) m_order.append(name); } inline void InspectorArrayBase::pushBoolean(bool value) { - m_data.append(InspectorBasicValue::create(value)); + m_map.append(InspectorValue::create(value)); } -inline void InspectorArrayBase::pushInt(int value) +inline void InspectorArrayBase::pushInteger(int value) { - m_data.append(InspectorBasicValue::create(value)); + m_map.append(InspectorValue::create(value)); } -inline void InspectorArrayBase::pushNumber(double value) +inline void InspectorArrayBase::pushDouble(double value) { - m_data.append(InspectorBasicValue::create(value)); + m_map.append(InspectorValue::create(value)); } inline void InspectorArrayBase::pushString(const String& value) { - m_data.append(InspectorString::create(value)); + m_map.append(InspectorValue::create(value)); } -inline void InspectorArrayBase::pushValue(PassRefPtr<InspectorValue> value) +inline void InspectorArrayBase::pushValue(RefPtr<InspectorValue>&& value) { ASSERT(value); - m_data.append(value); + m_map.append(WTFMove(value)); } -inline void InspectorArrayBase::pushObject(PassRefPtr<InspectorObject> value) +inline void InspectorArrayBase::pushObject(RefPtr<InspectorObjectBase>&& value) { ASSERT(value); - m_data.append(value); + m_map.append(WTFMove(value)); } -inline void InspectorArrayBase::pushArray(PassRefPtr<InspectorArray> value) +inline void InspectorArrayBase::pushArray(RefPtr<InspectorArrayBase>&& value) { ASSERT(value); - m_data.append(value); + m_map.append(WTFMove(value)); } } // namespace Inspector - -#endif // !defined(InspectorValues_h) diff --git a/Source/JavaScriptCore/inspector/JSGlobalObjectConsoleClient.cpp b/Source/JavaScriptCore/inspector/JSGlobalObjectConsoleClient.cpp new file mode 100644 index 000000000..1f903bae7 --- /dev/null +++ b/Source/JavaScriptCore/inspector/JSGlobalObjectConsoleClient.cpp @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSGlobalObjectConsoleClient.h" + +#include "ConsoleMessage.h" +#include "InspectorConsoleAgent.h" +#include "InspectorDebuggerAgent.h" +#include "InspectorScriptProfilerAgent.h" +#include "ScriptArguments.h" +#include "ScriptCallStack.h" +#include "ScriptCallStackFactory.h" + +using namespace JSC; + +namespace Inspector { + +#if !LOG_DISABLED +static bool sLogToSystemConsole = true; +#else +static bool sLogToSystemConsole = false; +#endif + +bool JSGlobalObjectConsoleClient::logToSystemConsole() +{ + return sLogToSystemConsole; +} + +void JSGlobalObjectConsoleClient::setLogToSystemConsole(bool shouldLog) +{ + sLogToSystemConsole = shouldLog; +} + +JSGlobalObjectConsoleClient::JSGlobalObjectConsoleClient(InspectorConsoleAgent* consoleAgent, InspectorDebuggerAgent* debuggerAgent, InspectorScriptProfilerAgent* scriptProfilerAgent) + : ConsoleClient() + , m_consoleAgent(consoleAgent) + , m_debuggerAgent(debuggerAgent) + , m_scriptProfilerAgent(scriptProfilerAgent) +{ +} + +void JSGlobalObjectConsoleClient::messageWithTypeAndLevel(MessageType type, MessageLevel level, JSC::ExecState* exec, Ref<ScriptArguments>&& arguments) +{ + if (JSGlobalObjectConsoleClient::logToSystemConsole()) + ConsoleClient::printConsoleMessageWithArguments(MessageSource::ConsoleAPI, type, level, exec, arguments.copyRef()); + + String message; + arguments->getFirstArgumentAsString(message); + m_consoleAgent->addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, type, level, message, WTFMove(arguments), exec)); +} + +void JSGlobalObjectConsoleClient::count(ExecState* exec, Ref<ScriptArguments>&& arguments) +{ + m_consoleAgent->count(exec, WTFMove(arguments)); +} + +void JSGlobalObjectConsoleClient::profile(JSC::ExecState*, const String& title) +{ + if (!m_consoleAgent->enabled()) + return; + + // Allow duplicate unnamed profiles. Disallow duplicate named profiles. + if (!title.isEmpty()) { + for (auto& existingTitle : m_profiles) { + if (existingTitle == title) { + // FIXME: Send an enum to the frontend for localization? + String warning = title.isEmpty() ? ASCIILiteral("Unnamed Profile already exists") : makeString("Profile \"", title, "\" already exists"); + m_consoleAgent->addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Profile, MessageLevel::Warning, warning)); + return; + } + } + } + + m_profiles.append(title); + startConsoleProfile(); +} + +void JSGlobalObjectConsoleClient::profileEnd(JSC::ExecState*, const String& title) +{ + if (!m_consoleAgent->enabled()) + return; + + // Stop profiles in reverse order. If the title is empty, then stop the last profile. + // Otherwise, match the title of the profile to stop. + for (ptrdiff_t i = m_profiles.size() - 1; i >= 0; --i) { + if (title.isEmpty() || m_profiles[i] == title) { + m_profiles.remove(i); + if (m_profiles.isEmpty()) + stopConsoleProfile(); + return; + } + } + + // FIXME: Send an enum to the frontend for localization? + String warning = title.isEmpty() ? ASCIILiteral("No profiles exist") : makeString("Profile \"", title, "\" does not exist"); + m_consoleAgent->addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::ProfileEnd, MessageLevel::Warning, warning)); +} + +void JSGlobalObjectConsoleClient::startConsoleProfile() +{ + // FIXME: <https://webkit.org/b/158753> Generalize the concept of Instruments on the backend to work equally for JSContext and Web inspection + m_scriptProfilerAgent->programmaticCaptureStarted(); + + m_profileRestoreBreakpointActiveValue = m_debuggerAgent->breakpointsActive(); + + ErrorString unused; + m_debuggerAgent->setBreakpointsActive(unused, false); + + const bool includeSamples = true; + m_scriptProfilerAgent->startTracking(unused, &includeSamples); +} + +void JSGlobalObjectConsoleClient::stopConsoleProfile() +{ + ErrorString unused; + m_scriptProfilerAgent->stopTracking(unused); + + m_debuggerAgent->setBreakpointsActive(unused, m_profileRestoreBreakpointActiveValue); + + // FIXME: <https://webkit.org/b/158753> Generalize the concept of Instruments on the backend to work equally for JSContext and Web inspection + m_scriptProfilerAgent->programmaticCaptureStopped(); +} + +void JSGlobalObjectConsoleClient::takeHeapSnapshot(JSC::ExecState*, const String& title) +{ + m_consoleAgent->takeHeapSnapshot(title); +} + +void JSGlobalObjectConsoleClient::time(ExecState*, const String& title) +{ + m_consoleAgent->startTiming(title); +} + +void JSGlobalObjectConsoleClient::timeEnd(ExecState* exec, const String& title) +{ + m_consoleAgent->stopTiming(title, createScriptCallStackForConsole(exec, 1)); +} + +void JSGlobalObjectConsoleClient::timeStamp(ExecState*, Ref<ScriptArguments>&&) +{ + // FIXME: JSContext inspection needs a timeline. + warnUnimplemented(ASCIILiteral("console.timeStamp")); +} + +void JSGlobalObjectConsoleClient::warnUnimplemented(const String& method) +{ + String message = method + " is currently ignored in JavaScript context inspection."; + m_consoleAgent->addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Log, MessageLevel::Warning, message)); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/JSGlobalObjectConsoleClient.h b/Source/JavaScriptCore/inspector/JSGlobalObjectConsoleClient.h new file mode 100644 index 000000000..d9b259cb6 --- /dev/null +++ b/Source/JavaScriptCore/inspector/JSGlobalObjectConsoleClient.h @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "ConsoleClient.h" +#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class InspectorConsoleAgent; +class InspectorDebuggerAgent; +class InspectorScriptProfilerAgent; + +class JSGlobalObjectConsoleClient final : public JSC::ConsoleClient { + WTF_MAKE_FAST_ALLOCATED; +public: + explicit JSGlobalObjectConsoleClient(InspectorConsoleAgent*, InspectorDebuggerAgent*, InspectorScriptProfilerAgent*); + virtual ~JSGlobalObjectConsoleClient() { } + + static bool logToSystemConsole(); + static void setLogToSystemConsole(bool); + +protected: + void messageWithTypeAndLevel(MessageType, MessageLevel, JSC::ExecState*, Ref<ScriptArguments>&&) override; + void count(JSC::ExecState*, Ref<ScriptArguments>&&) override; + void profile(JSC::ExecState*, const String& title) override; + void profileEnd(JSC::ExecState*, const String& title) override; + void takeHeapSnapshot(JSC::ExecState*, const String& title) override; + void time(JSC::ExecState*, const String& title) override; + void timeEnd(JSC::ExecState*, const String& title) override; + void timeStamp(JSC::ExecState*, Ref<ScriptArguments>&&) override; + +private: + void warnUnimplemented(const String& method); + void internalAddMessage(MessageType, MessageLevel, JSC::ExecState*, Ref<ScriptArguments>&&); + + void startConsoleProfile(); + void stopConsoleProfile(); + + InspectorConsoleAgent* m_consoleAgent; + InspectorDebuggerAgent* m_debuggerAgent; + InspectorScriptProfilerAgent* m_scriptProfilerAgent; + Vector<String> m_profiles; + bool m_profileRestoreBreakpointActiveValue { false }; +}; + +} diff --git a/Source/JavaScriptCore/inspector/JSGlobalObjectInspectorController.cpp b/Source/JavaScriptCore/inspector/JSGlobalObjectInspectorController.cpp new file mode 100644 index 000000000..313730a57 --- /dev/null +++ b/Source/JavaScriptCore/inspector/JSGlobalObjectInspectorController.cpp @@ -0,0 +1,315 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSGlobalObjectInspectorController.h" + +#include "Completion.h" +#include "ConsoleMessage.h" +#include "ErrorHandlingScope.h" +#include "Exception.h" +#include "InjectedScriptHost.h" +#include "InjectedScriptManager.h" +#include "InspectorAgent.h" +#include "InspectorBackendDispatcher.h" +#include "InspectorFrontendChannel.h" +#include "InspectorFrontendRouter.h" +#include "InspectorHeapAgent.h" +#include "InspectorScriptProfilerAgent.h" +#include "JSCInlines.h" +#include "JSGlobalObject.h" +#include "JSGlobalObjectConsoleAgent.h" +#include "JSGlobalObjectConsoleClient.h" +#include "JSGlobalObjectDebuggerAgent.h" +#include "JSGlobalObjectRuntimeAgent.h" +#include "ScriptArguments.h" +#include "ScriptCallStack.h" +#include "ScriptCallStackFactory.h" +#include <wtf/Stopwatch.h> + +#if OS(DARWIN) || (OS(LINUX) && !PLATFORM(GTK)) +#include <cxxabi.h> +#include <dlfcn.h> +#include <execinfo.h> +#endif + +#if ENABLE(REMOTE_INSPECTOR) +#include "JSGlobalObjectDebuggable.h" +#include "RemoteInspector.h" +#endif + +using namespace JSC; + +namespace Inspector { + +JSGlobalObjectInspectorController::JSGlobalObjectInspectorController(JSGlobalObject& globalObject) + : m_globalObject(globalObject) + , m_injectedScriptManager(std::make_unique<InjectedScriptManager>(*this, InjectedScriptHost::create())) + , m_executionStopwatch(Stopwatch::create()) + , m_scriptDebugServer(globalObject) + , m_frontendRouter(FrontendRouter::create()) + , m_backendDispatcher(BackendDispatcher::create(m_frontendRouter.copyRef())) +{ + AgentContext baseContext = { + *this, + *m_injectedScriptManager, + m_frontendRouter.get(), + m_backendDispatcher.get() + }; + + JSAgentContext context = { + baseContext, + globalObject + }; + + auto inspectorAgent = std::make_unique<InspectorAgent>(context); + auto runtimeAgent = std::make_unique<JSGlobalObjectRuntimeAgent>(context); + auto heapAgent = std::make_unique<InspectorHeapAgent>(context); + auto consoleAgent = std::make_unique<JSGlobalObjectConsoleAgent>(context, heapAgent.get()); + auto debuggerAgent = std::make_unique<JSGlobalObjectDebuggerAgent>(context, consoleAgent.get()); + auto scriptProfilerAgent = std::make_unique<InspectorScriptProfilerAgent>(context); + + m_inspectorAgent = inspectorAgent.get(); + m_debuggerAgent = debuggerAgent.get(); + m_consoleAgent = consoleAgent.get(); + m_consoleClient = std::make_unique<JSGlobalObjectConsoleClient>(m_consoleAgent, m_debuggerAgent, scriptProfilerAgent.get()); + + m_agents.append(WTFMove(inspectorAgent)); + m_agents.append(WTFMove(runtimeAgent)); + m_agents.append(WTFMove(consoleAgent)); + m_agents.append(WTFMove(debuggerAgent)); + m_agents.append(WTFMove(heapAgent)); + m_agents.append(WTFMove(scriptProfilerAgent)); + + m_executionStopwatch->start(); +} + +JSGlobalObjectInspectorController::~JSGlobalObjectInspectorController() +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_augmentingClient) + m_augmentingClient->inspectorControllerDestroyed(); +#endif +} + +void JSGlobalObjectInspectorController::globalObjectDestroyed() +{ + ASSERT(!m_frontendRouter->hasFrontends()); + + m_injectedScriptManager->disconnect(); + + m_agents.discardValues(); +} + +void JSGlobalObjectInspectorController::connectFrontend(FrontendChannel* frontendChannel, bool isAutomaticInspection) +{ + ASSERT_ARG(frontendChannel, frontendChannel); + + m_isAutomaticInspection = isAutomaticInspection; + + bool connectedFirstFrontend = !m_frontendRouter->hasFrontends(); + m_frontendRouter->connectFrontend(frontendChannel); + + if (!connectedFirstFrontend) + return; + + // Keep the JSGlobalObject and VM alive while we are debugging it. + m_strongVM = &m_globalObject.vm(); + m_strongGlobalObject.set(m_globalObject.vm(), &m_globalObject); + + // FIXME: change this to notify agents which frontend has connected (by id). + m_agents.didCreateFrontendAndBackend(nullptr, nullptr); + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + m_inspectorAgent->activateExtraDomains(m_agents.extraDomains()); + + if (m_augmentingClient) + m_augmentingClient->inspectorConnected(); +#endif +} + +void JSGlobalObjectInspectorController::disconnectFrontend(FrontendChannel* frontendChannel) +{ + ASSERT_ARG(frontendChannel, frontendChannel); + + // FIXME: change this to notify agents which frontend has disconnected (by id). + m_agents.willDestroyFrontendAndBackend(DisconnectReason::InspectorDestroyed); + + m_frontendRouter->disconnectFrontend(frontendChannel); + + m_isAutomaticInspection = false; + + bool disconnectedLastFrontend = !m_frontendRouter->hasFrontends(); + if (!disconnectedLastFrontend) + return; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_augmentingClient) + m_augmentingClient->inspectorDisconnected(); +#endif + + // Remove our JSGlobalObject and VM references, we are done debugging it. + m_strongGlobalObject.clear(); + m_strongVM = nullptr; +} + +void JSGlobalObjectInspectorController::dispatchMessageFromFrontend(const String& message) +{ + m_backendDispatcher->dispatch(message); +} + +void JSGlobalObjectInspectorController::pause() +{ + ErrorString dummyError; + m_debuggerAgent->enable(dummyError); + m_debuggerAgent->pause(dummyError); +} + +void JSGlobalObjectInspectorController::appendAPIBacktrace(ScriptCallStack& callStack) +{ +#if OS(DARWIN) || (OS(LINUX) && !PLATFORM(GTK)) + static const int framesToShow = 31; + static const int framesToSkip = 3; // WTFGetBacktrace, appendAPIBacktrace, reportAPIException. + + void* samples[framesToShow + framesToSkip]; + int frames = framesToShow + framesToSkip; + WTFGetBacktrace(samples, &frames); + + void** stack = samples + framesToSkip; + int size = frames - framesToSkip; + for (int i = 0; i < size; ++i) { + const char* mangledName = nullptr; + char* cxaDemangled = nullptr; + Dl_info info; + if (dladdr(stack[i], &info) && info.dli_sname) + mangledName = info.dli_sname; + if (mangledName) + cxaDemangled = abi::__cxa_demangle(mangledName, nullptr, nullptr, nullptr); + if (mangledName || cxaDemangled) + callStack.append(ScriptCallFrame(cxaDemangled ? cxaDemangled : mangledName, ASCIILiteral("[native code]"), noSourceID, 0, 0)); + else + callStack.append(ScriptCallFrame(ASCIILiteral("?"), ASCIILiteral("[native code]"), noSourceID, 0, 0)); + free(cxaDemangled); + } +#else + UNUSED_PARAM(callStack); +#endif +} + +void JSGlobalObjectInspectorController::reportAPIException(ExecState* exec, Exception* exception) +{ + VM& vm = exec->vm(); + if (isTerminatedExecutionException(vm, exception)) + return; + + auto scope = DECLARE_CATCH_SCOPE(vm); + ErrorHandlingScope errorScope(vm); + + Ref<ScriptCallStack> callStack = createScriptCallStackFromException(exec, exception, ScriptCallStack::maxCallStackSizeToCapture); + if (includesNativeCallStackWhenReportingExceptions()) + appendAPIBacktrace(callStack.get()); + + // FIXME: <http://webkit.org/b/115087> Web Inspector: Should not evaluate JavaScript handling exceptions + // If this is a custom exception object, call toString on it to try and get a nice string representation for the exception. + String errorMessage = exception->value().toWTFString(exec); + scope.clearException(); + + if (JSGlobalObjectConsoleClient::logToSystemConsole()) { + if (callStack->size()) { + const ScriptCallFrame& callFrame = callStack->at(0); + ConsoleClient::printConsoleMessage(MessageSource::JS, MessageType::Log, MessageLevel::Error, errorMessage, callFrame.sourceURL(), callFrame.lineNumber(), callFrame.columnNumber()); + } else + ConsoleClient::printConsoleMessage(MessageSource::JS, MessageType::Log, MessageLevel::Error, errorMessage, String(), 0, 0); + } + + m_consoleAgent->addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::JS, MessageType::Log, MessageLevel::Error, errorMessage, WTFMove(callStack))); +} + +ConsoleClient* JSGlobalObjectInspectorController::consoleClient() const +{ + return m_consoleClient.get(); +} + +bool JSGlobalObjectInspectorController::developerExtrasEnabled() const +{ +#if ENABLE(REMOTE_INSPECTOR) + if (!RemoteInspector::singleton().enabled()) + return false; + + if (!m_globalObject.inspectorDebuggable().remoteDebuggingAllowed()) + return false; +#endif + + return true; +} + +InspectorFunctionCallHandler JSGlobalObjectInspectorController::functionCallHandler() const +{ + return JSC::call; +} + +InspectorEvaluateHandler JSGlobalObjectInspectorController::evaluateHandler() const +{ + return JSC::evaluate; +} + +void JSGlobalObjectInspectorController::frontendInitialized() +{ +#if ENABLE(REMOTE_INSPECTOR) + if (m_isAutomaticInspection) + m_globalObject.inspectorDebuggable().unpauseForInitializedInspector(); +#endif +} + +Ref<Stopwatch> JSGlobalObjectInspectorController::executionStopwatch() +{ + return m_executionStopwatch.copyRef(); +} + +JSGlobalObjectScriptDebugServer& JSGlobalObjectInspectorController::scriptDebugServer() +{ + return m_scriptDebugServer; +} + +VM& JSGlobalObjectInspectorController::vm() +{ + return m_globalObject.vm(); +} + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +void JSGlobalObjectInspectorController::appendExtraAgent(std::unique_ptr<InspectorAgentBase> agent) +{ + String domainName = agent->domainName(); + + // FIXME: change this to notify agents which frontend has connected (by id). + agent->didCreateFrontendAndBackend(nullptr, nullptr); + + m_agents.appendExtraAgent(WTFMove(agent)); + + m_inspectorAgent->activateExtraDomain(domainName); +} +#endif + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/JSGlobalObjectInspectorController.h b/Source/JavaScriptCore/inspector/JSGlobalObjectInspectorController.h new file mode 100644 index 000000000..26a568f60 --- /dev/null +++ b/Source/JavaScriptCore/inspector/JSGlobalObjectInspectorController.h @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorAgentRegistry.h" +#include "InspectorEnvironment.h" +#include "InspectorFrontendRouter.h" +#include "JSGlobalObjectScriptDebugServer.h" +#include <wtf/Forward.h> +#include <wtf/Noncopyable.h> +#include <wtf/text/WTFString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "AugmentableInspectorController.h" +#endif + +namespace JSC { +class ConsoleClient; +class Exception; +class ExecState; +class JSGlobalObject; +} + +namespace Inspector { + +class BackendDispatcher; +class FrontendChannel; +class InjectedScriptManager; +class InspectorAgent; +class InspectorConsoleAgent; +class InspectorDebuggerAgent; +class InspectorScriptProfilerAgent; +class JSGlobalObjectConsoleClient; +class ScriptCallStack; + +class JSGlobalObjectInspectorController final + : public InspectorEnvironment +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + , public AugmentableInspectorController +#endif +{ + WTF_MAKE_NONCOPYABLE(JSGlobalObjectInspectorController); + WTF_MAKE_FAST_ALLOCATED; +public: + JSGlobalObjectInspectorController(JSC::JSGlobalObject&); + ~JSGlobalObjectInspectorController(); + + void connectFrontend(FrontendChannel*, bool isAutomaticInspection); + void disconnectFrontend(FrontendChannel*); + + void dispatchMessageFromFrontend(const String&); + + void globalObjectDestroyed(); + + bool includesNativeCallStackWhenReportingExceptions() const { return m_includeNativeCallStackWithExceptions; } + void setIncludesNativeCallStackWhenReportingExceptions(bool includesNativeCallStack) { m_includeNativeCallStackWithExceptions = includesNativeCallStack; } + + void pause(); + void reportAPIException(JSC::ExecState*, JSC::Exception*); + + JSC::ConsoleClient* consoleClient() const; + + bool developerExtrasEnabled() const override; + bool canAccessInspectedScriptState(JSC::ExecState*) const override { return true; } + InspectorFunctionCallHandler functionCallHandler() const override; + InspectorEvaluateHandler evaluateHandler() const override; + void frontendInitialized() override; + Ref<WTF::Stopwatch> executionStopwatch() override; + JSGlobalObjectScriptDebugServer& scriptDebugServer() override; + JSC::VM& vm() override; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + AugmentableInspectorControllerClient* augmentableInspectorControllerClient() const override { return m_augmentingClient; } + void setAugmentableInspectorControllerClient(AugmentableInspectorControllerClient* client) override { m_augmentingClient = client; } + + const FrontendRouter& frontendRouter() const override { return m_frontendRouter.get(); } + BackendDispatcher& backendDispatcher() override { return m_backendDispatcher.get(); } + void appendExtraAgent(std::unique_ptr<InspectorAgentBase>) override; +#endif + +private: + void appendAPIBacktrace(ScriptCallStack&); + + JSC::JSGlobalObject& m_globalObject; + std::unique_ptr<InjectedScriptManager> m_injectedScriptManager; + std::unique_ptr<JSGlobalObjectConsoleClient> m_consoleClient; + Ref<WTF::Stopwatch> m_executionStopwatch; + JSGlobalObjectScriptDebugServer m_scriptDebugServer; + + AgentRegistry m_agents; + InspectorAgent* m_inspectorAgent { nullptr }; + InspectorConsoleAgent* m_consoleAgent { nullptr }; + InspectorDebuggerAgent* m_debuggerAgent { nullptr }; + + Ref<FrontendRouter> m_frontendRouter; + Ref<BackendDispatcher> m_backendDispatcher; + + // Used to keep the JSGlobalObject and VM alive while we are debugging it. + JSC::Strong<JSC::JSGlobalObject> m_strongGlobalObject; + RefPtr<JSC::VM> m_strongVM; + + bool m_includeNativeCallStackWithExceptions { true }; + bool m_isAutomaticInspection { false }; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + AugmentableInspectorControllerClient* m_augmentingClient { nullptr }; +#endif +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/JSGlobalObjectScriptDebugServer.cpp b/Source/JavaScriptCore/inspector/JSGlobalObjectScriptDebugServer.cpp new file mode 100644 index 000000000..667438b5b --- /dev/null +++ b/Source/JavaScriptCore/inspector/JSGlobalObjectScriptDebugServer.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSGlobalObjectScriptDebugServer.h" + +#include "EventLoop.h" +#include "JSCInlines.h" +#include "JSLock.h" + +using namespace JSC; + +namespace Inspector { + +JSGlobalObjectScriptDebugServer::JSGlobalObjectScriptDebugServer(JSGlobalObject& globalObject) + : ScriptDebugServer(globalObject.vm()) + , m_globalObject(globalObject) +{ +} + +void JSGlobalObjectScriptDebugServer::attachDebugger() +{ + attach(&m_globalObject); +} + +void JSGlobalObjectScriptDebugServer::detachDebugger(bool isBeingDestroyed) +{ + detach(&m_globalObject, isBeingDestroyed ? Debugger::GlobalObjectIsDestructing : Debugger::TerminatingDebuggingSession); + if (!isBeingDestroyed) + recompileAllJSFunctions(); +} + +void JSGlobalObjectScriptDebugServer::runEventLoopWhilePaused() +{ + // Drop all locks so another thread can work in the VM while we are nested. + JSC::JSLock::DropAllLocks dropAllLocks(&m_globalObject.vm()); + + EventLoop loop; + while (!m_doneProcessingDebuggerEvents && !loop.ended()) + loop.cycle(); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/JSGlobalObjectScriptDebugServer.h b/Source/JavaScriptCore/inspector/JSGlobalObjectScriptDebugServer.h new file mode 100644 index 000000000..6c63be080 --- /dev/null +++ b/Source/JavaScriptCore/inspector/JSGlobalObjectScriptDebugServer.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "ScriptDebugServer.h" + +namespace Inspector { + +class JSGlobalObjectScriptDebugServer final : public ScriptDebugServer { + WTF_MAKE_NONCOPYABLE(JSGlobalObjectScriptDebugServer); +public: + JSGlobalObjectScriptDebugServer(JSC::JSGlobalObject&); + virtual ~JSGlobalObjectScriptDebugServer() { } + + JSC::JSGlobalObject& globalObject() const { return m_globalObject; } + +private: + void attachDebugger() override; + void detachDebugger(bool isBeingDestroyed) override; + + void didPause(JSC::JSGlobalObject*) override { } + void didContinue(JSC::JSGlobalObject*) override { } + void runEventLoopWhilePaused() override; + bool isContentScript(JSC::ExecState*) const override { return false; } + + // NOTE: Currently all exceptions are reported at the API boundary through reportAPIException. + // Until a time comes where an exception can be caused outside of the API (e.g. setTimeout + // or some other async operation in a pure JSContext) we can ignore exceptions reported here. + void reportException(JSC::ExecState*, JSC::Exception*) const override { } + + JSC::JSGlobalObject& m_globalObject; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/JSInjectedScriptHost.cpp b/Source/JavaScriptCore/inspector/JSInjectedScriptHost.cpp index 3f2f1ed4a..828d0c04f 100644 --- a/Source/JavaScriptCore/inspector/JSInjectedScriptHost.cpp +++ b/Source/JavaScriptCore/inspector/JSInjectedScriptHost.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2013, 2015-2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,37 +26,54 @@ #include "config.h" #include "JSInjectedScriptHost.h" -#if ENABLE(INSPECTOR) - +#include "BuiltinNames.h" +#include "Completion.h" #include "DateInstance.h" +#include "DirectArguments.h" #include "Error.h" #include "InjectedScriptHost.h" +#include "IteratorOperations.h" #include "JSArray.h" +#include "JSBoundFunction.h" +#include "JSCInlines.h" #include "JSFunction.h" +#include "JSGlobalObjectFunctions.h" #include "JSInjectedScriptHostPrototype.h" +#include "JSMap.h" +#include "JSMapIterator.h" +#include "JSPromise.h" +#include "JSPropertyNameIterator.h" +#include "JSSet.h" +#include "JSSetIterator.h" +#include "JSStringIterator.h" #include "JSTypedArrays.h" +#include "JSWeakMap.h" +#include "JSWeakSet.h" +#include "JSWithScope.h" #include "ObjectConstructor.h" -#include "Operations.h" +#include "ProxyObject.h" #include "RegExpObject.h" +#include "ScopedArguments.h" #include "SourceCode.h" #include "TypedArrayInlines.h" +#include "WeakMapData.h" using namespace JSC; namespace Inspector { -const ClassInfo JSInjectedScriptHost::s_info = { "InjectedScriptHost", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSInjectedScriptHost) }; +const ClassInfo JSInjectedScriptHost::s_info = { "InjectedScriptHost", &Base::s_info, 0, CREATE_METHOD_TABLE(JSInjectedScriptHost) }; -JSInjectedScriptHost::JSInjectedScriptHost(VM& vm, Structure* structure, PassRefPtr<InjectedScriptHost> impl) +JSInjectedScriptHost::JSInjectedScriptHost(VM& vm, Structure* structure, Ref<InjectedScriptHost>&& impl) : JSDestructibleObject(vm, structure) - , m_impl(impl.leakRef()) + , m_wrapped(WTFMove(impl)) { } void JSInjectedScriptHost::finishCreation(VM& vm) { Base::finishCreation(vm); - ASSERT(inherits(info())); + ASSERT(inherits(vm, info())); } JSObject* JSInjectedScriptHost::createPrototype(VM& vm, JSGlobalObject* globalObject) @@ -70,23 +87,31 @@ void JSInjectedScriptHost::destroy(JSC::JSCell* cell) thisObject->JSInjectedScriptHost::~JSInjectedScriptHost(); } -void JSInjectedScriptHost::releaseImpl() +JSValue JSInjectedScriptHost::evaluate(ExecState* exec) const { - if (m_impl) { - m_impl->deref(); - m_impl = nullptr; - } + JSGlobalObject* globalObject = exec->lexicalGlobalObject(); + return globalObject->evalFunction(); } -JSInjectedScriptHost::~JSInjectedScriptHost() +JSValue JSInjectedScriptHost::evaluateWithScopeExtension(ExecState* exec) { - releaseImpl(); -} + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); -JSValue JSInjectedScriptHost::evaluate(ExecState* exec) const -{ - JSGlobalObject* globalObject = exec->lexicalGlobalObject(); - return globalObject->evalFunction(); + JSValue scriptValue = exec->argument(0); + if (!scriptValue.isString()) + return throwTypeError(exec, scope, ASCIILiteral("InjectedScriptHost.evaluateWithScopeExtension first argument must be a string.")); + + String program = asString(scriptValue)->value(exec); + RETURN_IF_EXCEPTION(scope, JSValue()); + + NakedPtr<Exception> exception; + JSObject* scopeExtension = exec->argument(1).getObject(); + JSValue result = JSC::evaluateWithScopeExtension(exec, makeSource(program, exec->callerSourceOrigin()), scopeExtension, exception); + if (exception) + throwException(exec, scope, exception); + + return result; } JSValue JSInjectedScriptHost::internalConstructorName(ExecState* exec) @@ -94,9 +119,8 @@ JSValue JSInjectedScriptHost::internalConstructorName(ExecState* exec) if (exec->argumentCount() < 1) return jsUndefined(); - JSObject* thisObject = jsCast<JSObject*>(exec->uncheckedArgument(0).toThis(exec, NotStrictMode)); - String result = thisObject->methodTable()->className(thisObject); - return jsString(exec, result); + JSObject* object = jsCast<JSObject*>(exec->uncheckedArgument(0).toThis(exec, NotStrictMode)); + return jsString(exec, JSObject::calculatedClassName(object)); } JSValue JSInjectedScriptHost::isHTMLAllCollection(ExecState* exec) @@ -104,12 +128,14 @@ JSValue JSInjectedScriptHost::isHTMLAllCollection(ExecState* exec) if (exec->argumentCount() < 1) return jsUndefined(); + VM& vm = exec->vm(); JSValue value = exec->uncheckedArgument(0); - return jsBoolean(impl().isHTMLAllCollection(value)); + return jsBoolean(impl().isHTMLAllCollection(vm, value)); } -JSValue JSInjectedScriptHost::type(ExecState* exec) +JSValue JSInjectedScriptHost::subtype(ExecState* exec) { + VM& vm = exec->vm(); if (exec->argumentCount() < 1) return jsUndefined(); @@ -120,21 +146,58 @@ JSValue JSInjectedScriptHost::type(ExecState* exec) return exec->vm().smallStrings.booleanString(); if (value.isNumber()) return exec->vm().smallStrings.numberString(); + if (value.isSymbol()) + return exec->vm().smallStrings.symbolString(); + + JSObject* object = asObject(value); + if (object) { + if (object->isErrorInstance()) + return jsNontrivialString(exec, ASCIILiteral("error")); + + // Consider class constructor functions class objects. + JSFunction* function = jsDynamicCast<JSFunction*>(vm, value); + if (function && function->isClassConstructorFunction()) + return jsNontrivialString(exec, ASCIILiteral("class")); + } - if (value.inherits(JSArray::info())) + if (value.inherits(vm, JSArray::info())) return jsNontrivialString(exec, ASCIILiteral("array")); - if (value.inherits(DateInstance::info())) + if (value.inherits(vm, DirectArguments::info()) || value.inherits(vm, ScopedArguments::info())) + return jsNontrivialString(exec, ASCIILiteral("array")); + + if (value.inherits(vm, DateInstance::info())) return jsNontrivialString(exec, ASCIILiteral("date")); - if (value.inherits(RegExpObject::info())) + if (value.inherits(vm, RegExpObject::info())) return jsNontrivialString(exec, ASCIILiteral("regexp")); - if (value.inherits(JSInt8Array::info()) || value.inherits(JSInt16Array::info()) || value.inherits(JSInt32Array::info())) + if (value.inherits(vm, ProxyObject::info())) + return jsNontrivialString(exec, ASCIILiteral("proxy")); + + if (value.inherits(vm, JSMap::info())) + return jsNontrivialString(exec, ASCIILiteral("map")); + if (value.inherits(vm, JSSet::info())) + return jsNontrivialString(exec, ASCIILiteral("set")); + if (value.inherits(vm, JSWeakMap::info())) + return jsNontrivialString(exec, ASCIILiteral("weakmap")); + if (value.inherits(vm, JSWeakSet::info())) + return jsNontrivialString(exec, ASCIILiteral("weakset")); + + if (value.inherits(vm, JSMapIterator::info()) + || value.inherits(vm, JSSetIterator::info()) + || value.inherits(vm, JSStringIterator::info()) + || value.inherits(vm, JSPropertyNameIterator::info())) + return jsNontrivialString(exec, ASCIILiteral("iterator")); + + if (object && object->getDirect(exec->vm(), exec->vm().propertyNames->builtinNames().arrayIteratorNextIndexPrivateName())) + return jsNontrivialString(exec, ASCIILiteral("iterator")); + + if (value.inherits(vm, JSInt8Array::info()) || value.inherits(vm, JSInt16Array::info()) || value.inherits(vm, JSInt32Array::info())) return jsNontrivialString(exec, ASCIILiteral("array")); - if (value.inherits(JSUint8Array::info()) || value.inherits(JSUint16Array::info()) || value.inherits(JSUint32Array::info())) + if (value.inherits(vm, JSUint8Array::info()) || value.inherits(vm, JSUint16Array::info()) || value.inherits(vm, JSUint32Array::info())) return jsNontrivialString(exec, ASCIILiteral("array")); - if (value.inherits(JSFloat32Array::info()) || value.inherits(JSFloat64Array::info())) + if (value.inherits(vm, JSFloat32Array::info()) || value.inherits(vm, JSFloat64Array::info())) return jsNontrivialString(exec, ASCIILiteral("array")); - return impl().type(exec, value); + return impl().subtype(exec, value); } JSValue JSInjectedScriptHost::functionDetails(ExecState* exec) @@ -142,34 +205,42 @@ JSValue JSInjectedScriptHost::functionDetails(ExecState* exec) if (exec->argumentCount() < 1) return jsUndefined(); + VM& vm = exec->vm(); JSValue value = exec->uncheckedArgument(0); - if (!value.asCell()->inherits(JSFunction::info())) + if (!value.asCell()->inherits(vm, JSFunction::info())) return jsUndefined(); + // FIXME: This should provide better details for JSBoundFunctions. + JSFunction* function = jsCast<JSFunction*>(value); const SourceCode* sourceCode = function->sourceCode(); if (!sourceCode) return jsUndefined(); - int lineNumber = sourceCode->firstLine(); + // In the inspector protocol all positions are 0-based while in SourceCode they are 1-based + int lineNumber = sourceCode->firstLine().oneBasedInt(); if (lineNumber) - lineNumber -= 1; // In the inspector protocol all positions are 0-based while in SourceCode they are 1-based + lineNumber -= 1; + int columnNumber = sourceCode->startColumn().oneBasedInt(); + if (columnNumber) + columnNumber -= 1; String scriptID = String::number(sourceCode->provider()->asID()); JSObject* location = constructEmptyObject(exec); - location->putDirect(exec->vm(), Identifier(exec, "lineNumber"), jsNumber(lineNumber)); - location->putDirect(exec->vm(), Identifier(exec, "scriptId"), jsString(exec, scriptID)); + location->putDirect(vm, Identifier::fromString(exec, "scriptId"), jsString(exec, scriptID)); + location->putDirect(vm, Identifier::fromString(exec, "lineNumber"), jsNumber(lineNumber)); + location->putDirect(vm, Identifier::fromString(exec, "columnNumber"), jsNumber(columnNumber)); JSObject* result = constructEmptyObject(exec); - result->putDirect(exec->vm(), Identifier(exec, "location"), location); + result->putDirect(vm, Identifier::fromString(exec, "location"), location); - String name = function->name(exec); + String name = function->name(vm); if (!name.isEmpty()) - result->putDirect(exec->vm(), Identifier(exec, "name"), jsString(exec, name)); + result->putDirect(vm, Identifier::fromString(exec, "name"), jsString(exec, name)); - String displayName = function->displayName(exec); + String displayName = function->displayName(vm); if (!displayName.isEmpty()) - result->putDirect(exec->vm(), Identifier(exec, "displayName"), jsString(exec, displayName)); + result->putDirect(vm, Identifier::fromString(exec, "displayName"), jsString(exec, displayName)); // FIXME: provide function scope data in "scopesRaw" property when JSC supports it. // <https://webkit.org/b/87192> [JSC] expose function (closure) inner context to debugger @@ -177,29 +248,344 @@ JSValue JSInjectedScriptHost::functionDetails(ExecState* exec) return result; } -JSValue JSInjectedScriptHost::getInternalProperties(ExecState*) +static JSObject* constructInternalProperty(ExecState* exec, const String& name, JSValue value) { - // FIXME: <https://webkit.org/b/94533> [JSC] expose object inner properties to debugger + JSObject* result = constructEmptyObject(exec); + result->putDirect(exec->vm(), Identifier::fromString(exec, "name"), jsString(exec, name)); + result->putDirect(exec->vm(), Identifier::fromString(exec, "value"), value); + return result; +} + +JSValue JSInjectedScriptHost::getInternalProperties(ExecState* exec) +{ + if (exec->argumentCount() < 1) + return jsUndefined(); + + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSValue value = exec->uncheckedArgument(0); + + if (JSPromise* promise = jsDynamicCast<JSPromise*>(vm, value)) { + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr); + RETURN_IF_EXCEPTION(scope, JSValue()); + switch (promise->status(exec->vm())) { + case JSPromise::Status::Pending: + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, ASCIILiteral("status"), jsNontrivialString(exec, ASCIILiteral("pending")))); + return array; + case JSPromise::Status::Fulfilled: + array->putDirectIndex(exec, index++, constructInternalProperty(exec, ASCIILiteral("status"), jsNontrivialString(exec, ASCIILiteral("resolved")))); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, ASCIILiteral("result"), promise->result(exec->vm()))); + return array; + case JSPromise::Status::Rejected: + array->putDirectIndex(exec, index++, constructInternalProperty(exec, ASCIILiteral("status"), jsNontrivialString(exec, ASCIILiteral("rejected")))); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, ASCIILiteral("result"), promise->result(exec->vm()))); + return array; + } + // FIXME: <https://webkit.org/b/141664> Web Inspector: ES6: Improved Support for Promises - Promise Reactions + RELEASE_ASSERT_NOT_REACHED(); + } + + if (JSBoundFunction* boundFunction = jsDynamicCast<JSBoundFunction*>(vm, value)) { + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr); + RETURN_IF_EXCEPTION(scope, JSValue()); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "targetFunction", boundFunction->targetFunction())); + RETURN_IF_EXCEPTION(scope, JSValue()); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "boundThis", boundFunction->boundThis())); + RETURN_IF_EXCEPTION(scope, JSValue()); + if (boundFunction->boundArgs()) { + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "boundArgs", boundFunction->boundArgs())); + return array; + } + return array; + } + + if (ProxyObject* proxy = jsDynamicCast<ProxyObject*>(vm, value)) { + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr, 2); + RETURN_IF_EXCEPTION(scope, JSValue()); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, ASCIILiteral("target"), proxy->target())); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, ASCIILiteral("handler"), proxy->handler())); + return array; + } + + if (JSObject* iteratorObject = jsDynamicCast<JSObject*>(vm, value)) { + if (iteratorObject->getDirect(exec->vm(), exec->vm().propertyNames->builtinNames().arrayIteratorNextIndexPrivateName())) { + JSValue iteratedValue = iteratorObject->getDirect(exec->vm(), exec->vm().propertyNames->builtinNames().iteratedObjectPrivateName()); + JSValue kind = iteratorObject->getDirect(exec->vm(), exec->vm().propertyNames->builtinNames().arrayIteratorKindPrivateName()); + + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr, 2); + RETURN_IF_EXCEPTION(scope, JSValue()); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "array", iteratedValue)); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "kind", kind)); + return array; + } + } + + if (JSMapIterator* mapIterator = jsDynamicCast<JSMapIterator*>(vm, value)) { + String kind; + switch (mapIterator->kind()) { + case IterateKey: + kind = ASCIILiteral("key"); + break; + case IterateValue: + kind = ASCIILiteral("value"); + break; + case IterateKeyValue: + kind = ASCIILiteral("key+value"); + break; + } + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr, 2); + RETURN_IF_EXCEPTION(scope, JSValue()); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "map", mapIterator->iteratedValue())); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "kind", jsNontrivialString(exec, kind))); + return array; + } + + if (JSSetIterator* setIterator = jsDynamicCast<JSSetIterator*>(vm, value)) { + String kind; + switch (setIterator->kind()) { + case IterateKey: + kind = ASCIILiteral("key"); + break; + case IterateValue: + kind = ASCIILiteral("value"); + break; + case IterateKeyValue: + kind = ASCIILiteral("key+value"); + break; + } + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr, 2); + RETURN_IF_EXCEPTION(scope, JSValue()); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "set", setIterator->iteratedValue())); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "kind", jsNontrivialString(exec, kind))); + return array; + } + + if (JSStringIterator* stringIterator = jsDynamicCast<JSStringIterator*>(vm, value)) { + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr, 1); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "string", stringIterator->iteratedValue(exec))); + return array; + } + + if (JSPropertyNameIterator* propertyNameIterator = jsDynamicCast<JSPropertyNameIterator*>(vm, value)) { + unsigned index = 0; + JSArray* array = constructEmptyArray(exec, nullptr, 1); + RETURN_IF_EXCEPTION(scope, JSValue()); + scope.release(); + array->putDirectIndex(exec, index++, constructInternalProperty(exec, "object", propertyNameIterator->iteratedValue())); + return array; + } + return jsUndefined(); } -JSValue toJS(ExecState* exec, JSGlobalObject* globalObject, InjectedScriptHost* impl) +JSValue JSInjectedScriptHost::proxyTargetValue(ExecState *exec) +{ + if (exec->argumentCount() < 1) + return jsUndefined(); + + VM& vm = exec->vm(); + JSValue value = exec->uncheckedArgument(0); + ProxyObject* proxy = jsDynamicCast<ProxyObject*>(vm, value); + if (!proxy) + return jsUndefined(); + + JSObject* target = proxy->target(); + while (ProxyObject* proxy = jsDynamicCast<ProxyObject*>(vm, target)) + target = proxy->target(); + + return target; +} + +JSValue JSInjectedScriptHost::weakMapSize(ExecState* exec) { - if (!impl) - return jsNull(); + if (exec->argumentCount() < 1) + return jsUndefined(); - JSObject* prototype = JSInjectedScriptHost::createPrototype(exec->vm(), globalObject); - Structure* structure = JSInjectedScriptHost::createStructure(exec->vm(), globalObject, prototype); - JSInjectedScriptHost* injectedScriptHost = JSInjectedScriptHost::create(exec->vm(), structure, impl); + VM& vm = exec->vm(); + JSValue value = exec->uncheckedArgument(0); + JSWeakMap* weakMap = jsDynamicCast<JSWeakMap*>(vm, value); + if (!weakMap) + return jsUndefined(); - return injectedScriptHost; + return jsNumber(weakMap->weakMapData()->size()); } -JSInjectedScriptHost* toJSInjectedScriptHost(JSValue value) +JSValue JSInjectedScriptHost::weakMapEntries(ExecState* exec) { - return value.inherits(JSInjectedScriptHost::info()) ? jsCast<JSInjectedScriptHost*>(value) : nullptr; + if (exec->argumentCount() < 1) + return jsUndefined(); + + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSValue value = exec->uncheckedArgument(0); + JSWeakMap* weakMap = jsDynamicCast<JSWeakMap*>(vm, value); + if (!weakMap) + return jsUndefined(); + + unsigned fetched = 0; + unsigned numberToFetch = 100; + + JSValue numberToFetchArg = exec->argument(1); + double fetchDouble = numberToFetchArg.toInteger(exec); + if (fetchDouble >= 0) + numberToFetch = static_cast<unsigned>(fetchDouble); + + JSArray* array = constructEmptyArray(exec, nullptr); + RETURN_IF_EXCEPTION(scope, JSValue()); + for (auto it = weakMap->weakMapData()->begin(); it != weakMap->weakMapData()->end(); ++it) { + JSObject* entry = constructEmptyObject(exec); + entry->putDirect(exec->vm(), Identifier::fromString(exec, "key"), it->key); + entry->putDirect(exec->vm(), Identifier::fromString(exec, "value"), it->value.get()); + array->putDirectIndex(exec, fetched++, entry); + RETURN_IF_EXCEPTION(scope, JSValue()); + if (numberToFetch && fetched >= numberToFetch) + break; + } + + return array; } -} // namespace Inspector +JSValue JSInjectedScriptHost::weakSetSize(ExecState* exec) +{ + if (exec->argumentCount() < 1) + return jsUndefined(); -#endif // ENABLE(INSPECTOR) + VM& vm = exec->vm(); + JSValue value = exec->uncheckedArgument(0); + JSWeakSet* weakSet = jsDynamicCast<JSWeakSet*>(vm, value); + if (!weakSet) + return jsUndefined(); + + return jsNumber(weakSet->weakMapData()->size()); +} + +JSValue JSInjectedScriptHost::weakSetEntries(ExecState* exec) +{ + if (exec->argumentCount() < 1) + return jsUndefined(); + + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSValue value = exec->uncheckedArgument(0); + JSWeakSet* weakSet = jsDynamicCast<JSWeakSet*>(vm, value); + if (!weakSet) + return jsUndefined(); + + unsigned fetched = 0; + unsigned numberToFetch = 100; + + JSValue numberToFetchArg = exec->argument(1); + double fetchDouble = numberToFetchArg.toInteger(exec); + if (fetchDouble >= 0) + numberToFetch = static_cast<unsigned>(fetchDouble); + + JSArray* array = constructEmptyArray(exec, nullptr); + RETURN_IF_EXCEPTION(scope, JSValue()); + for (auto it = weakSet->weakMapData()->begin(); it != weakSet->weakMapData()->end(); ++it) { + JSObject* entry = constructEmptyObject(exec); + entry->putDirect(exec->vm(), Identifier::fromString(exec, "value"), it->key); + array->putDirectIndex(exec, fetched++, entry); + RETURN_IF_EXCEPTION(scope, JSValue()); + if (numberToFetch && fetched >= numberToFetch) + break; + } + + return array; +} + +static JSObject* cloneArrayIteratorObject(ExecState* exec, VM& vm, JSObject* iteratorObject, JSValue nextIndex) +{ + ASSERT(iteratorObject->type() == FinalObjectType); + JSObject* clone = constructEmptyObject(exec, iteratorObject->structure()); + clone->putDirect(vm, vm.propertyNames->builtinNames().arrayIteratorNextIndexPrivateName(), nextIndex); + clone->putDirect(vm, vm.propertyNames->builtinNames().iteratedObjectPrivateName(), iteratorObject->getDirect(vm, vm.propertyNames->builtinNames().iteratedObjectPrivateName())); + clone->putDirect(vm, vm.propertyNames->builtinNames().arrayIteratorIsDonePrivateName(), iteratorObject->getDirect(vm, vm.propertyNames->builtinNames().arrayIteratorIsDonePrivateName())); + clone->putDirect(vm, vm.propertyNames->builtinNames().arrayIteratorNextPrivateName(), iteratorObject->getDirect(vm, vm.propertyNames->builtinNames().arrayIteratorNextPrivateName())); + return clone; +} + +JSValue JSInjectedScriptHost::iteratorEntries(ExecState* exec) +{ + if (exec->argumentCount() < 1) + return jsUndefined(); + + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSValue iterator; + JSValue value = exec->uncheckedArgument(0); + if (JSMapIterator* mapIterator = jsDynamicCast<JSMapIterator*>(vm, value)) + iterator = mapIterator->clone(exec); + else if (JSSetIterator* setIterator = jsDynamicCast<JSSetIterator*>(vm, value)) + iterator = setIterator->clone(exec); + else if (JSStringIterator* stringIterator = jsDynamicCast<JSStringIterator*>(vm, value)) + iterator = stringIterator->clone(exec); + else if (JSPropertyNameIterator* propertyNameIterator = jsDynamicCast<JSPropertyNameIterator*>(vm, value)) { + iterator = propertyNameIterator->clone(exec); + RETURN_IF_EXCEPTION(scope, JSValue()); + } else { + if (JSObject* iteratorObject = jsDynamicCast<JSObject*>(vm, value)) { + // Array Iterators are created in JS for performance reasons. Thus the only way to know we have one is to + // look for a property that is unique to them. + if (JSValue nextIndex = iteratorObject->getDirect(vm, vm.propertyNames->builtinNames().arrayIteratorNextIndexPrivateName())) + iterator = cloneArrayIteratorObject(exec, vm, iteratorObject, nextIndex); + } + } + if (!iterator) + return jsUndefined(); + + unsigned numberToFetch = 5; + JSValue numberToFetchArg = exec->argument(1); + double fetchDouble = numberToFetchArg.toInteger(exec); + if (fetchDouble >= 0) + numberToFetch = static_cast<unsigned>(fetchDouble); + + JSArray* array = constructEmptyArray(exec, nullptr); + RETURN_IF_EXCEPTION(scope, JSValue()); + + for (unsigned i = 0; i < numberToFetch; ++i) { + JSValue next = iteratorStep(exec, iterator); + if (UNLIKELY(scope.exception())) + break; + if (next.isFalse()) + break; + + JSValue nextValue = iteratorValue(exec, next); + if (UNLIKELY(scope.exception())) + break; + + JSObject* entry = constructEmptyObject(exec); + entry->putDirect(exec->vm(), Identifier::fromString(exec, "value"), nextValue); + array->putDirectIndex(exec, i, entry); + if (UNLIKELY(scope.exception())) + break; + } + + iteratorClose(exec, iterator); + + return array; +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/JSInjectedScriptHost.h b/Source/JavaScriptCore/inspector/JSInjectedScriptHost.h index dc2356802..ede75437a 100644 --- a/Source/JavaScriptCore/inspector/JSInjectedScriptHost.h +++ b/Source/JavaScriptCore/inspector/JSInjectedScriptHost.h @@ -23,10 +23,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef JSInjectedScriptHost_h -#define JSInjectedScriptHost_h - -#if ENABLE(INSPECTOR) +#pragma once #include "JSDestructibleObject.h" @@ -37,6 +34,7 @@ class InjectedScriptHost; class JSInjectedScriptHost : public JSC::JSDestructibleObject { public: typedef JSC::JSDestructibleObject Base; + static const unsigned StructureFlags = Base::StructureFlags; DECLARE_INFO; @@ -45,9 +43,9 @@ public: return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } - static JSInjectedScriptHost* create(JSC::VM& vm, JSC::Structure* structure, PassRefPtr<InjectedScriptHost> impl) + static JSInjectedScriptHost* create(JSC::VM& vm, JSC::Structure* structure, Ref<InjectedScriptHost>&& impl) { - JSInjectedScriptHost* instance = new (NotNull, JSC::allocateCell<JSInjectedScriptHost>(vm.heap)) JSInjectedScriptHost(vm, structure, impl); + JSInjectedScriptHost* instance = new (NotNull, JSC::allocateCell<JSInjectedScriptHost>(vm.heap)) JSInjectedScriptHost(vm, structure, WTFMove(impl)); instance->finishCreation(vm); return instance; } @@ -55,36 +53,32 @@ public: static JSC::JSObject* createPrototype(JSC::VM&, JSC::JSGlobalObject*); static void destroy(JSC::JSCell*); - InjectedScriptHost& impl() const { return *m_impl; } - void releaseImpl(); + InjectedScriptHost& impl() const { return m_wrapped; } // Attributes. JSC::JSValue evaluate(JSC::ExecState*) const; // Functions. + JSC::JSValue evaluateWithScopeExtension(JSC::ExecState*); JSC::JSValue internalConstructorName(JSC::ExecState*); JSC::JSValue isHTMLAllCollection(JSC::ExecState*); - JSC::JSValue type(JSC::ExecState*); + JSC::JSValue subtype(JSC::ExecState*); JSC::JSValue functionDetails(JSC::ExecState*); JSC::JSValue getInternalProperties(JSC::ExecState*); + JSC::JSValue proxyTargetValue(JSC::ExecState*); + JSC::JSValue weakMapSize(JSC::ExecState*); + JSC::JSValue weakMapEntries(JSC::ExecState*); + JSC::JSValue weakSetSize(JSC::ExecState*); + JSC::JSValue weakSetEntries(JSC::ExecState*); + JSC::JSValue iteratorEntries(JSC::ExecState*); protected: - static const unsigned StructureFlags = Base::StructureFlags; - void finishCreation(JSC::VM&); private: - JSInjectedScriptHost(JSC::VM&, JSC::Structure*, PassRefPtr<InjectedScriptHost>); - ~JSInjectedScriptHost(); + JSInjectedScriptHost(JSC::VM&, JSC::Structure*, Ref<InjectedScriptHost>&&); - InjectedScriptHost* m_impl; + Ref<InjectedScriptHost> m_wrapped; }; -JSC::JSValue toJS(JSC::ExecState*, JSC::JSGlobalObject*, InjectedScriptHost*); -JSInjectedScriptHost* toJSInjectedScriptHost(JSC::JSValue); - } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(JSInjectedScriptHost_h) diff --git a/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.cpp b/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.cpp index 12c7a5021..a6f716879 100644 --- a/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.cpp +++ b/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2013, 2015-2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,13 +26,11 @@ #include "config.h" #include "JSInjectedScriptHostPrototype.h" -#if ENABLE(INSPECTOR) - #include "Error.h" #include "GetterSetter.h" #include "Identifier.h" #include "InjectedScriptHost.h" -#include "JSCJSValueInlines.h" +#include "JSCInlines.h" #include "JSFunction.h" #include "JSInjectedScriptHost.h" @@ -40,101 +38,213 @@ using namespace JSC; namespace Inspector { -static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionType(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionSubtype(ExecState*); static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionFunctionDetails(ExecState*); static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionGetInternalProperties(ExecState*); static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionInternalConstructorName(ExecState*); static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionIsHTMLAllCollection(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionProxyTargetValue(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakMapSize(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakMapEntries(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakSetSize(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakSetEntries(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionIteratorEntries(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionEvaluateWithScopeExtension(ExecState*); static EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeAttributeEvaluate(ExecState*); -const ClassInfo JSInjectedScriptHostPrototype::s_info = { "InjectedScriptHost", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSInjectedScriptHostPrototype) }; +const ClassInfo JSInjectedScriptHostPrototype::s_info = { "InjectedScriptHost", &Base::s_info, 0, CREATE_METHOD_TABLE(JSInjectedScriptHostPrototype) }; void JSInjectedScriptHostPrototype::finishCreation(VM& vm, JSGlobalObject* globalObject) { Base::finishCreation(vm); - ASSERT(inherits(info())); + ASSERT(inherits(vm, info())); vm.prototypeMap.addPrototype(this); - JSC_NATIVE_FUNCTION("type", jsInjectedScriptHostPrototypeFunctionType, DontEnum, 1); - JSC_NATIVE_FUNCTION("functionDetails", jsInjectedScriptHostPrototypeFunctionFunctionDetails, DontEnum, 1); - JSC_NATIVE_FUNCTION("getInternalProperties", jsInjectedScriptHostPrototypeFunctionGetInternalProperties, DontEnum, 1); - JSC_NATIVE_FUNCTION("internalConstructorName", jsInjectedScriptHostPrototypeFunctionInternalConstructorName, DontEnum, 1); - JSC_NATIVE_FUNCTION("isHTMLAllCollection", jsInjectedScriptHostPrototypeFunctionIsHTMLAllCollection, DontEnum, 1); - - Identifier evaluateIdentifier(&vm, "evaluate"); - GetterSetter* accessor = GetterSetter::create(vm); - JSFunction* function = JSFunction::create(vm, globalObject, 0, evaluateIdentifier.string(), jsInjectedScriptHostPrototypeAttributeEvaluate); - accessor->setGetter(vm, function); - putDirectNonIndexAccessor(vm, evaluateIdentifier, accessor, DontEnum | Accessor); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("subtype", jsInjectedScriptHostPrototypeFunctionSubtype, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("functionDetails", jsInjectedScriptHostPrototypeFunctionFunctionDetails, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("getInternalProperties", jsInjectedScriptHostPrototypeFunctionGetInternalProperties, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("internalConstructorName", jsInjectedScriptHostPrototypeFunctionInternalConstructorName, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("isHTMLAllCollection", jsInjectedScriptHostPrototypeFunctionIsHTMLAllCollection, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("proxyTargetValue", jsInjectedScriptHostPrototypeFunctionProxyTargetValue, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("weakMapSize", jsInjectedScriptHostPrototypeFunctionWeakMapSize, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("weakMapEntries", jsInjectedScriptHostPrototypeFunctionWeakMapEntries, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("weakSetSize", jsInjectedScriptHostPrototypeFunctionWeakSetSize, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("weakSetEntries", jsInjectedScriptHostPrototypeFunctionWeakSetEntries, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("iteratorEntries", jsInjectedScriptHostPrototypeFunctionIteratorEntries, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("evaluateWithScopeExtension", jsInjectedScriptHostPrototypeFunctionEvaluateWithScopeExtension, DontEnum, 1); + + JSC_NATIVE_GETTER("evaluate", jsInjectedScriptHostPrototypeAttributeEvaluate, DontEnum | Accessor); } EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeAttributeEvaluate(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSInjectedScriptHost::info()); return JSValue::encode(castedThis->evaluate(exec)); } EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionInternalConstructorName(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSInjectedScriptHost::info()); return JSValue::encode(castedThis->internalConstructorName(exec)); } EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionIsHTMLAllCollection(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSInjectedScriptHost::info()); return JSValue::encode(castedThis->isHTMLAllCollection(exec)); } -EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionType(ExecState* exec) +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionProxyTargetValue(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSInjectedScriptHost::info()); - return JSValue::encode(castedThis->type(exec)); + return JSValue::encode(castedThis->proxyTargetValue(exec)); +} + +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakMapSize(ExecState* exec) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); + + return JSValue::encode(castedThis->weakMapSize(exec)); +} + +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakMapEntries(ExecState* exec) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); + + return JSValue::encode(castedThis->weakMapEntries(exec)); +} + +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakSetSize(ExecState* exec) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); + + return JSValue::encode(castedThis->weakSetSize(exec)); +} + +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionWeakSetEntries(ExecState* exec) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); + + return JSValue::encode(castedThis->weakSetEntries(exec)); +} + +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionIteratorEntries(ExecState* exec) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); + + return JSValue::encode(castedThis->iteratorEntries(exec)); +} + +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionEvaluateWithScopeExtension(ExecState* exec) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); + + return JSValue::encode(castedThis->evaluateWithScopeExtension(exec)); +} + +EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionSubtype(ExecState* exec) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); + + return JSValue::encode(castedThis->subtype(exec)); } EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionFunctionDetails(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSInjectedScriptHost::info()); return JSValue::encode(castedThis->functionDetails(exec)); } EncodedJSValue JSC_HOST_CALL jsInjectedScriptHostPrototypeFunctionGetInternalProperties(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSInjectedScriptHost* castedThis = jsDynamicCast<JSInjectedScriptHost*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSInjectedScriptHost::info()); return JSValue::encode(castedThis->getInternalProperties(exec)); } } // namespace Inspector -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.h b/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.h index 9d0b7b666..58e9e5504 100644 --- a/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.h +++ b/Source/JavaScriptCore/inspector/JSInjectedScriptHostPrototype.h @@ -23,10 +23,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef JSInjectedScriptHostPrototype_h -#define JSInjectedScriptHostPrototype_h - -#if ENABLE(INSPECTOR) +#pragma once #include "JSObject.h" @@ -35,6 +32,7 @@ namespace Inspector { class JSInjectedScriptHostPrototype : public JSC::JSNonFinalObject { public: typedef JSC::JSNonFinalObject Base; + static const unsigned StructureFlags = Base::StructureFlags | JSC::OverridesGetOwnPropertySlot; DECLARE_INFO; @@ -50,9 +48,6 @@ public: return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } -protected: - static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | Base::StructureFlags; - private: JSInjectedScriptHostPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(vm, structure) @@ -62,7 +57,3 @@ private: }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(JSInjectedScriptHostPrototype_h) diff --git a/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.cpp b/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.cpp index 08fd618a8..1916c5dc8 100644 --- a/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.cpp +++ b/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (C) 2014, 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,30 +26,29 @@ #include "config.h" #include "JSJavaScriptCallFrame.h" -#if ENABLE(INSPECTOR) - +#include "DebuggerScope.h" #include "Error.h" -#include "JSCJSValue.h" -#include "JSCellInlines.h" +#include "IdentifierInlines.h" +#include "JSCInlines.h" #include "JSJavaScriptCallFramePrototype.h" -#include "StructureInlines.h" +#include "ObjectConstructor.h" using namespace JSC; namespace Inspector { -const ClassInfo JSJavaScriptCallFrame::s_info = { "JavaScriptCallFrame", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSJavaScriptCallFrame) }; +const ClassInfo JSJavaScriptCallFrame::s_info = { "JavaScriptCallFrame", &Base::s_info, 0, CREATE_METHOD_TABLE(JSJavaScriptCallFrame) }; -JSJavaScriptCallFrame::JSJavaScriptCallFrame(VM& vm, Structure* structure, PassRefPtr<JavaScriptCallFrame> impl) +JSJavaScriptCallFrame::JSJavaScriptCallFrame(VM& vm, Structure* structure, Ref<JavaScriptCallFrame>&& impl) : JSDestructibleObject(vm, structure) - , m_impl(impl.leakRef()) + , m_impl(&impl.leakRef()) { } void JSJavaScriptCallFrame::finishCreation(VM& vm) { Base::finishCreation(vm); - ASSERT(inherits(info())); + ASSERT(inherits(vm, info())); } JSObject* JSJavaScriptCallFrame::createPrototype(VM& vm, JSGlobalObject* globalObject) @@ -65,10 +64,8 @@ void JSJavaScriptCallFrame::destroy(JSC::JSCell* cell) void JSJavaScriptCallFrame::releaseImpl() { - if (m_impl) { - m_impl->deref(); - m_impl = nullptr; - } + if (auto impl = std::exchange(m_impl, nullptr)) + impl->deref(); } JSJavaScriptCallFrame::~JSJavaScriptCallFrame() @@ -76,55 +73,83 @@ JSJavaScriptCallFrame::~JSJavaScriptCallFrame() releaseImpl(); } -JSValue JSJavaScriptCallFrame::evaluate(ExecState* exec) +JSValue JSJavaScriptCallFrame::evaluateWithScopeExtension(ExecState* exec) { - JSValue exception; - JSValue result = impl().evaluate(exec->argument(0).toString(exec)->value(exec), exception); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue scriptValue = exec->argument(0); + if (!scriptValue.isString()) + return throwTypeError(exec, scope, ASCIILiteral("JSJavaScriptCallFrame.evaluateWithScopeExtension first argument must be a string.")); + + String script = asString(scriptValue)->value(exec); + RETURN_IF_EXCEPTION(scope, JSValue()); + + NakedPtr<Exception> exception; + JSObject* scopeExtension = exec->argument(1).getObject(); + JSValue result = impl().evaluateWithScopeExtension(script, scopeExtension, exception); if (exception) - exec->vm().throwException(exec, exception); + throwException(exec, scope, exception); return result; } -JSValue JSJavaScriptCallFrame::scopeType(ExecState* exec) +static JSValue valueForScopeType(DebuggerScope* scope) { - if (!impl().scopeChain()) - return jsUndefined(); + if (scope->isCatchScope()) + return jsNumber(JSJavaScriptCallFrame::CATCH_SCOPE); + if (scope->isFunctionNameScope()) + return jsNumber(JSJavaScriptCallFrame::FUNCTION_NAME_SCOPE); + if (scope->isWithScope()) + return jsNumber(JSJavaScriptCallFrame::WITH_SCOPE); + if (scope->isNestedLexicalScope()) + return jsNumber(JSJavaScriptCallFrame::NESTED_LEXICAL_SCOPE); + if (scope->isGlobalLexicalEnvironment()) + return jsNumber(JSJavaScriptCallFrame::GLOBAL_LEXICAL_ENVIRONMENT_SCOPE); + if (scope->isGlobalScope()) + return jsNumber(JSJavaScriptCallFrame::GLOBAL_SCOPE); - if (!exec->argument(0).isInt32()) + ASSERT(scope->isClosureScope()); + return jsNumber(JSJavaScriptCallFrame::CLOSURE_SCOPE); +} + +static JSValue valueForScopeLocation(ExecState* exec, const DebuggerLocation& location) +{ + if (location.sourceID == noSourceID) + return jsNull(); + + // Debugger.Location protocol object. + JSObject* result = constructEmptyObject(exec); + result->putDirect(exec->vm(), Identifier::fromString(exec, "scriptId"), jsString(exec, String::number(location.sourceID))); + result->putDirect(exec->vm(), Identifier::fromString(exec, "lineNumber"), jsNumber(location.line)); + result->putDirect(exec->vm(), Identifier::fromString(exec, "columnNumber"), jsNumber(location.column)); + return result; +} + +JSValue JSJavaScriptCallFrame::scopeDescriptions(ExecState* exec) +{ + VM& vm = exec->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + + DebuggerScope* scopeChain = impl().scopeChain(); + if (!scopeChain) return jsUndefined(); - int index = exec->argument(0).asInt32(); - - JSScope* scopeChain = impl().scopeChain(); - ScopeChainIterator end = scopeChain->end(); - - // FIXME: We should be identifying and returning CATCH_SCOPE appropriately. - - bool foundLocalScope = false; - for (ScopeChainIterator iter = scopeChain->begin(); iter != end; ++iter) { - JSObject* scope = iter.get(); - if (scope->isActivationObject()) { - if (!foundLocalScope) { - // First activation object is local scope, each successive activation object is closure. - if (!index) - return jsNumber(JSJavaScriptCallFrame::LOCAL_SCOPE); - foundLocalScope = true; - } else if (!index) - return jsNumber(JSJavaScriptCallFrame::CLOSURE_SCOPE); - } - - if (!index) { - // Last in the chain is global scope. - if (++iter == end) - return jsNumber(JSJavaScriptCallFrame::GLOBAL_SCOPE); - return jsNumber(JSJavaScriptCallFrame::WITH_SCOPE); - } - - --index; + + int index = 0; + JSArray* array = constructEmptyArray(exec, nullptr); + + DebuggerScope::iterator end = scopeChain->end(); + for (DebuggerScope::iterator iter = scopeChain->begin(); iter != end; ++iter) { + DebuggerScope* scope = iter.get(); + JSObject* description = constructEmptyObject(exec); + description->putDirect(exec->vm(), Identifier::fromString(exec, "type"), valueForScopeType(scope)); + description->putDirect(exec->vm(), Identifier::fromString(exec, "name"), jsString(exec, scope->name())); + description->putDirect(exec->vm(), Identifier::fromString(exec, "location"), valueForScopeLocation(exec, scope->location())); + array->putDirectIndex(exec, index++, description); + RETURN_IF_EXCEPTION(throwScope, JSValue()); } - ASSERT_NOT_REACHED(); - return jsUndefined(); + return array; } JSValue JSJavaScriptCallFrame::caller(ExecState* exec) const @@ -157,9 +182,9 @@ JSValue JSJavaScriptCallFrame::scopeChain(ExecState* exec) const if (!impl().scopeChain()) return jsNull(); - JSScope* scopeChain = impl().scopeChain(); - ScopeChainIterator iter = scopeChain->begin(); - ScopeChainIterator end = scopeChain->end(); + DebuggerScope* scopeChain = impl().scopeChain(); + DebuggerScope::iterator iter = scopeChain->begin(); + DebuggerScope::iterator end = scopeChain->end(); // We must always have something in the scope chain. ASSERT(iter != end); @@ -178,6 +203,11 @@ JSValue JSJavaScriptCallFrame::thisObject(ExecState*) const return impl().thisValue(); } +JSValue JSJavaScriptCallFrame::isTailDeleted(JSC::ExecState*) const +{ + return jsBoolean(impl().isTailDeleted()); +} + JSValue JSJavaScriptCallFrame::type(ExecState* exec) const { switch (impl().type()) { @@ -198,16 +228,10 @@ JSValue toJS(ExecState* exec, JSGlobalObject* globalObject, JavaScriptCallFrame* JSObject* prototype = JSJavaScriptCallFrame::createPrototype(exec->vm(), globalObject); Structure* structure = JSJavaScriptCallFrame::createStructure(exec->vm(), globalObject, prototype); - JSJavaScriptCallFrame* javaScriptCallFrame = JSJavaScriptCallFrame::create(exec->vm(), structure, impl); + JSJavaScriptCallFrame* javaScriptCallFrame = JSJavaScriptCallFrame::create(exec->vm(), structure, *impl); return javaScriptCallFrame; } -JSJavaScriptCallFrame* toJSJavaScriptCallFrame(JSValue value) -{ - return value.inherits(JSJavaScriptCallFrame::info()) ? jsCast<JSJavaScriptCallFrame*>(value) : nullptr; -} - } // namespace Inspector -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.h b/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.h index dbbb93fa2..2ac247cae 100644 --- a/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.h +++ b/Source/JavaScriptCore/inspector/JSJavaScriptCallFrame.h @@ -23,10 +23,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef JSJavaScriptCallFrame_h -#define JSJavaScriptCallFrame_h - -#if ENABLE(INSPECTOR) +#pragma once #include "JSDestructibleObject.h" #include "JavaScriptCallFrame.h" @@ -36,6 +33,7 @@ namespace Inspector { class JSJavaScriptCallFrame : public JSC::JSDestructibleObject { public: typedef JSC::JSDestructibleObject Base; + static const unsigned StructureFlags = Base::StructureFlags; DECLARE_INFO; @@ -44,9 +42,9 @@ public: return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } - static JSJavaScriptCallFrame* create(JSC::VM& vm, JSC::Structure* structure, PassRefPtr<JavaScriptCallFrame> impl) + static JSJavaScriptCallFrame* create(JSC::VM& vm, JSC::Structure* structure, Ref<JavaScriptCallFrame>&& impl) { - JSJavaScriptCallFrame* instance = new (NotNull, JSC::allocateCell<JSJavaScriptCallFrame>(vm.heap)) JSJavaScriptCallFrame(vm, structure, impl); + JSJavaScriptCallFrame* instance = new (NotNull, JSC::allocateCell<JSJavaScriptCallFrame>(vm.heap)) JSJavaScriptCallFrame(vm, structure, WTFMove(impl)); instance->finishCreation(vm); return instance; } @@ -58,8 +56,8 @@ public: void releaseImpl(); // Functions. - JSC::JSValue evaluate(JSC::ExecState*); - JSC::JSValue scopeType(JSC::ExecState*); + JSC::JSValue evaluateWithScopeExtension(JSC::ExecState*); + JSC::JSValue scopeDescriptions(JSC::ExecState*); // Attributes. JSC::JSValue caller(JSC::ExecState*) const; @@ -70,31 +68,27 @@ public: JSC::JSValue scopeChain(JSC::ExecState*) const; JSC::JSValue thisObject(JSC::ExecState*) const; JSC::JSValue type(JSC::ExecState*) const; + JSC::JSValue isTailDeleted(JSC::ExecState*) const; // Constants. static const unsigned short GLOBAL_SCOPE = 0; - static const unsigned short LOCAL_SCOPE = 1; - static const unsigned short WITH_SCOPE = 2; - static const unsigned short CLOSURE_SCOPE = 3; - static const unsigned short CATCH_SCOPE = 4; + static const unsigned short WITH_SCOPE = 1; + static const unsigned short CLOSURE_SCOPE = 2; + static const unsigned short CATCH_SCOPE = 3; + static const unsigned short FUNCTION_NAME_SCOPE = 4; + static const unsigned short GLOBAL_LEXICAL_ENVIRONMENT_SCOPE = 5; + static const unsigned short NESTED_LEXICAL_SCOPE = 6; protected: - static const unsigned StructureFlags = Base::StructureFlags; - void finishCreation(JSC::VM&); private: - JSJavaScriptCallFrame(JSC::VM&, JSC::Structure*, PassRefPtr<JavaScriptCallFrame>); + JSJavaScriptCallFrame(JSC::VM&, JSC::Structure*, Ref<JavaScriptCallFrame>&&); ~JSJavaScriptCallFrame(); JavaScriptCallFrame* m_impl; }; JSC::JSValue toJS(JSC::ExecState*, JSC::JSGlobalObject*, JavaScriptCallFrame*); -JSJavaScriptCallFrame* toJSJavaScriptCallFrame(JSC::JSValue); } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(JSJavaScriptCallFrame_h) diff --git a/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.cpp b/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.cpp index d74126cb2..3a0a8a980 100644 --- a/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.cpp +++ b/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (C) 2014, 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,12 +26,9 @@ #include "config.h" #include "JSJavaScriptCallFramePrototype.h" -#if ENABLE(INSPECTOR) - #include "Error.h" -#include "GetterSetter.h" #include "Identifier.h" -#include "JSCJSValueInlines.h" +#include "JSCInlines.h" #include "JSFunction.h" #include "JSJavaScriptCallFrame.h" @@ -40,8 +37,8 @@ using namespace JSC; namespace Inspector { // Functions. -static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionEvaluate(ExecState*); -static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionScopeType(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionEvaluateWithScopeExtension(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionScopeDescriptions(ExecState*); // Attributes. static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeCaller(ExecState*); @@ -52,185 +49,171 @@ static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeFunctionName(E static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeScopeChain(ExecState*); static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeThisObject(ExecState*); static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeType(ExecState*); +static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameIsTailDeleted(ExecState*); -// Constants. -static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantGLOBAL_SCOPE(ExecState*); -static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantLOCAL_SCOPE(ExecState*); -static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantWITH_SCOPE(ExecState*); -static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantCLOSURE_SCOPE(ExecState*); -static EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantCATCH_SCOPE(ExecState*); - -const ClassInfo JSJavaScriptCallFramePrototype::s_info = { "JavaScriptCallFrame", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSJavaScriptCallFramePrototype) }; - -#define JSC_NATIVE_NON_INDEX_ACCESSOR(jsName, cppName, attributes) \ - { \ - Identifier identifier(&vm, jsName); \ - GetterSetter* accessor = GetterSetter::create(vm); \ - JSFunction* function = JSFunction::create(vm, globalObject, 0, identifier.string(), cppName); \ - accessor->setGetter(vm, function); \ - putDirectNonIndexAccessor(vm, identifier, accessor, (attributes)); \ - } +const ClassInfo JSJavaScriptCallFramePrototype::s_info = { "JavaScriptCallFrame", &Base::s_info, 0, CREATE_METHOD_TABLE(JSJavaScriptCallFramePrototype) }; void JSJavaScriptCallFramePrototype::finishCreation(VM& vm, JSGlobalObject* globalObject) { Base::finishCreation(vm); - ASSERT(inherits(info())); + ASSERT(inherits(vm, info())); vm.prototypeMap.addPrototype(this); - JSC_NATIVE_FUNCTION("evaluate", jsJavaScriptCallFramePrototypeFunctionEvaluate, DontEnum, 1); - JSC_NATIVE_FUNCTION("scopeType", jsJavaScriptCallFramePrototypeFunctionScopeType, DontEnum, 1); - - JSC_NATIVE_NON_INDEX_ACCESSOR("caller", jsJavaScriptCallFrameAttributeCaller, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("sourceID", jsJavaScriptCallFrameAttributeSourceID, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("line", jsJavaScriptCallFrameAttributeLine, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("column", jsJavaScriptCallFrameAttributeColumn, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("functionName", jsJavaScriptCallFrameAttributeFunctionName, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("scopeChain", jsJavaScriptCallFrameAttributeScopeChain, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("thisObject", jsJavaScriptCallFrameAttributeThisObject, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("type", jsJavaScriptCallFrameAttributeType, DontEnum | Accessor); - - JSC_NATIVE_NON_INDEX_ACCESSOR("GLOBAL_SCOPE", jsJavaScriptCallFrameConstantGLOBAL_SCOPE, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("LOCAL_SCOPE", jsJavaScriptCallFrameConstantLOCAL_SCOPE, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("WITH_SCOPE", jsJavaScriptCallFrameConstantWITH_SCOPE, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("CLOSURE_SCOPE", jsJavaScriptCallFrameConstantCLOSURE_SCOPE, DontEnum | Accessor); - JSC_NATIVE_NON_INDEX_ACCESSOR("CATCH_SCOPE", jsJavaScriptCallFrameConstantCATCH_SCOPE, DontEnum | Accessor); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("evaluateWithScopeExtension", jsJavaScriptCallFramePrototypeFunctionEvaluateWithScopeExtension, DontEnum, 1); + JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("scopeDescriptions", jsJavaScriptCallFramePrototypeFunctionScopeDescriptions, DontEnum, 0); + + JSC_NATIVE_GETTER("caller", jsJavaScriptCallFrameAttributeCaller, DontEnum | Accessor); + JSC_NATIVE_GETTER("sourceID", jsJavaScriptCallFrameAttributeSourceID, DontEnum | Accessor); + JSC_NATIVE_GETTER("line", jsJavaScriptCallFrameAttributeLine, DontEnum | Accessor); + JSC_NATIVE_GETTER("column", jsJavaScriptCallFrameAttributeColumn, DontEnum | Accessor); + JSC_NATIVE_GETTER("functionName", jsJavaScriptCallFrameAttributeFunctionName, DontEnum | Accessor); + JSC_NATIVE_GETTER("scopeChain", jsJavaScriptCallFrameAttributeScopeChain, DontEnum | Accessor); + JSC_NATIVE_GETTER("thisObject", jsJavaScriptCallFrameAttributeThisObject, DontEnum | Accessor); + JSC_NATIVE_GETTER("type", jsJavaScriptCallFrameAttributeType, DontEnum | Accessor); + JSC_NATIVE_GETTER("isTailDeleted", jsJavaScriptCallFrameIsTailDeleted, DontEnum | Accessor); } -EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionEvaluate(ExecState* exec) +EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionEvaluateWithScopeExtension(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); - return JSValue::encode(castedThis->evaluate(exec)); + return JSValue::encode(castedThis->evaluateWithScopeExtension(exec)); } -EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionScopeType(ExecState* exec) +EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFramePrototypeFunctionScopeDescriptions(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); - return JSValue::encode(castedThis->scopeType(exec)); + return JSValue::encode(castedThis->scopeDescriptions(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeCaller(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->caller(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeSourceID(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->sourceID(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeLine(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->line(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeColumn(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->column(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeFunctionName(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->functionName(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeScopeChain(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->scopeChain(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeThisObject(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->thisObject(exec)); } EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameAttributeType(ExecState* exec) { - JSValue thisValue = exec->hostThisValue(); - JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(thisValue); + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); if (!castedThis) - return throwVMTypeError(exec); + return throwVMTypeError(exec, scope); - ASSERT_GC_OBJECT_INHERITS(castedThis, JSJavaScriptCallFrame::info()); return JSValue::encode(castedThis->type(exec)); } -EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantGLOBAL_SCOPE(ExecState*) +EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameIsTailDeleted(ExecState* exec) { - return JSValue::encode(jsNumber(JSJavaScriptCallFrame::GLOBAL_SCOPE)); -} + VM& vm = exec->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); -EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantLOCAL_SCOPE(ExecState*) -{ - return JSValue::encode(jsNumber(JSJavaScriptCallFrame::LOCAL_SCOPE)); -} - -EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantWITH_SCOPE(ExecState*) -{ - return JSValue::encode(jsNumber(JSJavaScriptCallFrame::WITH_SCOPE)); -} - -EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantCLOSURE_SCOPE(ExecState*) -{ - return JSValue::encode(jsNumber(JSJavaScriptCallFrame::CLOSURE_SCOPE)); -} + JSValue thisValue = exec->thisValue(); + JSJavaScriptCallFrame* castedThis = jsDynamicCast<JSJavaScriptCallFrame*>(vm, thisValue); + if (!castedThis) + return throwVMTypeError(exec, scope); -EncodedJSValue JSC_HOST_CALL jsJavaScriptCallFrameConstantCATCH_SCOPE(ExecState*) -{ - return JSValue::encode(jsNumber(JSJavaScriptCallFrame::CATCH_SCOPE)); + return JSValue::encode(castedThis->isTailDeleted(exec)); } } // namespace Inspector - -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.h b/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.h index b868c53e2..c69e94a4e 100644 --- a/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.h +++ b/Source/JavaScriptCore/inspector/JSJavaScriptCallFramePrototype.h @@ -23,10 +23,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef JSJavaScriptCallFramePrototype_h -#define JSJavaScriptCallFramePrototype_h - -#if ENABLE(INSPECTOR) +#pragma once #include "JSObject.h" @@ -35,6 +32,7 @@ namespace Inspector { class JSJavaScriptCallFramePrototype : public JSC::JSNonFinalObject { public: typedef JSC::JSNonFinalObject Base; + static const unsigned StructureFlags = Base::StructureFlags | JSC::OverridesGetOwnPropertySlot; DECLARE_INFO; @@ -50,9 +48,6 @@ public: return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } -protected: - static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | Base::StructureFlags; - private: JSJavaScriptCallFramePrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(vm, structure) @@ -62,7 +57,3 @@ private: }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(JSJavaScriptCallFramePrototype_h) diff --git a/Source/JavaScriptCore/inspector/JavaScriptCallFrame.cpp b/Source/JavaScriptCore/inspector/JavaScriptCallFrame.cpp index f735a8aa6..3c28484ae 100644 --- a/Source/JavaScriptCore/inspector/JavaScriptCallFrame.cpp +++ b/Source/JavaScriptCore/inspector/JavaScriptCallFrame.cpp @@ -26,14 +26,12 @@ #include "config.h" #include "JavaScriptCallFrame.h" -#if ENABLE(INSPECTOR) - using namespace JSC; namespace Inspector { -JavaScriptCallFrame::JavaScriptCallFrame(PassRefPtr<DebuggerCallFrame> debuggerCallFrame) - : m_debuggerCallFrame(debuggerCallFrame) +JavaScriptCallFrame::JavaScriptCallFrame(Ref<DebuggerCallFrame>&& debuggerCallFrame) + : m_debuggerCallFrame(WTFMove(debuggerCallFrame)) { } @@ -46,10 +44,9 @@ JavaScriptCallFrame* JavaScriptCallFrame::caller() if (!debuggerCallerFrame) return nullptr; - m_caller = create(debuggerCallerFrame); + m_caller = create(debuggerCallerFrame.releaseNonNull()); return m_caller.get(); } } // namespace Inspector -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/JavaScriptCallFrame.h b/Source/JavaScriptCore/inspector/JavaScriptCallFrame.h index b584067a2..ee1f8aea3 100644 --- a/Source/JavaScriptCore/inspector/JavaScriptCallFrame.h +++ b/Source/JavaScriptCore/inspector/JavaScriptCallFrame.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008, 2013 Apple Inc. All Rights Reserved. + * Copyright (C) 2008, 2013-2014 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,16 +23,12 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef JavaScriptCallFrame_h -#define JavaScriptCallFrame_h - -#if ENABLE(INSPECTOR) +#pragma once #include "JSCJSValueInlines.h" #include "debugger/DebuggerCallFrame.h" #include "interpreter/CallFrame.h" #include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> #include <wtf/text/TextPosition.h> @@ -40,9 +36,9 @@ namespace Inspector { class JavaScriptCallFrame : public RefCounted<JavaScriptCallFrame> { public: - static PassRefPtr<JavaScriptCallFrame> create(PassRefPtr<JSC::DebuggerCallFrame> debuggerCallFrame) + static Ref<JavaScriptCallFrame> create(Ref<JSC::DebuggerCallFrame>&& debuggerCallFrame) { - return adoptRef(new JavaScriptCallFrame(debuggerCallFrame)); + return adoptRef(*new JavaScriptCallFrame(WTFMove(debuggerCallFrame))); } JavaScriptCallFrame* caller(); @@ -53,21 +49,18 @@ public: String functionName() const { return m_debuggerCallFrame->functionName(); } JSC::DebuggerCallFrame::Type type() const { return m_debuggerCallFrame->type(); } - JSC::JSScope* scopeChain() const { return m_debuggerCallFrame->scope(); } + JSC::DebuggerScope* scopeChain() const { return m_debuggerCallFrame->scope(); } JSC::JSGlobalObject* vmEntryGlobalObject() const { return m_debuggerCallFrame->vmEntryGlobalObject(); } + bool isTailDeleted() const { return m_debuggerCallFrame->isTailDeleted(); } JSC::JSValue thisValue() const { return m_debuggerCallFrame->thisValue(); } - JSC::JSValue evaluate(const String& script, JSC::JSValue& exception) const { return m_debuggerCallFrame->evaluate(script, exception); } + JSC::JSValue evaluateWithScopeExtension(const String& script, JSC::JSObject* scopeExtension, NakedPtr<JSC::Exception>& exception) const { return m_debuggerCallFrame->evaluateWithScopeExtension(script, scopeExtension, exception); } private: - JavaScriptCallFrame(PassRefPtr<JSC::DebuggerCallFrame>); + JavaScriptCallFrame(Ref<JSC::DebuggerCallFrame>&&); - RefPtr<JSC::DebuggerCallFrame> m_debuggerCallFrame; + Ref<JSC::DebuggerCallFrame> m_debuggerCallFrame; RefPtr<JavaScriptCallFrame> m_caller; }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // JavaScriptCallFrame_h diff --git a/Source/JavaScriptCore/inspector/PerGlobalObjectWrapperWorld.cpp b/Source/JavaScriptCore/inspector/PerGlobalObjectWrapperWorld.cpp new file mode 100644 index 000000000..c9b7abd8f --- /dev/null +++ b/Source/JavaScriptCore/inspector/PerGlobalObjectWrapperWorld.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PerGlobalObjectWrapperWorld.h" + +using namespace JSC; + +namespace Inspector { + +JSValue PerGlobalObjectWrapperWorld::getWrapper(JSGlobalObject* globalObject) +{ + auto it = m_wrappers.find(globalObject); + if (it != m_wrappers.end()) + return it->value.get(); + return JSValue(); +} + +void PerGlobalObjectWrapperWorld::addWrapper(JSGlobalObject* globalObject, JSObject* object) +{ + Strong<JSObject> wrapper(globalObject->vm(), object); + m_wrappers.add(globalObject, wrapper); +} + +void PerGlobalObjectWrapperWorld::clearAllWrappers() +{ + m_wrappers.clear(); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/PerGlobalObjectWrapperWorld.h b/Source/JavaScriptCore/inspector/PerGlobalObjectWrapperWorld.h new file mode 100644 index 000000000..51adaed06 --- /dev/null +++ b/Source/JavaScriptCore/inspector/PerGlobalObjectWrapperWorld.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "JSCJSValueInlines.h" +#include "Strong.h" +#include "StrongInlines.h" +#include <wtf/HashMap.h> + +namespace Inspector { + +class JS_EXPORT_PRIVATE PerGlobalObjectWrapperWorld { +public: + JSC::JSValue getWrapper(JSC::JSGlobalObject*); + void addWrapper(JSC::JSGlobalObject*, JSC::JSObject*); + void clearAllWrappers(); + +private: + HashMap<JSC::JSGlobalObject*, JSC::Strong<JSC::JSObject>> m_wrappers; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptArguments.cpp b/Source/JavaScriptCore/inspector/ScriptArguments.cpp new file mode 100644 index 000000000..ff131b581 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptArguments.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptArguments.h" + +#include "JSCInlines.h" +#include "ProxyObject.h" +#include "ScriptValue.h" + +namespace Inspector { + +Ref<ScriptArguments> ScriptArguments::create(JSC::ExecState* scriptState, Vector<Deprecated::ScriptValue>& arguments) +{ + return adoptRef(*new ScriptArguments(scriptState, arguments)); +} + +Ref<ScriptArguments> ScriptArguments::createEmpty(JSC::ExecState* scriptState) +{ + return adoptRef(*new ScriptArguments(scriptState)); +} + +ScriptArguments::ScriptArguments(JSC::ExecState* execState) + : m_globalObject(execState->vm(), execState->lexicalGlobalObject()) +{ +} + +ScriptArguments::ScriptArguments(JSC::ExecState* execState, Vector<Deprecated::ScriptValue>& arguments) + : m_globalObject(execState->vm(), execState->lexicalGlobalObject()) +{ + m_arguments.swap(arguments); +} + +ScriptArguments::~ScriptArguments() +{ +} + +const Deprecated::ScriptValue& ScriptArguments::argumentAt(size_t index) const +{ + ASSERT(m_arguments.size() > index); + return m_arguments[index]; +} + +JSC::ExecState* ScriptArguments::globalState() const +{ + if (m_globalObject) + return const_cast<JSC::JSGlobalObject*>(m_globalObject.get())->globalExec(); + + return nullptr; +} + +bool ScriptArguments::getFirstArgumentAsString(String& result) +{ + if (!argumentCount()) + return false; + + if (!globalState()) { + ASSERT_NOT_REACHED(); + return false; + } + + JSC::JSValue value = argumentAt(0).jsValue(); + if (JSC::jsDynamicCast<JSC::ProxyObject*>(globalState()->vm(), value)) { + result = ASCIILiteral("[object Proxy]"); + return true; + } + + result = argumentAt(0).toString(globalState()); + return true; +} + +bool ScriptArguments::isEqual(ScriptArguments* other) const +{ + if (!other) + return false; + + if (m_arguments.size() != other->m_arguments.size()) + return false; + if (!globalState() && m_arguments.size()) + return false; + + for (size_t i = 0; i < m_arguments.size(); ++i) { + if (!m_arguments[i].isEqual(other->globalState(), other->m_arguments[i])) + return false; + } + + return true; +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptArguments.h b/Source/JavaScriptCore/inspector/ScriptArguments.h new file mode 100644 index 000000000..50abd1bdf --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptArguments.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <heap/Strong.h> +#include <wtf/Forward.h> +#include <wtf/RefCounted.h> +#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace Deprecated { +class ScriptValue; +} + +namespace JSC { +class ExecState; +class JSGlobalObject; +} + +namespace Inspector { + +class JS_EXPORT_PRIVATE ScriptArguments : public RefCounted<ScriptArguments> { +public: + static Ref<ScriptArguments> create(JSC::ExecState*, Vector<Deprecated::ScriptValue>& arguments); + static Ref<ScriptArguments> createEmpty(JSC::ExecState*); + ~ScriptArguments(); + + const Deprecated::ScriptValue& argumentAt(size_t) const; + size_t argumentCount() const { return m_arguments.size(); } + + JSC::ExecState* globalState() const; + + bool getFirstArgumentAsString(String& result); + bool isEqual(ScriptArguments*) const; + +private: + ScriptArguments(JSC::ExecState*); + ScriptArguments(JSC::ExecState*, Vector<Deprecated::ScriptValue>& arguments); + + JSC::Strong<JSC::JSGlobalObject> m_globalObject; + Vector<Deprecated::ScriptValue> m_arguments; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptBreakpoint.h b/Source/JavaScriptCore/inspector/ScriptBreakpoint.h index e3d52424d..586041796 100644 --- a/Source/JavaScriptCore/inspector/ScriptBreakpoint.h +++ b/Source/JavaScriptCore/inspector/ScriptBreakpoint.h @@ -11,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -27,8 +27,7 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ScriptBreakpoint_h -#define ScriptBreakpoint_h +#pragma once #include <wtf/Vector.h> #include <wtf/text/WTFString.h> @@ -55,35 +54,38 @@ struct ScriptBreakpointAction { String data; }; +typedef Vector<ScriptBreakpointAction> BreakpointActions; + struct ScriptBreakpoint { ScriptBreakpoint() { } - ScriptBreakpoint(int lineNumber, int columnNumber, const String& condition, bool autoContinue) + ScriptBreakpoint(int lineNumber, int columnNumber, const String& condition, bool autoContinue, unsigned ignoreCount) : lineNumber(lineNumber) , columnNumber(columnNumber) , condition(condition) , autoContinue(autoContinue) + , ignoreCount(ignoreCount) { } - ScriptBreakpoint(int lineNumber, int columnNumber, const String& condition, Vector<ScriptBreakpointAction>& actions, bool autoContinue) + ScriptBreakpoint(int lineNumber, int columnNumber, const String& condition, BreakpointActions& actions, bool autoContinue, unsigned ignoreCount) : lineNumber(lineNumber) , columnNumber(columnNumber) , condition(condition) , actions(actions) , autoContinue(autoContinue) + , ignoreCount(ignoreCount) { } - int lineNumber; - int columnNumber; + int lineNumber { 0 }; + int columnNumber { 0 }; String condition; - Vector<ScriptBreakpointAction> actions; - bool autoContinue; + BreakpointActions actions; + bool autoContinue { false }; + unsigned ignoreCount { 0 }; }; } // namespace Inspector - -#endif // !defined(ScriptBreakpoint_h) diff --git a/Source/JavaScriptCore/inspector/ScriptCallFrame.cpp b/Source/JavaScriptCore/inspector/ScriptCallFrame.cpp new file mode 100644 index 000000000..44627ab74 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptCallFrame.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptCallFrame.h" + +#include "InspectorValues.h" + +namespace Inspector { + +ScriptCallFrame::ScriptCallFrame(const String& functionName, const String& scriptName, JSC::SourceID sourceID, unsigned lineNumber, unsigned column) + : m_functionName(functionName) + , m_scriptName(scriptName) + , m_sourceID(sourceID) + , m_lineNumber(lineNumber) + , m_column(column) +{ +} + +ScriptCallFrame::~ScriptCallFrame() +{ +} + +bool ScriptCallFrame::isEqual(const ScriptCallFrame& o) const +{ + // Ignore sourceID in isEqual in case of identical scripts executed multiple times + // that would get different script identifiers, but are otherwise the same. + return m_functionName == o.m_functionName + && m_scriptName == o.m_scriptName + && m_lineNumber == o.m_lineNumber + && m_column == o.m_column; +} + +bool ScriptCallFrame::isNative() const +{ + return m_scriptName == "[native code]"; +} + +Ref<Inspector::Protocol::Console::CallFrame> ScriptCallFrame::buildInspectorObject() const +{ + return Inspector::Protocol::Console::CallFrame::create() + .setFunctionName(m_functionName) + .setUrl(m_scriptName) + .setScriptId(String::number(m_sourceID)) + .setLineNumber(m_lineNumber) + .setColumnNumber(m_column) + .release(); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptCallFrame.h b/Source/JavaScriptCore/inspector/ScriptCallFrame.h new file mode 100644 index 000000000..f80b42638 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptCallFrame.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "DebuggerPrimitives.h" +#include "InspectorProtocolObjects.h" +#include <wtf/Forward.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class JS_EXPORT_PRIVATE ScriptCallFrame { +public: + ScriptCallFrame(const String& functionName, const String& scriptName, JSC::SourceID sourceID, unsigned lineNumber, unsigned column); + ~ScriptCallFrame(); + + const String& functionName() const { return m_functionName; } + const String& sourceURL() const { return m_scriptName; } + unsigned lineNumber() const { return m_lineNumber; } + unsigned columnNumber() const { return m_column; } + JSC::SourceID sourceID() const { return m_sourceID; } + + bool isEqual(const ScriptCallFrame&) const; + bool isNative() const; + + Ref<Inspector::Protocol::Console::CallFrame> buildInspectorObject() const; + +private: + String m_functionName; + String m_scriptName; + JSC::SourceID m_sourceID; + unsigned m_lineNumber; + unsigned m_column; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptCallStack.cpp b/Source/JavaScriptCore/inspector/ScriptCallStack.cpp new file mode 100644 index 000000000..612c448c4 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptCallStack.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (c) 2008, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptCallStack.h" + +#include "InspectorValues.h" + +namespace Inspector { + +Ref<ScriptCallStack> ScriptCallStack::create() +{ + return adoptRef(*new ScriptCallStack); +} + +Ref<ScriptCallStack> ScriptCallStack::create(Vector<ScriptCallFrame>& frames) +{ + return adoptRef(*new ScriptCallStack(frames)); +} + +ScriptCallStack::ScriptCallStack() +{ +} + +ScriptCallStack::ScriptCallStack(Vector<ScriptCallFrame>& frames) +{ + m_frames.swap(frames); +} + +ScriptCallStack::~ScriptCallStack() +{ +} + +const ScriptCallFrame& ScriptCallStack::at(size_t index) const +{ + ASSERT(m_frames.size() > index); + return m_frames[index]; +} + +size_t ScriptCallStack::size() const +{ + return m_frames.size(); +} + +const ScriptCallFrame* ScriptCallStack::firstNonNativeCallFrame() const +{ + if (!m_frames.size()) + return nullptr; + + for (const auto& frame : m_frames) { + if (!frame.isNative()) + return &frame; + } + + return nullptr; +} + +void ScriptCallStack::append(const ScriptCallFrame& frame) +{ + m_frames.append(frame); +} + +bool ScriptCallStack::isEqual(ScriptCallStack* o) const +{ + if (!o) + return false; + + size_t frameCount = o->m_frames.size(); + if (frameCount != m_frames.size()) + return false; + + for (size_t i = 0; i < frameCount; ++i) { + if (!m_frames[i].isEqual(o->m_frames[i])) + return false; + } + + return true; +} + +Ref<Inspector::Protocol::Array<Inspector::Protocol::Console::CallFrame>> ScriptCallStack::buildInspectorArray() const +{ + auto frames = Inspector::Protocol::Array<Inspector::Protocol::Console::CallFrame>::create(); + for (size_t i = 0; i < m_frames.size(); i++) + frames->addItem(m_frames.at(i).buildInspectorObject()); + return frames; +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptCallStack.h b/Source/JavaScriptCore/inspector/ScriptCallStack.h new file mode 100644 index 000000000..0f5e33249 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptCallStack.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (c) 2008, 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorProtocolObjects.h" +#include "ScriptCallFrame.h" +#include <wtf/Forward.h> +#include <wtf/RefCounted.h> +#include <wtf/Vector.h> + +namespace Inspector { + +class JS_EXPORT_PRIVATE ScriptCallStack : public RefCounted<ScriptCallStack> { +public: + static const size_t maxCallStackSizeToCapture = 200; + + static Ref<ScriptCallStack> create(); + static Ref<ScriptCallStack> create(Vector<ScriptCallFrame>&); + + ~ScriptCallStack(); + + const ScriptCallFrame& at(size_t) const; + size_t size() const; + + const ScriptCallFrame* firstNonNativeCallFrame() const; + + void append(const ScriptCallFrame&); + + bool isEqual(ScriptCallStack*) const; + + Ref<Inspector::Protocol::Array<Inspector::Protocol::Console::CallFrame>> buildInspectorArray() const; + +private: + ScriptCallStack(); + ScriptCallStack(Vector<ScriptCallFrame>&); + + Vector<ScriptCallFrame> m_frames; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptCallStackFactory.cpp b/Source/JavaScriptCore/inspector/ScriptCallStackFactory.cpp new file mode 100644 index 000000000..c47758fb4 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptCallStackFactory.cpp @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2014, 2016 Apple Inc. All rights reserved. + * Copyright (c) 2010 Google Inc. All rights reserved. + * Copyright (C) 2012 Research In Motion Limited. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptCallStackFactory.h" + +#include "CallFrame.h" +#include "CodeBlock.h" +#include "Exception.h" +#include "JSCJSValue.h" +#include "JSCInlines.h" +#include "ScriptArguments.h" +#include "ScriptCallFrame.h" +#include "ScriptCallStack.h" +#include "ScriptValue.h" +#include "StackVisitor.h" +#include <wtf/text/WTFString.h> + +using namespace JSC; + +namespace Inspector { + +class CreateScriptCallStackFunctor { +public: + CreateScriptCallStackFunctor(bool needToSkipAFrame, Vector<ScriptCallFrame>& frames, size_t remainingCapacity) + : m_needToSkipAFrame(needToSkipAFrame) + , m_frames(frames) + , m_remainingCapacityForFrameCapture(remainingCapacity) + { + } + + StackVisitor::Status operator()(StackVisitor& visitor) const + { + if (m_needToSkipAFrame) { + m_needToSkipAFrame = false; + return StackVisitor::Continue; + } + + if (m_remainingCapacityForFrameCapture) { + unsigned line; + unsigned column; + visitor->computeLineAndColumn(line, column); + m_frames.append(ScriptCallFrame(visitor->functionName(), visitor->sourceURL(), static_cast<SourceID>(visitor->sourceID()), line, column)); + + m_remainingCapacityForFrameCapture--; + return StackVisitor::Continue; + } + + return StackVisitor::Done; + } + +private: + mutable bool m_needToSkipAFrame; + Vector<ScriptCallFrame>& m_frames; + mutable size_t m_remainingCapacityForFrameCapture; +}; + +Ref<ScriptCallStack> createScriptCallStack(JSC::ExecState* exec, size_t maxStackSize) +{ + if (!exec) + return ScriptCallStack::create(); + + Vector<ScriptCallFrame> frames; + + CallFrame* frame = exec->vm().topCallFrame; + CreateScriptCallStackFunctor functor(false, frames, maxStackSize); + frame->iterate(functor); + + return ScriptCallStack::create(frames); +} + +Ref<ScriptCallStack> createScriptCallStackForConsole(JSC::ExecState* exec, size_t maxStackSize) +{ + if (!exec) + return ScriptCallStack::create(); + + Vector<ScriptCallFrame> frames; + + CallFrame* frame = exec->vm().topCallFrame; + CreateScriptCallStackFunctor functor(true, frames, maxStackSize); + frame->iterate(functor); + + if (frames.isEmpty()) { + CreateScriptCallStackFunctor functor(false, frames, maxStackSize); + frame->iterate(functor); + } + + return ScriptCallStack::create(frames); +} + +static void extractSourceInformationFromException(JSC::ExecState* exec, JSObject* exceptionObject, int* lineNumber, int* columnNumber, String* sourceURL) +{ + VM& vm = exec->vm(); + auto scope = DECLARE_CATCH_SCOPE(vm); + + // FIXME: <http://webkit.org/b/115087> Web Inspector: Should not need to evaluate JavaScript handling exceptions + JSValue lineValue = exceptionObject->getDirect(exec->vm(), Identifier::fromString(exec, "line")); + *lineNumber = lineValue && lineValue.isNumber() ? int(lineValue.toNumber(exec)) : 0; + JSValue columnValue = exceptionObject->getDirect(exec->vm(), Identifier::fromString(exec, "column")); + *columnNumber = columnValue && columnValue.isNumber() ? int(columnValue.toNumber(exec)) : 0; + JSValue sourceURLValue = exceptionObject->getDirect(exec->vm(), Identifier::fromString(exec, "sourceURL")); + *sourceURL = sourceURLValue && sourceURLValue.isString() ? sourceURLValue.toWTFString(exec) : ASCIILiteral("undefined"); + scope.clearException(); +} + +Ref<ScriptCallStack> createScriptCallStackFromException(JSC::ExecState* exec, JSC::Exception* exception, size_t maxStackSize) +{ + Vector<ScriptCallFrame> frames; + auto& stackTrace = exception->stack(); + VM& vm = exec->vm(); + for (size_t i = 0; i < stackTrace.size() && i < maxStackSize; i++) { + unsigned line; + unsigned column; + stackTrace[i].computeLineAndColumn(line, column); + String functionName = stackTrace[i].functionName(vm); + frames.append(ScriptCallFrame(functionName, stackTrace[i].sourceURL(), static_cast<SourceID>(stackTrace[i].sourceID()), line, column)); + } + + // Fallback to getting at least the line and sourceURL from the exception object if it has values and the exceptionStack doesn't. + if (exception->value().isObject()) { + JSObject* exceptionObject = exception->value().toObject(exec); + ASSERT(exceptionObject); + int lineNumber; + int columnNumber; + String exceptionSourceURL; + if (!frames.size()) { + extractSourceInformationFromException(exec, exceptionObject, &lineNumber, &columnNumber, &exceptionSourceURL); + frames.append(ScriptCallFrame(String(), exceptionSourceURL, noSourceID, lineNumber, columnNumber)); + } else { + if (!stackTrace[0].hasLineAndColumnInfo() || stackTrace[0].sourceURL().isEmpty()) { + const ScriptCallFrame& firstCallFrame = frames.first(); + extractSourceInformationFromException(exec, exceptionObject, &lineNumber, &columnNumber, &exceptionSourceURL); + frames[0] = ScriptCallFrame(firstCallFrame.functionName(), exceptionSourceURL, stackTrace[0].sourceID(), lineNumber, columnNumber); + } + } + } + + return ScriptCallStack::create(frames); +} + +Ref<ScriptArguments> createScriptArguments(JSC::ExecState* exec, unsigned skipArgumentCount) +{ + Vector<Deprecated::ScriptValue> arguments; + size_t argumentCount = exec->argumentCount(); + for (size_t i = skipArgumentCount; i < argumentCount; ++i) + arguments.append(Deprecated::ScriptValue(exec->vm(), exec->uncheckedArgument(i))); + return ScriptArguments::create(exec, arguments); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptCallStackFactory.h b/Source/JavaScriptCore/inspector/ScriptCallStackFactory.h new file mode 100644 index 000000000..d87edbe31 --- /dev/null +++ b/Source/JavaScriptCore/inspector/ScriptCallStackFactory.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <wtf/Forward.h> + +namespace JSC { +class Exception; +class ExecState; +class JSValue; +} + +namespace Inspector { + +class ScriptArguments; +class ScriptCallStack; + +// FIXME: The subtle differences between these should be eliminated. +JS_EXPORT_PRIVATE Ref<ScriptCallStack> createScriptCallStack(JSC::ExecState*, size_t maxStackSize); +JS_EXPORT_PRIVATE Ref<ScriptCallStack> createScriptCallStackForConsole(JSC::ExecState*, size_t maxStackSize); +JS_EXPORT_PRIVATE Ref<ScriptCallStack> createScriptCallStackFromException(JSC::ExecState*, JSC::Exception*, size_t maxStackSize); +JS_EXPORT_PRIVATE Ref<ScriptArguments> createScriptArguments(JSC::ExecState*, unsigned skipArgumentCount); + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptDebugListener.h b/Source/JavaScriptCore/inspector/ScriptDebugListener.h index bee3bc047..5b0bb9f41 100644 --- a/Source/JavaScriptCore/inspector/ScriptDebugListener.h +++ b/Source/JavaScriptCore/inspector/ScriptDebugListener.h @@ -11,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -27,55 +27,41 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ScriptDebugListener_h -#define ScriptDebugListener_h +#pragma once #include "debugger/Debugger.h" -#include <wtf/Forward.h> +#include "parser/SourceProvider.h" #include <wtf/text/WTFString.h> -namespace Deprecated { -class ScriptValue; -} - namespace Inspector { +struct ScriptBreakpointAction; + class ScriptDebugListener { public: - class Script { - public: - Script() - : startLine(0) - , startColumn(0) - , endLine(0) - , endColumn(0) - , isContentScript(false) - { - } - + struct Script { String url; String source; String sourceURL; String sourceMappingURL; - int startLine; - int startColumn; - int endLine; - int endColumn; - bool isContentScript; + RefPtr<JSC::SourceProvider> sourceProvider; + int startLine {0}; + int startColumn {0}; + int endLine {0}; + int endColumn {0}; + bool isContentScript {false}; }; virtual ~ScriptDebugListener() { } virtual void didParseSource(JSC::SourceID, const Script&) = 0; virtual void failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage) = 0; - virtual void didPause(JSC::ExecState*, const Deprecated::ScriptValue& callFrames, const Deprecated::ScriptValue& exception) = 0; - virtual void didSampleProbe(JSC::ExecState*, int probeIdentifier, int hitCount, const Deprecated::ScriptValue& result) = 0; + virtual void didPause(JSC::ExecState&, JSC::JSValue callFrames, JSC::JSValue exception) = 0; virtual void didContinue() = 0; - virtual void breakpointActionLog(JSC::ExecState*, const String&) = 0; - virtual void breakpointActionSound() = 0; + virtual void breakpointActionLog(JSC::ExecState&, const String&) = 0; + virtual void breakpointActionSound(int breakpointActionIdentifier) = 0; + virtual void breakpointActionProbe(JSC::ExecState&, const ScriptBreakpointAction&, unsigned batchId, unsigned sampleId, JSC::JSValue result) = 0; }; } // namespace Inspector - -#endif // ScriptDebugListener_h diff --git a/Source/JavaScriptCore/inspector/ScriptDebugServer.cpp b/Source/JavaScriptCore/inspector/ScriptDebugServer.cpp index b1151cf7f..84cefdf70 100644 --- a/Source/JavaScriptCore/inspector/ScriptDebugServer.cpp +++ b/Source/JavaScriptCore/inspector/ScriptDebugServer.cpp @@ -12,7 +12,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -32,25 +32,22 @@ #include "ScriptDebugServer.h" #include "DebuggerCallFrame.h" +#include "DebuggerScope.h" +#include "Exception.h" +#include "JSCInlines.h" #include "JSJavaScriptCallFrame.h" -#include "JSLock.h" #include "JavaScriptCallFrame.h" #include "ScriptValue.h" #include "SourceProvider.h" -#include <wtf/MainThread.h> #include <wtf/NeverDestroyed.h> -#include <wtf/TemporaryChange.h> -#include <wtf/text/WTFString.h> +#include <wtf/SetForScope.h> using namespace JSC; -using namespace Inspector; namespace Inspector { -ScriptDebugServer::ScriptDebugServer(bool isInWorkerThread) - : Debugger(isInWorkerThread) - , m_doneProcessingDebuggerEvents(true) - , m_callingListeners(false) +ScriptDebugServer::ScriptDebugServer(VM& vm) + : Debugger(vm) { } @@ -58,62 +55,67 @@ ScriptDebugServer::~ScriptDebugServer() { } -JSC::BreakpointID ScriptDebugServer::setBreakpoint(JSC::SourceID sourceID, const ScriptBreakpoint& scriptBreakpoint, unsigned* actualLineNumber, unsigned* actualColumnNumber) +void ScriptDebugServer::setBreakpointActions(BreakpointID id, const ScriptBreakpoint& scriptBreakpoint) { - if (!sourceID) - return JSC::noBreakpointID; - - JSC::Breakpoint breakpoint(sourceID, scriptBreakpoint.lineNumber, scriptBreakpoint.columnNumber, scriptBreakpoint.condition, scriptBreakpoint.autoContinue); - JSC::BreakpointID id = Debugger::setBreakpoint(breakpoint, *actualLineNumber, *actualColumnNumber); - if (id != JSC::noBreakpointID && !scriptBreakpoint.actions.isEmpty()) { -#ifndef NDEBUG - BreakpointIDToActionsMap::iterator it = m_breakpointIDToActions.find(id); - ASSERT(it == m_breakpointIDToActions.end()); -#endif - const Vector<ScriptBreakpointAction> &actions = scriptBreakpoint.actions; - m_breakpointIDToActions.set(id, actions); - } - return id; + ASSERT(id != noBreakpointID); + ASSERT(!m_breakpointIDToActions.contains(id)); + + m_breakpointIDToActions.set(id, scriptBreakpoint.actions); } -void ScriptDebugServer::removeBreakpoint(JSC::BreakpointID id) +void ScriptDebugServer::removeBreakpointActions(BreakpointID id) { - ASSERT(id != JSC::noBreakpointID); - BreakpointIDToActionsMap::iterator it = m_breakpointIDToActions.find(id); - if (it != m_breakpointIDToActions.end()) - m_breakpointIDToActions.remove(it); + ASSERT(id != noBreakpointID); - Debugger::removeBreakpoint(id); + m_breakpointIDToActions.remove(id); +} + +const BreakpointActions& ScriptDebugServer::getActionsForBreakpoint(BreakpointID id) +{ + ASSERT(id != noBreakpointID); + + auto entry = m_breakpointIDToActions.find(id); + if (entry != m_breakpointIDToActions.end()) + return entry->value; + + static NeverDestroyed<BreakpointActions> emptyActionVector = BreakpointActions(); + return emptyActionVector; +} + +void ScriptDebugServer::clearBreakpointActions() +{ + m_breakpointIDToActions.clear(); } bool ScriptDebugServer::evaluateBreakpointAction(const ScriptBreakpointAction& breakpointAction) { - DebuggerCallFrame* debuggerCallFrame = currentDebuggerCallFrame(); + DebuggerCallFrame& debuggerCallFrame = currentDebuggerCallFrame(); switch (breakpointAction.type) { case ScriptBreakpointActionTypeLog: { - dispatchBreakpointActionLog(debuggerCallFrame->exec(), breakpointAction.data); + dispatchBreakpointActionLog(debuggerCallFrame.globalExec(), breakpointAction.data); break; } case ScriptBreakpointActionTypeEvaluate: { - JSValue exception; - debuggerCallFrame->evaluate(breakpointAction.data, exception); + NakedPtr<Exception> exception; + JSObject* scopeExtensionObject = nullptr; + debuggerCallFrame.evaluateWithScopeExtension(breakpointAction.data, scopeExtensionObject, exception); if (exception) - reportException(debuggerCallFrame->exec(), exception); + reportException(debuggerCallFrame.globalExec(), exception); break; } case ScriptBreakpointActionTypeSound: - dispatchBreakpointActionSound(debuggerCallFrame->exec()); + dispatchBreakpointActionSound(debuggerCallFrame.globalExec(), breakpointAction.identifier); break; case ScriptBreakpointActionTypeProbe: { - JSValue exception; - JSValue result = debuggerCallFrame->evaluate(breakpointAction.data, exception); + NakedPtr<Exception> exception; + JSObject* scopeExtensionObject = nullptr; + JSValue result = debuggerCallFrame.evaluateWithScopeExtension(breakpointAction.data, scopeExtensionObject, exception); + JSC::ExecState* exec = debuggerCallFrame.globalExec(); if (exception) - reportException(debuggerCallFrame->exec(), exception); - - JSC::ExecState* state = debuggerCallFrame->scope()->globalObject()->globalExec(); - Deprecated::ScriptValue wrappedResult = Deprecated::ScriptValue(state->vm(), exception ? exception : result); - dispatchDidSampleProbe(state, breakpointAction.identifier, wrappedResult); + reportException(exec, exception); + + dispatchBreakpointActionProbe(exec, breakpointAction, exception ? exception->value() : result); break; } default: @@ -123,21 +125,14 @@ bool ScriptDebugServer::evaluateBreakpointAction(const ScriptBreakpointAction& b return true; } -void ScriptDebugServer::clearBreakpoints() -{ - Debugger::clearBreakpoints(); - m_breakpointIDToActions.clear(); -} - void ScriptDebugServer::dispatchDidPause(ScriptDebugListener* listener) { ASSERT(isPaused()); - DebuggerCallFrame* debuggerCallFrame = currentDebuggerCallFrame(); - JSGlobalObject* globalObject = debuggerCallFrame->scope()->globalObject(); - JSC::ExecState* state = globalObject->globalExec(); - RefPtr<JavaScriptCallFrame> javaScriptCallFrame = JavaScriptCallFrame::create(debuggerCallFrame); - JSValue jsCallFrame = toJS(state, globalObject, javaScriptCallFrame.get()); - listener->didPause(state, Deprecated::ScriptValue(state->vm(), jsCallFrame), Deprecated::ScriptValue()); + DebuggerCallFrame& debuggerCallFrame = currentDebuggerCallFrame(); + JSGlobalObject* globalObject = debuggerCallFrame.scope()->globalObject(); + JSC::ExecState& state = *globalObject->globalExec(); + JSValue jsCallFrame = toJS(&state, globalObject, JavaScriptCallFrame::create(debuggerCallFrame).ptr()); + listener->didPause(state, jsCallFrame, exceptionOrCaughtValue(&state)); } void ScriptDebugServer::dispatchBreakpointActionLog(ExecState* exec, const String& message) @@ -145,53 +140,49 @@ void ScriptDebugServer::dispatchBreakpointActionLog(ExecState* exec, const Strin if (m_callingListeners) return; - ListenerSet* listeners = getListenersForGlobalObject(exec->lexicalGlobalObject()); - if (!listeners) + if (m_listeners.isEmpty()) return; - ASSERT(!listeners->isEmpty()); - TemporaryChange<bool> change(m_callingListeners, true); + SetForScope<bool> change(m_callingListeners, true); Vector<ScriptDebugListener*> listenersCopy; - copyToVector(*listeners, listenersCopy); - for (auto listener : listenersCopy) - listener->breakpointActionLog(exec, message); + copyToVector(m_listeners, listenersCopy); + for (auto* listener : listenersCopy) + listener->breakpointActionLog(*exec, message); } -void ScriptDebugServer::dispatchBreakpointActionSound(ExecState* exec) +void ScriptDebugServer::dispatchBreakpointActionSound(ExecState*, int breakpointActionIdentifier) { if (m_callingListeners) return; - ListenerSet* listeners = getListenersForGlobalObject(exec->lexicalGlobalObject()); - if (!listeners) + if (m_listeners.isEmpty()) return; - ASSERT(!listeners->isEmpty()); - TemporaryChange<bool> change(m_callingListeners, true); + SetForScope<bool> change(m_callingListeners, true); Vector<ScriptDebugListener*> listenersCopy; - copyToVector(*listeners, listenersCopy); - for (auto listener : listenersCopy) - listener->breakpointActionSound(); + copyToVector(m_listeners, listenersCopy); + for (auto* listener : listenersCopy) + listener->breakpointActionSound(breakpointActionIdentifier); } -void ScriptDebugServer::dispatchDidSampleProbe(ExecState* exec, int identifier, const Deprecated::ScriptValue& sample) +void ScriptDebugServer::dispatchBreakpointActionProbe(ExecState* exec, const ScriptBreakpointAction& action, JSC::JSValue sampleValue) { if (m_callingListeners) return; - ListenerSet* listeners = getListenersForGlobalObject(exec->lexicalGlobalObject()); - if (!listeners) + if (m_listeners.isEmpty()) return; - ASSERT(!listeners->isEmpty()); - TemporaryChange<bool> change(m_callingListeners, true); + SetForScope<bool> change(m_callingListeners, true); + + unsigned sampleId = m_nextProbeSampleId++; Vector<ScriptDebugListener*> listenersCopy; - copyToVector(*listeners, listenersCopy); - for (auto listener : listenersCopy) - listener->didSampleProbe(exec, identifier, m_hitCount, sample); + copyToVector(m_listeners, listenersCopy); + for (auto* listener : listenersCopy) + listener->breakpointActionProbe(*exec, action, m_currentProbeBatchId, sampleId, sampleValue); } void ScriptDebugServer::dispatchDidContinue(ScriptDebugListener* listener) @@ -203,12 +194,16 @@ void ScriptDebugServer::dispatchDidParseSource(const ListenerSet& listeners, Sou { JSC::SourceID sourceID = sourceProvider->asID(); + // FIXME: <https://webkit.org/b/162773> Web Inspector: Simplify ScriptDebugListener::Script to use SourceProvider ScriptDebugListener::Script script; + script.sourceProvider = sourceProvider; script.url = sourceProvider->url(); - script.source = sourceProvider->source(); + script.source = sourceProvider->source().toString(); script.startLine = sourceProvider->startPosition().m_line.zeroBasedInt(); script.startColumn = sourceProvider->startPosition().m_column.zeroBasedInt(); script.isContentScript = isContentScript; + script.sourceURL = sourceProvider->sourceURL(); + script.sourceMappingURL = sourceProvider->sourceMappingURL(); int sourceLength = script.source.length(); int lineCount = 1; @@ -235,7 +230,7 @@ void ScriptDebugServer::dispatchDidParseSource(const ListenerSet& listeners, Sou void ScriptDebugServer::dispatchFailedToParseSource(const ListenerSet& listeners, SourceProvider* sourceProvider, int errorLine, const String& errorMessage) { String url = sourceProvider->url(); - const String& data = sourceProvider->source(); + String data = sourceProvider->source().toString(); int firstLine = sourceProvider->startPosition().m_line.oneBasedInt(); Vector<ScriptDebugListener*> copy; @@ -249,18 +244,29 @@ void ScriptDebugServer::sourceParsed(ExecState* exec, SourceProvider* sourceProv if (m_callingListeners) return; - ListenerSet* listeners = getListenersForGlobalObject(exec->lexicalGlobalObject()); - if (!listeners) + if (m_listeners.isEmpty()) return; - ASSERT(!listeners->isEmpty()); - TemporaryChange<bool> change(m_callingListeners, true); + SetForScope<bool> change(m_callingListeners, true); bool isError = errorLine != -1; if (isError) - dispatchFailedToParseSource(*listeners, sourceProvider, errorLine, errorMessage); + dispatchFailedToParseSource(m_listeners, sourceProvider, errorLine, errorMessage); else - dispatchDidParseSource(*listeners, sourceProvider, isContentScript(exec)); + dispatchDidParseSource(m_listeners, sourceProvider, isContentScript(exec)); +} + +void ScriptDebugServer::dispatchFunctionToListeners(JavaScriptExecutionCallback callback) +{ + if (m_callingListeners) + return; + + if (m_listeners.isEmpty()) + return; + + SetForScope<bool> change(m_callingListeners, true); + + dispatchFunctionToListeners(m_listeners, callback); } void ScriptDebugServer::dispatchFunctionToListeners(const ListenerSet& listeners, JavaScriptExecutionCallback callback) @@ -271,68 +277,81 @@ void ScriptDebugServer::dispatchFunctionToListeners(const ListenerSet& listeners (this->*callback)(copy[i]); } -void ScriptDebugServer::dispatchFunctionToListeners(JavaScriptExecutionCallback callback, JSGlobalObject* globalObject) -{ - if (m_callingListeners) - return; - - TemporaryChange<bool> change(m_callingListeners, true); - - if (ListenerSet* listeners = getListenersForGlobalObject(globalObject)) { - ASSERT(!listeners->isEmpty()); - dispatchFunctionToListeners(*listeners, callback); - } -} - void ScriptDebugServer::notifyDoneProcessingDebuggerEvents() { m_doneProcessingDebuggerEvents = true; } -bool ScriptDebugServer::needPauseHandling(JSGlobalObject* globalObject) +void ScriptDebugServer::handleBreakpointHit(JSC::JSGlobalObject* globalObject, const JSC::Breakpoint& breakpoint) { - return !!getListenersForGlobalObject(globalObject); -} + ASSERT(isAttached(globalObject)); -void ScriptDebugServer::handleBreakpointHit(const JSC::Breakpoint& breakpoint) -{ - m_hitCount++; - BreakpointIDToActionsMap::iterator it = m_breakpointIDToActions.find(breakpoint.id); - if (it != m_breakpointIDToActions.end()) { - BreakpointActions& actions = it->value; + m_currentProbeBatchId++; + + auto entry = m_breakpointIDToActions.find(breakpoint.id); + if (entry != m_breakpointIDToActions.end()) { + BreakpointActions actions = entry->value; for (size_t i = 0; i < actions.size(); ++i) { if (!evaluateBreakpointAction(actions[i])) return; + if (!isAttached(globalObject)) + return; } } } -void ScriptDebugServer::handleExceptionInBreakpointCondition(JSC::ExecState* exec, JSC::JSValue exception) const +void ScriptDebugServer::handleExceptionInBreakpointCondition(JSC::ExecState* exec, JSC::Exception* exception) const { reportException(exec, exception); } -void ScriptDebugServer::handlePause(Debugger::ReasonForPause, JSGlobalObject* vmEntryGlobalObject) +void ScriptDebugServer::handlePause(JSGlobalObject* vmEntryGlobalObject, Debugger::ReasonForPause) { - dispatchFunctionToListeners(&ScriptDebugServer::dispatchDidPause, vmEntryGlobalObject); + dispatchFunctionToListeners(&ScriptDebugServer::dispatchDidPause); didPause(vmEntryGlobalObject); m_doneProcessingDebuggerEvents = false; runEventLoopWhilePaused(); didContinue(vmEntryGlobalObject); - dispatchFunctionToListeners(&ScriptDebugServer::dispatchDidContinue, vmEntryGlobalObject); + dispatchFunctionToListeners(&ScriptDebugServer::dispatchDidContinue); } -const Vector<ScriptBreakpointAction>& ScriptDebugServer::getActionsForBreakpoint(JSC::BreakpointID breakpointID) +void ScriptDebugServer::addListener(ScriptDebugListener* listener) { - ASSERT(breakpointID != JSC::noBreakpointID); + ASSERT(listener); - if (m_breakpointIDToActions.contains(breakpointID)) - return m_breakpointIDToActions.find(breakpointID)->value; - - static NeverDestroyed<Vector<ScriptBreakpointAction>> emptyActionVector = Vector<ScriptBreakpointAction>(); - return emptyActionVector; + bool wasEmpty = m_listeners.isEmpty(); + m_listeners.add(listener); + + // First listener. Attach the debugger. + if (wasEmpty) + attachDebugger(); +} + +void ScriptDebugServer::removeListener(ScriptDebugListener* listener, bool isBeingDestroyed) +{ + ASSERT(listener); + + m_listeners.remove(listener); + + // Last listener. Detach the debugger. + if (m_listeners.isEmpty()) + detachDebugger(isBeingDestroyed); +} + +JSC::JSValue ScriptDebugServer::exceptionOrCaughtValue(JSC::ExecState* state) +{ + if (reasonForPause() == PausedForException) + return currentException(); + + for (RefPtr<DebuggerCallFrame> frame = ¤tDebuggerCallFrame(); frame; frame = frame->callerFrame()) { + DebuggerScope& scope = *frame->scope(); + if (scope.isCatchScope()) + return scope.caughtValue(state); + } + + return { }; } } // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/ScriptDebugServer.h b/Source/JavaScriptCore/inspector/ScriptDebugServer.h index 6d55de241..7e4c54335 100644 --- a/Source/JavaScriptCore/inspector/ScriptDebugServer.h +++ b/Source/JavaScriptCore/inspector/ScriptDebugServer.h @@ -11,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -27,8 +27,7 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ScriptDebugServer_h -#define ScriptDebugServer_h +#pragma once #include "ScriptBreakpoint.h" #include "ScriptDebugListener.h" @@ -36,14 +35,12 @@ #include "debugger/Debugger.h" #include <wtf/HashMap.h> #include <wtf/HashSet.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> -#include <wtf/text/TextPosition.h> #include <wtf/text/WTFString.h> namespace JSC { class ExecState; class JSGlobalObject; +class VM; } namespace Inspector { @@ -52,65 +49,63 @@ class JS_EXPORT_PRIVATE ScriptDebugServer : public JSC::Debugger { WTF_MAKE_NONCOPYABLE(ScriptDebugServer); WTF_MAKE_FAST_ALLOCATED; public: - JSC::BreakpointID setBreakpoint(JSC::SourceID, const ScriptBreakpoint&, unsigned* actualLineNumber, unsigned* actualColumnNumber); - void removeBreakpoint(JSC::BreakpointID); - void clearBreakpoints(); - virtual void recompileAllJSFunctions() = 0; + // FIXME: Move BreakpointAction handling into JSC::Debugger or InspectorDebuggerAgent. + void setBreakpointActions(JSC::BreakpointID, const ScriptBreakpoint&); + void removeBreakpointActions(JSC::BreakpointID); + void clearBreakpointActions(); - const Vector<ScriptBreakpointAction>& getActionsForBreakpoint(JSC::BreakpointID); + const BreakpointActions& getActionsForBreakpoint(JSC::BreakpointID); - class Task { - WTF_MAKE_FAST_ALLOCATED; - public: - virtual ~Task() { } - virtual void run() = 0; - }; + void addListener(ScriptDebugListener*); + void removeListener(ScriptDebugListener*, bool isBeingDestroyed); protected: typedef HashSet<ScriptDebugListener*> ListenerSet; typedef void (ScriptDebugServer::*JavaScriptExecutionCallback)(ScriptDebugListener*); - ScriptDebugServer(bool isInWorkerThread = false); + ScriptDebugServer(JSC::VM&); ~ScriptDebugServer(); - virtual ListenerSet* getListenersForGlobalObject(JSC::JSGlobalObject*) = 0; + virtual void attachDebugger() = 0; + virtual void detachDebugger(bool isBeingDestroyed) = 0; + virtual void didPause(JSC::JSGlobalObject*) = 0; virtual void didContinue(JSC::JSGlobalObject*) = 0; virtual void runEventLoopWhilePaused() = 0; virtual bool isContentScript(JSC::ExecState*) const = 0; - virtual void reportException(JSC::ExecState*, JSC::JSValue) const = 0; + virtual void reportException(JSC::ExecState*, JSC::Exception*) const = 0; bool evaluateBreakpointAction(const ScriptBreakpointAction&); - void dispatchFunctionToListeners(JavaScriptExecutionCallback, JSC::JSGlobalObject*); + void dispatchFunctionToListeners(JavaScriptExecutionCallback); void dispatchFunctionToListeners(const ListenerSet& listeners, JavaScriptExecutionCallback); void dispatchDidPause(ScriptDebugListener*); void dispatchDidContinue(ScriptDebugListener*); void dispatchDidParseSource(const ListenerSet& listeners, JSC::SourceProvider*, bool isContentScript); void dispatchFailedToParseSource(const ListenerSet& listeners, JSC::SourceProvider*, int errorLine, const String& errorMessage); void dispatchBreakpointActionLog(JSC::ExecState*, const String&); - void dispatchBreakpointActionSound(JSC::ExecState*); - void dispatchDidSampleProbe(JSC::ExecState*, int probeIdentifier, const Deprecated::ScriptValue& sample); + void dispatchBreakpointActionSound(JSC::ExecState*, int breakpointActionIdentifier); + void dispatchBreakpointActionProbe(JSC::ExecState*, const ScriptBreakpointAction&, JSC::JSValue sample); - bool m_doneProcessingDebuggerEvents; + bool m_doneProcessingDebuggerEvents { true }; private: - typedef Vector<ScriptBreakpointAction> BreakpointActions; typedef HashMap<JSC::BreakpointID, BreakpointActions> BreakpointIDToActionsMap; - virtual void sourceParsed(JSC::ExecState*, JSC::SourceProvider*, int errorLine, const String& errorMsg) override final; - virtual bool needPauseHandling(JSC::JSGlobalObject*) override final; - virtual void handleBreakpointHit(const JSC::Breakpoint&) override final; - virtual void handleExceptionInBreakpointCondition(JSC::ExecState*, JSC::JSValue exception) const override final; - virtual void handlePause(JSC::Debugger::ReasonForPause, JSC::JSGlobalObject*) override final; - virtual void notifyDoneProcessingDebuggerEvents() override final; + void sourceParsed(JSC::ExecState*, JSC::SourceProvider*, int errorLine, const String& errorMsg) final; + void handleBreakpointHit(JSC::JSGlobalObject*, const JSC::Breakpoint&) final; + void handleExceptionInBreakpointCondition(JSC::ExecState*, JSC::Exception*) const final; + void handlePause(JSC::JSGlobalObject*, JSC::Debugger::ReasonForPause) final; + void notifyDoneProcessingDebuggerEvents() final; + + JSC::JSValue exceptionOrCaughtValue(JSC::ExecState*); - unsigned m_hitCount; - bool m_callingListeners; BreakpointIDToActionsMap m_breakpointIDToActions; + ListenerSet m_listeners; + bool m_callingListeners { false }; + unsigned m_nextProbeSampleId { 1 }; + unsigned m_currentProbeBatchId { 0 }; }; } // namespace Inspector - -#endif // ScriptDebugServer_h diff --git a/Source/JavaScriptCore/inspector/agents/InspectorAgent.cpp b/Source/JavaScriptCore/inspector/agents/InspectorAgent.cpp index fcee46e9d..f64baf3d3 100644 --- a/Source/JavaScriptCore/inspector/agents/InspectorAgent.cpp +++ b/Source/JavaScriptCore/inspector/agents/InspectorAgent.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. + * Copyright (C) 2007-2010, 2015 Apple Inc. All rights reserved. * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com> * Copyright (C) 2011 Google Inc. All rights reserved. * @@ -12,7 +12,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -31,18 +31,18 @@ #include "config.h" #include "InspectorAgent.h" -#if ENABLE(INSPECTOR) - +#include "InspectorEnvironment.h" +#include "InspectorFrontendRouter.h" #include "InspectorValues.h" #include "ScriptValue.h" -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> namespace Inspector { -InspectorAgent::InspectorAgent() +InspectorAgent::InspectorAgent(AgentContext& context) : InspectorAgentBase(ASCIILiteral("Inspector")) - , m_enabled(false) + , m_environment(context.environment) + , m_frontendDispatcher(std::make_unique<InspectorFrontendDispatcher>(context.frontendRouter)) + , m_backendDispatcher(InspectorBackendDispatcher::create(context.backendDispatcher, this)) { } @@ -50,43 +50,49 @@ InspectorAgent::~InspectorAgent() { } -void InspectorAgent::didCreateFrontendAndBackend(InspectorFrontendChannel* frontendChannel, InspectorBackendDispatcher* backendDispatcher) +void InspectorAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) { - m_frontendDispatcher = std::make_unique<InspectorInspectorFrontendDispatcher>(frontendChannel); - m_backendDispatcher = InspectorInspectorBackendDispatcher::create(backendDispatcher, this); } -void InspectorAgent::willDestroyFrontendAndBackend(InspectorDisconnectReason) +void InspectorAgent::willDestroyFrontendAndBackend(DisconnectReason) { - m_frontendDispatcher = nullptr; - m_backendDispatcher.clear(); - m_pendingEvaluateTestCommands.clear(); - ErrorString error; - disable(&error); + ErrorString unused; + disable(unused); } -void InspectorAgent::enable(ErrorString*) +void InspectorAgent::enable(ErrorString&) { m_enabled = true; if (m_pendingInspectData.first) - inspect(m_pendingInspectData.first, m_pendingInspectData.second); + inspect(m_pendingInspectData.first.copyRef(), m_pendingInspectData.second.copyRef()); + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_pendingExtraDomainsData) + m_frontendDispatcher->activateExtraDomains(m_pendingExtraDomainsData); +#endif + + for (auto& testCommand : m_pendingEvaluateTestCommands) + m_frontendDispatcher->evaluateForTestInFrontend(testCommand); - for (Vector<std::pair<long, String>>::iterator it = m_pendingEvaluateTestCommands.begin(); m_frontendDispatcher && it != m_pendingEvaluateTestCommands.end(); ++it) - m_frontendDispatcher->evaluateForTestInFrontend(static_cast<int>((*it).first), (*it).second); m_pendingEvaluateTestCommands.clear(); } -void InspectorAgent::disable(ErrorString*) +void InspectorAgent::disable(ErrorString&) { m_enabled = false; } -void InspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<InspectorObject> hints) +void InspectorAgent::initialized(ErrorString&) { - if (m_enabled && m_frontendDispatcher) { + m_environment.frontendInitialized(); +} + +void InspectorAgent::inspect(RefPtr<Protocol::Runtime::RemoteObject>&& objectToInspect, RefPtr<InspectorObject>&& hints) +{ + if (m_enabled) { m_frontendDispatcher->inspect(objectToInspect, hints); m_pendingInspectData.first = nullptr; m_pendingInspectData.second = nullptr; @@ -97,14 +103,43 @@ void InspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> obje m_pendingInspectData.second = hints; } -void InspectorAgent::evaluateForTestInFrontend(long callId, const String& script) +void InspectorAgent::evaluateForTestInFrontend(const String& script) { - if (m_enabled && m_frontendDispatcher) - m_frontendDispatcher->evaluateForTestInFrontend(static_cast<int>(callId), script); + if (m_enabled) + m_frontendDispatcher->evaluateForTestInFrontend(script); else - m_pendingEvaluateTestCommands.append(std::pair<long, String>(callId, script)); + m_pendingEvaluateTestCommands.append(script); } -} // namespace Inspector +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +void InspectorAgent::activateExtraDomain(const String& domainName) +{ + if (!m_enabled) { + if (!m_pendingExtraDomainsData) + m_pendingExtraDomainsData = Inspector::Protocol::Array<String>::create(); + m_pendingExtraDomainsData->addItem(domainName); + return; + } -#endif // ENABLE(INSPECTOR) + auto domainNames = Inspector::Protocol::Array<String>::create(); + domainNames->addItem(domainName); + m_frontendDispatcher->activateExtraDomains(WTFMove(domainNames)); +} + +void InspectorAgent::activateExtraDomains(const Vector<String>& extraDomains) +{ + if (extraDomains.isEmpty()) + return; + + auto domainNames = Inspector::Protocol::Array<String>::create(); + for (auto domainName : extraDomains) + domainNames->addItem(domainName); + + if (!m_enabled) + m_pendingExtraDomainsData = WTFMove(domainNames); + else + m_frontendDispatcher->activateExtraDomains(WTFMove(domainNames)); +} +#endif + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/InspectorAgent.h b/Source/JavaScriptCore/inspector/agents/InspectorAgent.h index c7dc9ba5a..a9b039207 100644 --- a/Source/JavaScriptCore/inspector/agents/InspectorAgent.h +++ b/Source/JavaScriptCore/inspector/agents/InspectorAgent.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. + * Copyright (C) 2007-2010, 2015 Apple Inc. All rights reserved. * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -11,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -27,46 +27,55 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorAgent_h -#define InspectorAgent_h +#pragma once -#include "InspectorJSBackendDispatchers.h" -#include "InspectorJSFrontendDispatchers.h" +#include "InspectorBackendDispatchers.h" +#include "InspectorFrontendDispatchers.h" #include "inspector/InspectorAgentBase.h" #include <wtf/Forward.h> -#include <wtf/PassOwnPtr.h> #include <wtf/Vector.h> namespace Inspector { +class BackendDispatcher; +class InspectorEnvironment; class InspectorObject; -class InstrumentingAgents; typedef String ErrorString; -class JS_EXPORT_PRIVATE InspectorAgent final : public InspectorAgentBase, public InspectorInspectorBackendDispatcherHandler { +class JS_EXPORT_PRIVATE InspectorAgent final : public InspectorAgentBase, public InspectorBackendDispatcherHandler { WTF_MAKE_NONCOPYABLE(InspectorAgent); + WTF_MAKE_FAST_ALLOCATED; public: - InspectorAgent(); + InspectorAgent(AgentContext&); virtual ~InspectorAgent(); - virtual void didCreateFrontendAndBackend(InspectorFrontendChannel*, InspectorBackendDispatcher*) override; - virtual void willDestroyFrontendAndBackend(InspectorDisconnectReason reason) override; + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) override; + void willDestroyFrontendAndBackend(DisconnectReason) override; - virtual void enable(ErrorString*) override; - virtual void disable(ErrorString*) override; + void enable(ErrorString&) override; + void disable(ErrorString&) override; + void initialized(ErrorString&) override; - void inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<InspectorObject> hints); - void evaluateForTestInFrontend(long testCallId, const String& script); + void inspect(RefPtr<Protocol::Runtime::RemoteObject>&& objectToInspect, RefPtr<InspectorObject>&& hints); + void evaluateForTestInFrontend(const String& script); + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + void activateExtraDomain(const String&); + void activateExtraDomains(const Vector<String>&); +#endif private: - std::unique_ptr<InspectorInspectorFrontendDispatcher> m_frontendDispatcher; - RefPtr<InspectorInspectorBackendDispatcher> m_backendDispatcher; - Vector<std::pair<long, String>> m_pendingEvaluateTestCommands; - std::pair<RefPtr<TypeBuilder::Runtime::RemoteObject>, RefPtr<InspectorObject>> m_pendingInspectData; - bool m_enabled; + InspectorEnvironment& m_environment; + std::unique_ptr<InspectorFrontendDispatcher> m_frontendDispatcher; + Ref<InspectorBackendDispatcher> m_backendDispatcher; + + Vector<String> m_pendingEvaluateTestCommands; + std::pair<RefPtr<Protocol::Runtime::RemoteObject>, RefPtr<InspectorObject>> m_pendingInspectData; +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + RefPtr<Inspector::Protocol::Array<String>> m_pendingExtraDomainsData; +#endif + bool m_enabled { false }; }; } // namespace Inspector - -#endif // !defined(InspectorAgent_h) diff --git a/Source/JavaScriptCore/inspector/agents/InspectorConsoleAgent.cpp b/Source/JavaScriptCore/inspector/agents/InspectorConsoleAgent.cpp new file mode 100644 index 000000000..d453dbbd8 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/InspectorConsoleAgent.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InspectorConsoleAgent.h" + +#include "ConsoleMessage.h" +#include "InjectedScriptManager.h" +#include "InspectorFrontendRouter.h" +#include "InspectorHeapAgent.h" +#include "ScriptArguments.h" +#include "ScriptCallFrame.h" +#include "ScriptCallStack.h" +#include "ScriptCallStackFactory.h" +#include "ScriptObject.h" +#include <wtf/CurrentTime.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +static const unsigned maximumConsoleMessages = 100; +static const int expireConsoleMessagesStep = 10; + +InspectorConsoleAgent::InspectorConsoleAgent(AgentContext& context, InspectorHeapAgent* heapAgent) + : InspectorAgentBase(ASCIILiteral("Console")) + , m_injectedScriptManager(context.injectedScriptManager) + , m_frontendDispatcher(std::make_unique<ConsoleFrontendDispatcher>(context.frontendRouter)) + , m_backendDispatcher(ConsoleBackendDispatcher::create(context.backendDispatcher, this)) + , m_heapAgent(heapAgent) +{ +} + +InspectorConsoleAgent::~InspectorConsoleAgent() +{ +} + +void InspectorConsoleAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) +{ +} + +void InspectorConsoleAgent::willDestroyFrontendAndBackend(DisconnectReason) +{ + String errorString; + disable(errorString); +} + +void InspectorConsoleAgent::discardValues() +{ + m_consoleMessages.clear(); +} + +void InspectorConsoleAgent::enable(ErrorString&) +{ + if (m_enabled) + return; + + m_enabled = true; + + if (m_expiredConsoleMessageCount) { + ConsoleMessage expiredMessage(MessageSource::Other, MessageType::Log, MessageLevel::Warning, String::format("%d console messages are not shown.", m_expiredConsoleMessageCount)); + expiredMessage.addToFrontend(*m_frontendDispatcher, m_injectedScriptManager, false); + } + + size_t messageCount = m_consoleMessages.size(); + for (size_t i = 0; i < messageCount; ++i) + m_consoleMessages[i]->addToFrontend(*m_frontendDispatcher, m_injectedScriptManager, false); +} + +void InspectorConsoleAgent::disable(ErrorString&) +{ + if (!m_enabled) + return; + + m_enabled = false; +} + +void InspectorConsoleAgent::clearMessages(ErrorString&) +{ + m_consoleMessages.clear(); + m_expiredConsoleMessageCount = 0; + m_previousMessage = nullptr; + + m_injectedScriptManager.releaseObjectGroup(ASCIILiteral("console")); + + if (m_enabled) + m_frontendDispatcher->messagesCleared(); +} + +void InspectorConsoleAgent::reset() +{ + ErrorString unused; + clearMessages(unused); + + m_times.clear(); + m_counts.clear(); +} + +void InspectorConsoleAgent::addMessageToConsole(std::unique_ptr<ConsoleMessage> message) +{ + if (!m_injectedScriptManager.inspectorEnvironment().developerExtrasEnabled()) + return; + + if (message->type() == MessageType::Clear) { + ErrorString unused; + clearMessages(unused); + } + + addConsoleMessage(WTFMove(message)); +} + +void InspectorConsoleAgent::startTiming(const String& title) +{ + ASSERT(!title.isNull()); + if (title.isNull()) + return; + + auto result = m_times.add(title, monotonicallyIncreasingTime()); + + if (!result.isNewEntry) { + // FIXME: Send an enum to the frontend for localization? + String warning = makeString("Timer \"", title, "\" already exists"); + addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Timing, MessageLevel::Warning, warning)); + } +} + +void InspectorConsoleAgent::stopTiming(const String& title, Ref<ScriptCallStack>&& callStack) +{ + ASSERT(!title.isNull()); + if (title.isNull()) + return; + + auto it = m_times.find(title); + if (it == m_times.end()) { + // FIXME: Send an enum to the frontend for localization? + String warning = makeString("Timer \"", title, "\" does not exist"); + addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Timing, MessageLevel::Warning, warning)); + return; + } + + double startTime = it->value; + m_times.remove(it); + + double elapsed = monotonicallyIncreasingTime() - startTime; + String message = title + String::format(": %.3fms", elapsed * 1000); + addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Timing, MessageLevel::Debug, message, WTFMove(callStack))); +} + +void InspectorConsoleAgent::takeHeapSnapshot(const String& title) +{ + if (!m_injectedScriptManager.inspectorEnvironment().developerExtrasEnabled()) + return; + + ErrorString ignored; + double timestamp; + String snapshotData; + m_heapAgent->snapshot(ignored, ×tamp, &snapshotData); + + m_frontendDispatcher->heapSnapshot(timestamp, snapshotData, title.isEmpty() ? nullptr : &title); +} + +void InspectorConsoleAgent::count(JSC::ExecState* state, Ref<ScriptArguments>&& arguments) +{ + Ref<ScriptCallStack> callStack = createScriptCallStackForConsole(state, ScriptCallStack::maxCallStackSizeToCapture); + + String title; + String identifier; + if (!arguments->argumentCount()) { + // '@' prefix for engine generated labels. + title = ASCIILiteral("Global"); + identifier = makeString('@', title); + } else { + // '#' prefix for user labels. + arguments->getFirstArgumentAsString(title); + identifier = makeString('#', title); + } + + auto result = m_counts.add(identifier, 1); + if (!result.isNewEntry) + result.iterator->value += 1; + + // FIXME: Web Inspector should have a better UI for counters, but for now we just log an updated counter value. + + String message = makeString(title, ": ", String::number(result.iterator->value)); + addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Log, MessageLevel::Debug, message, WTFMove(callStack))); +} + +static bool isGroupMessage(MessageType type) +{ + return type == MessageType::StartGroup + || type == MessageType::StartGroupCollapsed + || type == MessageType::EndGroup; +} + +void InspectorConsoleAgent::addConsoleMessage(std::unique_ptr<ConsoleMessage> consoleMessage) +{ + ASSERT(m_injectedScriptManager.inspectorEnvironment().developerExtrasEnabled()); + ASSERT_ARG(consoleMessage, consoleMessage); + + if (m_previousMessage && !isGroupMessage(m_previousMessage->type()) && m_previousMessage->isEqual(consoleMessage.get())) { + m_previousMessage->incrementCount(); + if (m_enabled) + m_previousMessage->updateRepeatCountInConsole(*m_frontendDispatcher); + } else { + m_previousMessage = consoleMessage.get(); + m_consoleMessages.append(WTFMove(consoleMessage)); + if (m_enabled) + m_previousMessage->addToFrontend(*m_frontendDispatcher, m_injectedScriptManager, true); + } + + if (m_consoleMessages.size() >= maximumConsoleMessages) { + m_expiredConsoleMessageCount += expireConsoleMessagesStep; + m_consoleMessages.remove(0, expireConsoleMessagesStep); + } +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/InspectorConsoleAgent.h b/Source/JavaScriptCore/inspector/agents/InspectorConsoleAgent.h new file mode 100644 index 000000000..175cec9da --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/InspectorConsoleAgent.h @@ -0,0 +1,94 @@ +/* +* Copyright (C) 2014, 2015 Apple Inc. All rights reserved. +* Copyright (C) 2011 Google Inc. All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* +* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#pragma once + +#include "InspectorBackendDispatchers.h" +#include "InspectorFrontendDispatchers.h" +#include "inspector/InspectorAgentBase.h" +#include "runtime/ConsoleTypes.h" +#include <wtf/Forward.h> +#include <wtf/HashMap.h> +#include <wtf/Noncopyable.h> +#include <wtf/Vector.h> +#include <wtf/text/StringHash.h> + +namespace JSC { +class ExecState; +} + +namespace Inspector { + +class ConsoleMessage; +class InjectedScriptManager; +class InspectorHeapAgent; +class ScriptArguments; +class ScriptCallStack; +typedef String ErrorString; + +class JS_EXPORT_PRIVATE InspectorConsoleAgent : public InspectorAgentBase, public ConsoleBackendDispatcherHandler { + WTF_MAKE_NONCOPYABLE(InspectorConsoleAgent); + WTF_MAKE_FAST_ALLOCATED; +public: + InspectorConsoleAgent(AgentContext&, InspectorHeapAgent*); + virtual ~InspectorConsoleAgent(); + + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) override; + void willDestroyFrontendAndBackend(DisconnectReason) override; + void discardValues() override; + + void enable(ErrorString&) override; + void disable(ErrorString&) override; + void clearMessages(ErrorString&) override; + void setMonitoringXHREnabled(ErrorString&, bool enabled) override = 0; + void addInspectedNode(ErrorString&, int nodeId) override = 0; + + bool enabled() const { return m_enabled; } + void reset(); + + void addMessageToConsole(std::unique_ptr<ConsoleMessage>); + + void startTiming(const String& title); + void stopTiming(const String& title, Ref<ScriptCallStack>&&); + void takeHeapSnapshot(const String& title); + void count(JSC::ExecState*, Ref<ScriptArguments>&&); + +protected: + void addConsoleMessage(std::unique_ptr<ConsoleMessage>); + + InjectedScriptManager& m_injectedScriptManager; + std::unique_ptr<ConsoleFrontendDispatcher> m_frontendDispatcher; + RefPtr<ConsoleBackendDispatcher> m_backendDispatcher; + InspectorHeapAgent* m_heapAgent; + + ConsoleMessage* m_previousMessage { nullptr }; + Vector<std::unique_ptr<ConsoleMessage>> m_consoleMessages; + int m_expiredConsoleMessageCount { 0 }; + HashMap<String, unsigned> m_counts; + HashMap<String, double> m_times; + bool m_enabled { false }; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.cpp b/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.cpp index 06b759568..617efb9ac 100644 --- a/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.cpp +++ b/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.cpp @@ -1,6 +1,6 @@ /* - * Copyright (C) 2010, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2010-2011 Google Inc. All rights reserved. + * Copyright (C) 2010, 2013, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -11,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -30,38 +30,43 @@ #include "config.h" #include "InspectorDebuggerAgent.h" -#if ENABLE(INSPECTOR) - +#include "AsyncStackTrace.h" #include "ContentSearchUtilities.h" #include "InjectedScript.h" #include "InjectedScriptManager.h" +#include "InspectorFrontendRouter.h" #include "InspectorValues.h" +#include "JSCInlines.h" #include "RegularExpression.h" +#include "ScriptCallStackFactory.h" #include "ScriptDebugServer.h" #include "ScriptObject.h" #include "ScriptValue.h" +#include <wtf/NeverDestroyed.h> +#include <wtf/Stopwatch.h> #include <wtf/text/WTFString.h> namespace Inspector { const char* InspectorDebuggerAgent::backtraceObjectGroup = "backtrace"; -static String objectGroupForBreakpointAction(int identifier) +// Objects created and retained by evaluating breakpoint actions are put into object groups +// according to the breakpoint action identifier assigned by the frontend. A breakpoint may +// have several object groups, and objects from several backend breakpoint action instances may +// create objects in the same group. +static String objectGroupForBreakpointAction(const ScriptBreakpointAction& action) { - DEFINE_STATIC_LOCAL(const AtomicString, objectGroup, ("breakpoint-action-", AtomicString::ConstructFromLiteral)); - return makeString(objectGroup, String::number(identifier)); + static NeverDestroyed<String> objectGroup(ASCIILiteral("breakpoint-action-")); + return makeString(objectGroup.get(), String::number(action.identifier)); } -InspectorDebuggerAgent::InspectorDebuggerAgent(InjectedScriptManager* injectedScriptManager) +InspectorDebuggerAgent::InspectorDebuggerAgent(AgentContext& context) : InspectorAgentBase(ASCIILiteral("Debugger")) - , m_injectedScriptManager(injectedScriptManager) - , m_listener(nullptr) - , m_pausedScriptState(nullptr) + , m_injectedScriptManager(context.injectedScriptManager) + , m_frontendDispatcher(std::make_unique<DebuggerFrontendDispatcher>(context.frontendRouter)) + , m_backendDispatcher(DebuggerBackendDispatcher::create(context.backendDispatcher, this)) + , m_scriptDebugServer(context.environment.scriptDebugServer()) , m_continueToLocationBreakpointID(JSC::noBreakpointID) - , m_enabled(false) - , m_javaScriptPauseScheduled(false) - , m_nextProbeSampleId(1) - , m_nextBreakpointActionIdentifier(1) { // FIXME: make breakReason optional so that there was no need to init it with "other". clearBreakDetails(); @@ -71,18 +76,13 @@ InspectorDebuggerAgent::~InspectorDebuggerAgent() { } -void InspectorDebuggerAgent::didCreateFrontendAndBackend(InspectorFrontendChannel* frontendChannel, InspectorBackendDispatcher* backendDispatcher) +void InspectorDebuggerAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) { - m_frontendDispatcher = std::make_unique<InspectorDebuggerFrontendDispatcher>(frontendChannel); - m_backendDispatcher = InspectorDebuggerBackendDispatcher::create(backendDispatcher, this); } -void InspectorDebuggerAgent::willDestroyFrontendAndBackend(InspectorDisconnectReason reason) +void InspectorDebuggerAgent::willDestroyFrontendAndBackend(DisconnectReason reason) { - m_frontendDispatcher = nullptr; - m_backendDispatcher.clear(); - - bool skipRecompile = reason == InspectorDisconnectReason::InspectedTargetDestroyed; + bool skipRecompile = reason == DisconnectReason::InspectedTargetDestroyed; disable(skipRecompile); } @@ -91,8 +91,7 @@ void InspectorDebuggerAgent::enable() if (m_enabled) return; - scriptDebugServer().setBreakpointsActivated(true); - startListeningScriptDebugServer(); + m_scriptDebugServer.addListener(this); if (m_listener) m_listener->debuggerWasEnabled(); @@ -105,55 +104,221 @@ void InspectorDebuggerAgent::disable(bool isBeingDestroyed) if (!m_enabled) return; - m_javaScriptBreakpoints.clear(); + m_scriptDebugServer.removeListener(this, isBeingDestroyed); + clearInspectorBreakpointState(); + + if (!isBeingDestroyed) + m_scriptDebugServer.deactivateBreakpoints(); - stopListeningScriptDebugServer(isBeingDestroyed); - clearResolvedBreakpointState(); + ASSERT(m_javaScriptBreakpoints.isEmpty()); if (m_listener) m_listener->debuggerWasDisabled(); + clearAsyncStackTraceData(); + + m_pauseOnAssertionFailures = false; + m_enabled = false; } -void InspectorDebuggerAgent::enable(ErrorString*) +void InspectorDebuggerAgent::enable(ErrorString&) { enable(); } -void InspectorDebuggerAgent::disable(ErrorString*) +void InspectorDebuggerAgent::disable(ErrorString&) { disable(false); } -void InspectorDebuggerAgent::setBreakpointsActive(ErrorString*, bool active) +bool InspectorDebuggerAgent::breakpointsActive() const +{ + return m_scriptDebugServer.breakpointsActive(); +} + +void InspectorDebuggerAgent::setAsyncStackTraceDepth(ErrorString& errorString, int depth) +{ + if (m_asyncStackTraceDepth == depth) + return; + + if (depth < 0) { + errorString = ASCIILiteral("depth must be a positive number."); + return; + } + + m_asyncStackTraceDepth = depth; + + if (!m_asyncStackTraceDepth) + clearAsyncStackTraceData(); +} + +void InspectorDebuggerAgent::setBreakpointsActive(ErrorString&, bool active) { if (active) - scriptDebugServer().activateBreakpoints(); + m_scriptDebugServer.activateBreakpoints(); else - scriptDebugServer().deactivateBreakpoints(); + m_scriptDebugServer.deactivateBreakpoints(); +} + +bool InspectorDebuggerAgent::isPaused() const +{ + return m_scriptDebugServer.isPaused(); +} + +void InspectorDebuggerAgent::setSuppressAllPauses(bool suppress) +{ + m_scriptDebugServer.setSuppressAllPauses(suppress); +} + +static RefPtr<InspectorObject> buildAssertPauseReason(const String& message) +{ + auto reason = Inspector::Protocol::Debugger::AssertPauseReason::create().release(); + if (!message.isNull()) + reason->setMessage(message); + return reason->openAccessors(); +} + +static RefPtr<InspectorObject> buildCSPViolationPauseReason(const String& directiveText) +{ + auto reason = Inspector::Protocol::Debugger::CSPViolationPauseReason::create() + .setDirective(directiveText) + .release(); + return reason->openAccessors(); +} + +RefPtr<InspectorObject> InspectorDebuggerAgent::buildBreakpointPauseReason(JSC::BreakpointID debuggerBreakpointIdentifier) +{ + ASSERT(debuggerBreakpointIdentifier != JSC::noBreakpointID); + auto it = m_debuggerBreakpointIdentifierToInspectorBreakpointIdentifier.find(debuggerBreakpointIdentifier); + if (it == m_debuggerBreakpointIdentifierToInspectorBreakpointIdentifier.end()) + return nullptr; + + auto reason = Inspector::Protocol::Debugger::BreakpointPauseReason::create() + .setBreakpointId(it->value) + .release(); + return reason->openAccessors(); +} + +RefPtr<InspectorObject> InspectorDebuggerAgent::buildExceptionPauseReason(JSC::JSValue exception, const InjectedScript& injectedScript) +{ + ASSERT(exception); + if (!exception) + return nullptr; + + ASSERT(!injectedScript.hasNoValue()); + if (injectedScript.hasNoValue()) + return nullptr; + + return injectedScript.wrapObject(exception, InspectorDebuggerAgent::backtraceObjectGroup)->openAccessors(); +} + +void InspectorDebuggerAgent::handleConsoleAssert(const String& message) +{ + if (!m_scriptDebugServer.breakpointsActive()) + return; + + if (m_pauseOnAssertionFailures) + breakProgram(DebuggerFrontendDispatcher::Reason::Assert, buildAssertPauseReason(message)); +} + +void InspectorDebuggerAgent::didScheduleAsyncCall(JSC::ExecState* exec, int asyncCallType, int callbackIdentifier, bool singleShot) +{ + if (!m_asyncStackTraceDepth) + return; + + if (!m_scriptDebugServer.breakpointsActive()) + return; + + Ref<ScriptCallStack> callStack = createScriptCallStack(exec, m_asyncStackTraceDepth); + ASSERT(callStack->size()); + if (!callStack->size()) + return; + + RefPtr<AsyncStackTrace> parentStackTrace; + if (m_currentAsyncCallIdentifier) { + auto it = m_pendingAsyncCalls.find(m_currentAsyncCallIdentifier.value()); + ASSERT(it != m_pendingAsyncCalls.end()); + parentStackTrace = it->value; + } + + auto identifier = std::make_pair(asyncCallType, callbackIdentifier); + auto asyncStackTrace = AsyncStackTrace::create(WTFMove(callStack), singleShot, WTFMove(parentStackTrace)); + + m_pendingAsyncCalls.set(identifier, WTFMove(asyncStackTrace)); +} + +void InspectorDebuggerAgent::didCancelAsyncCall(int asyncCallType, int callbackIdentifier) +{ + if (!m_asyncStackTraceDepth) + return; + + auto identifier = std::make_pair(asyncCallType, callbackIdentifier); + auto it = m_pendingAsyncCalls.find(identifier); + if (it == m_pendingAsyncCalls.end()) + return; + + auto& asyncStackTrace = it->value; + asyncStackTrace->didCancelAsyncCall(); + + if (m_currentAsyncCallIdentifier && m_currentAsyncCallIdentifier.value() == identifier) + return; + + m_pendingAsyncCalls.remove(identifier); } -bool InspectorDebuggerAgent::isPaused() +void InspectorDebuggerAgent::willDispatchAsyncCall(int asyncCallType, int callbackIdentifier) { - return scriptDebugServer().isPaused(); + if (!m_asyncStackTraceDepth) + return; + + if (m_currentAsyncCallIdentifier) + return; + + // A call can be scheduled before the Inspector is opened, or while async stack + // traces are disabled. If no call data exists, do nothing. + auto identifier = std::make_pair(asyncCallType, callbackIdentifier); + auto it = m_pendingAsyncCalls.find(identifier); + if (it == m_pendingAsyncCalls.end()) + return; + + auto& asyncStackTrace = it->value; + asyncStackTrace->willDispatchAsyncCall(m_asyncStackTraceDepth); + + m_currentAsyncCallIdentifier = identifier; } -void InspectorDebuggerAgent::handleConsoleAssert() +void InspectorDebuggerAgent::didDispatchAsyncCall() { - if (scriptDebugServer().pauseOnExceptionsState() != JSC::Debugger::DontPauseOnExceptions) - breakProgram(InspectorDebuggerFrontendDispatcher::Reason::Assert, nullptr); + if (!m_asyncStackTraceDepth) + return; + + if (!m_currentAsyncCallIdentifier) + return; + + auto identifier = m_currentAsyncCallIdentifier.value(); + auto it = m_pendingAsyncCalls.find(identifier); + ASSERT(it != m_pendingAsyncCalls.end()); + + auto& asyncStackTrace = it->value; + asyncStackTrace->didDispatchAsyncCall(); + + m_currentAsyncCallIdentifier = std::nullopt; + + if (!asyncStackTrace->isPending()) + m_pendingAsyncCalls.remove(identifier); } -static PassRefPtr<InspectorObject> buildObjectForBreakpointCookie(const String& url, int lineNumber, int columnNumber, const String& condition, RefPtr<InspectorArray>& actions, bool isRegex, bool autoContinue) +static Ref<InspectorObject> buildObjectForBreakpointCookie(const String& url, int lineNumber, int columnNumber, const String& condition, RefPtr<InspectorArray>& actions, bool isRegex, bool autoContinue, unsigned ignoreCount) { - RefPtr<InspectorObject> breakpointObject = InspectorObject::create(); + Ref<InspectorObject> breakpointObject = InspectorObject::create(); breakpointObject->setString(ASCIILiteral("url"), url); - breakpointObject->setNumber(ASCIILiteral("lineNumber"), lineNumber); - breakpointObject->setNumber(ASCIILiteral("columnNumber"), columnNumber); + breakpointObject->setInteger(ASCIILiteral("lineNumber"), lineNumber); + breakpointObject->setInteger(ASCIILiteral("columnNumber"), columnNumber); breakpointObject->setString(ASCIILiteral("condition"), condition); breakpointObject->setBoolean(ASCIILiteral("isRegex"), isRegex); breakpointObject->setBoolean(ASCIILiteral("autoContinue"), autoContinue); + breakpointObject->setInteger(ASCIILiteral("ignoreCount"), ignoreCount); if (actions) breakpointObject->setArray(ASCIILiteral("actions"), actions); @@ -172,19 +337,19 @@ static bool matches(const String& url, const String& pattern, bool isRegex) static bool breakpointActionTypeForString(const String& typeString, ScriptBreakpointActionType* output) { - if (typeString == Inspector::TypeBuilder::getJSEnumConstantValue(Inspector::TypeBuilder::Debugger::BreakpointAction::Type::Log)) { + if (typeString == Inspector::Protocol::InspectorHelpers::getEnumConstantValue(Inspector::Protocol::Debugger::BreakpointAction::Type::Log)) { *output = ScriptBreakpointActionTypeLog; return true; } - if (typeString == Inspector::TypeBuilder::getJSEnumConstantValue(Inspector::TypeBuilder::Debugger::BreakpointAction::Type::Evaluate)) { + if (typeString == Inspector::Protocol::InspectorHelpers::getEnumConstantValue(Inspector::Protocol::Debugger::BreakpointAction::Type::Evaluate)) { *output = ScriptBreakpointActionTypeEvaluate; return true; } - if (typeString == Inspector::TypeBuilder::getJSEnumConstantValue(Inspector::TypeBuilder::Debugger::BreakpointAction::Type::Sound)) { + if (typeString == Inspector::Protocol::InspectorHelpers::getEnumConstantValue(Inspector::Protocol::Debugger::BreakpointAction::Type::Sound)) { *output = ScriptBreakpointActionTypeSound; return true; } - if (typeString == Inspector::TypeBuilder::getJSEnumConstantValue(Inspector::TypeBuilder::Debugger::BreakpointAction::Type::Probe)) { + if (typeString == Inspector::Protocol::InspectorHelpers::getEnumConstantValue(Inspector::Protocol::Debugger::BreakpointAction::Type::Probe)) { *output = ScriptBreakpointActionTypeProbe; return true; } @@ -192,7 +357,7 @@ static bool breakpointActionTypeForString(const String& typeString, ScriptBreakp return false; } -bool InspectorDebuggerAgent::breakpointActionsFromProtocol(ErrorString* errorString, RefPtr<InspectorArray>& actions, Vector<ScriptBreakpointAction>* result) +bool InspectorDebuggerAgent::breakpointActionsFromProtocol(ErrorString& errorString, RefPtr<InspectorArray>& actions, BreakpointActions* result) { if (!actions) return true; @@ -205,37 +370,70 @@ bool InspectorDebuggerAgent::breakpointActionsFromProtocol(ErrorString* errorStr for (unsigned i = 0; i < actionsLength; ++i) { RefPtr<InspectorValue> value = actions->get(i); RefPtr<InspectorObject> object; - if (!value->asObject(&object)) { - *errorString = ASCIILiteral("BreakpointAction of incorrect type, expected object"); + if (!value->asObject(object)) { + errorString = ASCIILiteral("BreakpointAction of incorrect type, expected object"); return false; } String typeString; - if (!object->getString(ASCIILiteral("type"), &typeString)) { - *errorString = ASCIILiteral("BreakpointAction had type missing"); + if (!object->getString(ASCIILiteral("type"), typeString)) { + errorString = ASCIILiteral("BreakpointAction had type missing"); return false; } ScriptBreakpointActionType type; if (!breakpointActionTypeForString(typeString, &type)) { - *errorString = ASCIILiteral("BreakpointAction had unknown type"); + errorString = ASCIILiteral("BreakpointAction had unknown type"); return false; } + // Specifying an identifier is optional. They are used to correlate probe samples + // in the frontend across multiple backend probe actions and segregate object groups. + int identifier = 0; + object->getInteger(ASCIILiteral("id"), identifier); + String data; - object->getString(ASCIILiteral("data"), &data); + object->getString(ASCIILiteral("data"), data); - result->append(ScriptBreakpointAction(type, m_nextBreakpointActionIdentifier++, data)); + result->append(ScriptBreakpointAction(type, identifier, data)); } return true; } -void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString* errorString, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const RefPtr<InspectorObject>* options, Inspector::TypeBuilder::Debugger::BreakpointId* outBreakpointIdentifier, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::Location>>& locations, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::BreakpointActionIdentifier>>& breakpointActionIdentifiers) +static RefPtr<Inspector::Protocol::Debugger::Location> buildDebuggerLocation(const JSC::Breakpoint& breakpoint) +{ + ASSERT(breakpoint.resolved); + + auto location = Inspector::Protocol::Debugger::Location::create() + .setScriptId(String::number(breakpoint.sourceID)) + .setLineNumber(breakpoint.line) + .release(); + location->setColumnNumber(breakpoint.column); + + return WTFMove(location); +} + +static bool parseLocation(ErrorString& errorString, const InspectorObject& location, JSC::SourceID& sourceID, unsigned& lineNumber, unsigned& columnNumber) { - locations = Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::Location>::create(); + String scriptIDStr; + if (!location.getString(ASCIILiteral("scriptId"), scriptIDStr) || !location.getInteger(ASCIILiteral("lineNumber"), lineNumber)) { + sourceID = JSC::noSourceID; + errorString = ASCIILiteral("scriptId and lineNumber are required."); + return false; + } + + sourceID = scriptIDStr.toIntPtr(); + columnNumber = 0; + location.getInteger(ASCIILiteral("columnNumber"), columnNumber); + return true; +} + +void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString& errorString, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const InspectorObject* options, Inspector::Protocol::Debugger::BreakpointId* outBreakpointIdentifier, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Debugger::Location>>& locations) +{ + locations = Inspector::Protocol::Array<Inspector::Protocol::Debugger::Location>::create(); if (!optionalURL == !optionalURLRegex) { - *errorString = ASCIILiteral("Either url or urlRegex must be specified."); + errorString = ASCIILiteral("Either url or urlRegex must be specified."); return; } @@ -245,258 +443,361 @@ void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString* errorString, int li String breakpointIdentifier = (isRegex ? "/" + url + "/" : url) + ':' + String::number(lineNumber) + ':' + String::number(columnNumber); if (m_javaScriptBreakpoints.contains(breakpointIdentifier)) { - *errorString = ASCIILiteral("Breakpoint at specified location already exists."); + errorString = ASCIILiteral("Breakpoint at specified location already exists."); return; } String condition = emptyString(); bool autoContinue = false; + unsigned ignoreCount = 0; RefPtr<InspectorArray> actions; if (options) { - (*options)->getString(ASCIILiteral("condition"), &condition); - (*options)->getBoolean(ASCIILiteral("autoContinue"), &autoContinue); - actions = (*options)->getArray(ASCIILiteral("actions")); + options->getString(ASCIILiteral("condition"), condition); + options->getBoolean(ASCIILiteral("autoContinue"), autoContinue); + options->getArray(ASCIILiteral("actions"), actions); + options->getInteger(ASCIILiteral("ignoreCount"), ignoreCount); } - Vector<ScriptBreakpointAction> breakpointActions; + BreakpointActions breakpointActions; if (!breakpointActionsFromProtocol(errorString, actions, &breakpointActions)) return; - breakpointActionIdentifiers = Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::BreakpointActionIdentifier>::create(); - for (ScriptBreakpointAction& action : breakpointActions) - breakpointActionIdentifiers->addItem(action.identifier); + m_javaScriptBreakpoints.set(breakpointIdentifier, buildObjectForBreakpointCookie(url, lineNumber, columnNumber, condition, actions, isRegex, autoContinue, ignoreCount)); - m_javaScriptBreakpoints.set(breakpointIdentifier, buildObjectForBreakpointCookie(url, lineNumber, columnNumber, condition, actions, isRegex, autoContinue)); + for (auto& entry : m_scripts) { + Script& script = entry.value; + String scriptURLForBreakpoints = !script.sourceURL.isEmpty() ? script.sourceURL : script.url; + if (!matches(scriptURLForBreakpoints, url, isRegex)) + continue; - ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition, breakpointActions, autoContinue); - for (ScriptsMap::iterator it = m_scripts.begin(); it != m_scripts.end(); ++it) { - String scriptURL = !it->value.sourceURL.isEmpty() ? it->value.sourceURL : it->value.url; - if (!matches(scriptURL, url, isRegex)) + JSC::SourceID sourceID = entry.key; + JSC::Breakpoint breakpoint(sourceID, lineNumber, columnNumber, condition, autoContinue, ignoreCount); + resolveBreakpoint(script, breakpoint); + if (!breakpoint.resolved) continue; - RefPtr<Inspector::TypeBuilder::Debugger::Location> location = resolveBreakpoint(breakpointIdentifier, it->key, breakpoint); - if (location) - locations->addItem(location); - } - *outBreakpointIdentifier = breakpointIdentifier; -} + bool existing; + setBreakpoint(breakpoint, existing); + if (existing) + continue; -static bool parseLocation(ErrorString* errorString, InspectorObject* location, JSC::SourceID* sourceID, unsigned* lineNumber, unsigned* columnNumber) -{ - String scriptIDStr; - if (!location->getString(ASCIILiteral("scriptId"), &scriptIDStr) || !location->getNumber(ASCIILiteral("lineNumber"), lineNumber)) { - *sourceID = JSC::noSourceID; - *errorString = ASCIILiteral("scriptId and lineNumber are required."); - return false; + ScriptBreakpoint scriptBreakpoint(breakpoint.line, breakpoint.column, condition, breakpointActions, autoContinue, ignoreCount); + didSetBreakpoint(breakpoint, breakpointIdentifier, scriptBreakpoint); + + locations->addItem(buildDebuggerLocation(breakpoint)); } - *sourceID = scriptIDStr.toIntPtr(); - *columnNumber = 0; - location->getNumber(ASCIILiteral("columnNumber"), columnNumber); - return true; + *outBreakpointIdentifier = breakpointIdentifier; } -void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<InspectorObject>& location, const RefPtr<InspectorObject>* options, Inspector::TypeBuilder::Debugger::BreakpointId* outBreakpointIdentifier, RefPtr<Inspector::TypeBuilder::Debugger::Location>& actualLocation, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::BreakpointActionIdentifier>>& breakpointActionIdentifiers) +void InspectorDebuggerAgent::setBreakpoint(ErrorString& errorString, const InspectorObject& location, const InspectorObject* options, Inspector::Protocol::Debugger::BreakpointId* outBreakpointIdentifier, RefPtr<Inspector::Protocol::Debugger::Location>& actualLocation) { JSC::SourceID sourceID; unsigned lineNumber; unsigned columnNumber; - if (!parseLocation(errorString, location.get(), &sourceID, &lineNumber, &columnNumber)) + if (!parseLocation(errorString, location, sourceID, lineNumber, columnNumber)) return; String condition = emptyString(); bool autoContinue = false; + unsigned ignoreCount = 0; RefPtr<InspectorArray> actions; if (options) { - (*options)->getString(ASCIILiteral("condition"), &condition); - (*options)->getBoolean(ASCIILiteral("autoContinue"), &autoContinue); - actions = (*options)->getArray(ASCIILiteral("actions")); + options->getString(ASCIILiteral("condition"), condition); + options->getBoolean(ASCIILiteral("autoContinue"), autoContinue); + options->getArray(ASCIILiteral("actions"), actions); + options->getInteger(ASCIILiteral("ignoreCount"), ignoreCount); } - Vector<ScriptBreakpointAction> breakpointActions; + BreakpointActions breakpointActions; if (!breakpointActionsFromProtocol(errorString, actions, &breakpointActions)) return; - breakpointActionIdentifiers = Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::BreakpointActionIdentifier>::create(); - for (ScriptBreakpointAction& action : breakpointActions) - breakpointActionIdentifiers->addItem(action.identifier); + auto scriptIterator = m_scripts.find(sourceID); + if (scriptIterator == m_scripts.end()) { + errorString = ASCIILiteral("No script for id: ") + String::number(sourceID); + return; + } - String breakpointIdentifier = String::number(sourceID) + ':' + String::number(lineNumber) + ':' + String::number(columnNumber); - if (m_breakpointIdentifierToDebugServerBreakpointIDs.find(breakpointIdentifier) != m_breakpointIdentifierToDebugServerBreakpointIDs.end()) { - *errorString = ASCIILiteral("Breakpoint at specified location already exists."); + Script& script = scriptIterator->value; + JSC::Breakpoint breakpoint(sourceID, lineNumber, columnNumber, condition, autoContinue, ignoreCount); + resolveBreakpoint(script, breakpoint); + if (!breakpoint.resolved) { + errorString = ASCIILiteral("Could not resolve breakpoint"); return; } - ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition, breakpointActions, autoContinue); - actualLocation = resolveBreakpoint(breakpointIdentifier, sourceID, breakpoint); - if (!actualLocation) { - *errorString = ASCIILiteral("Could not resolve breakpoint"); + bool existing; + setBreakpoint(breakpoint, existing); + if (existing) { + errorString = ASCIILiteral("Breakpoint at specified location already exists"); return; } + String breakpointIdentifier = String::number(sourceID) + ':' + String::number(breakpoint.line) + ':' + String::number(breakpoint.column); + ScriptBreakpoint scriptBreakpoint(breakpoint.line, breakpoint.column, condition, breakpointActions, autoContinue, ignoreCount); + didSetBreakpoint(breakpoint, breakpointIdentifier, scriptBreakpoint); + + actualLocation = buildDebuggerLocation(breakpoint); *outBreakpointIdentifier = breakpointIdentifier; } -void InspectorDebuggerAgent::removeBreakpoint(ErrorString*, const String& breakpointIdentifier) +void InspectorDebuggerAgent::didSetBreakpoint(const JSC::Breakpoint& breakpoint, const String& breakpointIdentifier, const ScriptBreakpoint& scriptBreakpoint) +{ + JSC::BreakpointID id = breakpoint.id; + m_scriptDebugServer.setBreakpointActions(id, scriptBreakpoint); + + auto debugServerBreakpointIDsIterator = m_breakpointIdentifierToDebugServerBreakpointIDs.find(breakpointIdentifier); + if (debugServerBreakpointIDsIterator == m_breakpointIdentifierToDebugServerBreakpointIDs.end()) + debugServerBreakpointIDsIterator = m_breakpointIdentifierToDebugServerBreakpointIDs.set(breakpointIdentifier, Vector<JSC::BreakpointID>()).iterator; + debugServerBreakpointIDsIterator->value.append(id); + + m_debuggerBreakpointIdentifierToInspectorBreakpointIdentifier.set(id, breakpointIdentifier); +} + +void InspectorDebuggerAgent::resolveBreakpoint(const Script& script, JSC::Breakpoint& breakpoint) +{ + if (breakpoint.line < static_cast<unsigned>(script.startLine) || static_cast<unsigned>(script.endLine) < breakpoint.line) + return; + + m_scriptDebugServer.resolveBreakpoint(breakpoint, script.sourceProvider.get()); +} + +void InspectorDebuggerAgent::setBreakpoint(JSC::Breakpoint& breakpoint, bool& existing) +{ + JSC::JSLockHolder locker(m_scriptDebugServer.vm()); + m_scriptDebugServer.setBreakpoint(breakpoint, existing); +} + +void InspectorDebuggerAgent::removeBreakpoint(ErrorString&, const String& breakpointIdentifier) { m_javaScriptBreakpoints.remove(breakpointIdentifier); - Vector<JSC::BreakpointID> breakpointIDs = m_breakpointIdentifierToDebugServerBreakpointIDs.take(breakpointIdentifier); - for (auto breakpointID : breakpointIDs) { - const Vector<ScriptBreakpointAction>& breakpointActions = scriptDebugServer().getActionsForBreakpoint(breakpointID); + for (JSC::BreakpointID breakpointID : m_breakpointIdentifierToDebugServerBreakpointIDs.take(breakpointIdentifier)) { + m_debuggerBreakpointIdentifierToInspectorBreakpointIdentifier.remove(breakpointID); + + const BreakpointActions& breakpointActions = m_scriptDebugServer.getActionsForBreakpoint(breakpointID); for (auto& action : breakpointActions) - m_injectedScriptManager->releaseObjectGroup(objectGroupForBreakpointAction(action.identifier)); + m_injectedScriptManager.releaseObjectGroup(objectGroupForBreakpointAction(action)); - scriptDebugServer().removeBreakpoint(breakpointID); + JSC::JSLockHolder locker(m_scriptDebugServer.vm()); + m_scriptDebugServer.removeBreakpointActions(breakpointID); + m_scriptDebugServer.removeBreakpoint(breakpointID); } } -void InspectorDebuggerAgent::continueToLocation(ErrorString* errorString, const RefPtr<InspectorObject>& location) +void InspectorDebuggerAgent::continueUntilNextRunLoop(ErrorString& errorString) +{ + if (!assertPaused(errorString)) + return; + + resume(errorString); + + m_enablePauseWhenIdle = true; + + registerIdleHandler(); +} + +void InspectorDebuggerAgent::continueToLocation(ErrorString& errorString, const InspectorObject& location) { + if (!assertPaused(errorString)) + return; + if (m_continueToLocationBreakpointID != JSC::noBreakpointID) { - scriptDebugServer().removeBreakpoint(m_continueToLocationBreakpointID); + m_scriptDebugServer.removeBreakpoint(m_continueToLocationBreakpointID); m_continueToLocationBreakpointID = JSC::noBreakpointID; } JSC::SourceID sourceID; unsigned lineNumber; unsigned columnNumber; - if (!parseLocation(errorString, location.get(), &sourceID, &lineNumber, &columnNumber)) + if (!parseLocation(errorString, location, sourceID, lineNumber, columnNumber)) return; - ScriptBreakpoint breakpoint(lineNumber, columnNumber, "", false); - m_continueToLocationBreakpointID = scriptDebugServer().setBreakpoint(sourceID, breakpoint, &lineNumber, &columnNumber); - resume(errorString); -} + auto scriptIterator = m_scripts.find(sourceID); + if (scriptIterator == m_scripts.end()) { + m_scriptDebugServer.continueProgram(); + m_frontendDispatcher->resumed(); + errorString = ASCIILiteral("No script for id: ") + String::number(sourceID); + return; + } -PassRefPtr<Inspector::TypeBuilder::Debugger::Location> InspectorDebuggerAgent::resolveBreakpoint(const String& breakpointIdentifier, JSC::SourceID sourceID, const ScriptBreakpoint& breakpoint) -{ - ScriptsMap::iterator scriptIterator = m_scripts.find(sourceID); - if (scriptIterator == m_scripts.end()) - return nullptr; + String condition; + bool autoContinue = false; + unsigned ignoreCount = 0; + JSC::Breakpoint breakpoint(sourceID, lineNumber, columnNumber, condition, autoContinue, ignoreCount); Script& script = scriptIterator->value; - if (breakpoint.lineNumber < script.startLine || script.endLine < breakpoint.lineNumber) - return nullptr; + resolveBreakpoint(script, breakpoint); + if (!breakpoint.resolved) { + m_scriptDebugServer.continueProgram(); + m_frontendDispatcher->resumed(); + errorString = ASCIILiteral("Could not resolve breakpoint"); + return; + } - unsigned actualLineNumber; - unsigned actualColumnNumber; - JSC::BreakpointID debugServerBreakpointID = scriptDebugServer().setBreakpoint(sourceID, breakpoint, &actualLineNumber, &actualColumnNumber); - if (debugServerBreakpointID == JSC::noBreakpointID) - return nullptr; + bool existing; + setBreakpoint(breakpoint, existing); + if (existing) { + // There is an existing breakpoint at this location. Instead of + // acting like a series of steps, just resume and we will either + // hit this new breakpoint or not. + m_scriptDebugServer.continueProgram(); + m_frontendDispatcher->resumed(); + return; + } - BreakpointIdentifierToDebugServerBreakpointIDsMap::iterator debugServerBreakpointIDsIterator = m_breakpointIdentifierToDebugServerBreakpointIDs.find(breakpointIdentifier); - if (debugServerBreakpointIDsIterator == m_breakpointIdentifierToDebugServerBreakpointIDs.end()) - debugServerBreakpointIDsIterator = m_breakpointIdentifierToDebugServerBreakpointIDs.set(breakpointIdentifier, Vector<JSC::BreakpointID>()).iterator; - debugServerBreakpointIDsIterator->value.append(debugServerBreakpointID); + m_continueToLocationBreakpointID = breakpoint.id; - RefPtr<Inspector::TypeBuilder::Debugger::Location> location = Inspector::TypeBuilder::Debugger::Location::create() - .setScriptId(String::number(sourceID)) - .setLineNumber(actualLineNumber); - location->setColumnNumber(actualColumnNumber); - return location; + // Treat this as a series of steps until reaching the new breakpoint. + // So don't issue a resumed event unless we exit the VM without pausing. + willStepAndMayBecomeIdle(); + m_scriptDebugServer.continueProgram(); } -void InspectorDebuggerAgent::searchInContent(ErrorString* error, const String& scriptIDStr, const String& query, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::GenericTypes::SearchMatch>>& results) +void InspectorDebuggerAgent::searchInContent(ErrorString& error, const String& scriptIDStr, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>>& results) { + JSC::SourceID sourceID = scriptIDStr.toIntPtr(); + auto it = m_scripts.find(sourceID); + if (it == m_scripts.end()) { + error = ASCIILiteral("No script for id: ") + scriptIDStr; + return; + } + bool isRegex = optionalIsRegex ? *optionalIsRegex : false; bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false; - - JSC::SourceID sourceID = scriptIDStr.toIntPtr(); - ScriptsMap::iterator it = m_scripts.find(sourceID); - if (it != m_scripts.end()) - results = ContentSearchUtilities::searchInTextByLines(it->value.source, query, caseSensitive, isRegex); - else - *error = "No script for id: " + scriptIDStr; + results = ContentSearchUtilities::searchInTextByLines(it->value.source, query, caseSensitive, isRegex); } -void InspectorDebuggerAgent::getScriptSource(ErrorString* error, const String& scriptIDStr, String* scriptSource) +void InspectorDebuggerAgent::getScriptSource(ErrorString& error, const String& scriptIDStr, String* scriptSource) { JSC::SourceID sourceID = scriptIDStr.toIntPtr(); ScriptsMap::iterator it = m_scripts.find(sourceID); if (it != m_scripts.end()) *scriptSource = it->value.source; else - *error = "No script for id: " + scriptIDStr; + error = ASCIILiteral("No script for id: ") + scriptIDStr; } -void InspectorDebuggerAgent::getFunctionDetails(ErrorString* errorString, const String& functionId, RefPtr<Inspector::TypeBuilder::Debugger::FunctionDetails>& details) +void InspectorDebuggerAgent::getFunctionDetails(ErrorString& errorString, const String& functionId, RefPtr<Inspector::Protocol::Debugger::FunctionDetails>& details) { - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(functionId); + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(functionId); if (injectedScript.hasNoValue()) { - *errorString = ASCIILiteral("Function object id is obsolete"); + errorString = ASCIILiteral("Function object id is obsolete"); return; } injectedScript.getFunctionDetails(errorString, functionId, &details); } -void InspectorDebuggerAgent::schedulePauseOnNextStatement(InspectorDebuggerFrontendDispatcher::Reason::Enum breakReason, PassRefPtr<InspectorObject> data) +void InspectorDebuggerAgent::schedulePauseOnNextStatement(DebuggerFrontendDispatcher::Reason breakReason, RefPtr<InspectorObject>&& data) { if (m_javaScriptPauseScheduled) return; + m_javaScriptPauseScheduled = true; + m_breakReason = breakReason; - m_breakAuxData = data; - scriptDebugServer().setPauseOnNextStatement(true); + m_breakAuxData = WTFMove(data); + + JSC::JSLockHolder locker(m_scriptDebugServer.vm()); + m_scriptDebugServer.setPauseOnNextStatement(true); } void InspectorDebuggerAgent::cancelPauseOnNextStatement() { - if (m_javaScriptPauseScheduled) + if (!m_javaScriptPauseScheduled) return; + m_javaScriptPauseScheduled = false; + clearBreakDetails(); - scriptDebugServer().setPauseOnNextStatement(false); + m_scriptDebugServer.setPauseOnNextStatement(false); + m_enablePauseWhenIdle = false; } -void InspectorDebuggerAgent::pause(ErrorString*) +void InspectorDebuggerAgent::pause(ErrorString&) { - if (m_javaScriptPauseScheduled) + schedulePauseOnNextStatement(DebuggerFrontendDispatcher::Reason::PauseOnNextStatement, nullptr); +} + +void InspectorDebuggerAgent::resume(ErrorString& errorString) +{ + if (!m_pausedScriptState && !m_javaScriptPauseScheduled) { + errorString = ASCIILiteral("Was not paused or waiting to pause"); return; + } - clearBreakDetails(); - scriptDebugServer().setPauseOnNextStatement(true); - m_javaScriptPauseScheduled = true; + cancelPauseOnNextStatement(); + m_scriptDebugServer.continueProgram(); + m_conditionToDispatchResumed = ShouldDispatchResumed::WhenContinued; } -void InspectorDebuggerAgent::resume(ErrorString* errorString) +void InspectorDebuggerAgent::stepOver(ErrorString& errorString) { if (!assertPaused(errorString)) return; - m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup); - scriptDebugServer().continueProgram(); + willStepAndMayBecomeIdle(); + m_scriptDebugServer.stepOverStatement(); } -void InspectorDebuggerAgent::stepOver(ErrorString* errorString) +void InspectorDebuggerAgent::stepInto(ErrorString& errorString) { if (!assertPaused(errorString)) return; - m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup); - scriptDebugServer().stepOverStatement(); + willStepAndMayBecomeIdle(); + m_scriptDebugServer.stepIntoStatement(); } -void InspectorDebuggerAgent::stepInto(ErrorString* errorString) +void InspectorDebuggerAgent::stepOut(ErrorString& errorString) { if (!assertPaused(errorString)) return; - m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup); - scriptDebugServer().stepIntoStatement(); - m_listener->stepInto(); + willStepAndMayBecomeIdle(); + m_scriptDebugServer.stepOutOfFunction(); } -void InspectorDebuggerAgent::stepOut(ErrorString* errorString) +void InspectorDebuggerAgent::registerIdleHandler() { - if (!assertPaused(errorString)) - return; + if (!m_registeredIdleCallback) { + m_registeredIdleCallback = true; + JSC::VM& vm = m_scriptDebugServer.vm(); + vm.whenIdle([this]() { + didBecomeIdle(); + }); + } +} - m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup); - scriptDebugServer().stepOutOfFunction(); +void InspectorDebuggerAgent::willStepAndMayBecomeIdle() +{ + // When stepping the backend must eventually trigger a "paused" or "resumed" event. + // If the step causes us to exit the VM, then we should issue "resumed". + m_conditionToDispatchResumed = ShouldDispatchResumed::WhenIdle; + + registerIdleHandler(); } -void InspectorDebuggerAgent::setPauseOnExceptions(ErrorString* errorString, const String& stringPauseState) +void InspectorDebuggerAgent::didBecomeIdle() +{ + m_registeredIdleCallback = false; + + if (m_conditionToDispatchResumed == ShouldDispatchResumed::WhenIdle) { + cancelPauseOnNextStatement(); + m_scriptDebugServer.continueProgram(); + m_frontendDispatcher->resumed(); + } + + m_conditionToDispatchResumed = ShouldDispatchResumed::No; + + if (m_enablePauseWhenIdle) { + ErrorString ignored; + pause(ignored); + } +} + +void InspectorDebuggerAgent::setPauseOnExceptions(ErrorString& errorString, const String& stringPauseState) { JSC::Debugger::PauseOnExceptionsState pauseState; if (stringPauseState == "none") @@ -506,114 +807,139 @@ void InspectorDebuggerAgent::setPauseOnExceptions(ErrorString* errorString, cons else if (stringPauseState == "uncaught") pauseState = JSC::Debugger::PauseOnUncaughtExceptions; else { - *errorString = "Unknown pause on exceptions mode: " + stringPauseState; + errorString = ASCIILiteral("Unknown pause on exceptions mode: ") + stringPauseState; return; } - scriptDebugServer().setPauseOnExceptionsState(static_cast<JSC::Debugger::PauseOnExceptionsState>(pauseState)); - if (scriptDebugServer().pauseOnExceptionsState() != pauseState) - *errorString = ASCIILiteral("Internal error. Could not change pause on exceptions state"); + m_scriptDebugServer.setPauseOnExceptionsState(static_cast<JSC::Debugger::PauseOnExceptionsState>(pauseState)); + if (m_scriptDebugServer.pauseOnExceptionsState() != pauseState) + errorString = ASCIILiteral("Internal error. Could not change pause on exceptions state"); +} + +void InspectorDebuggerAgent::setPauseOnAssertions(ErrorString&, bool enabled) +{ + m_pauseOnAssertionFailures = enabled; } -void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString* errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>& result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) +void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString& errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, const bool* saveResult, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result, Inspector::Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex) { - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(callFrameId); + if (m_currentCallStack.hasNoValue()) { + errorString = ASCIILiteral("Not paused"); + return; + } + + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(callFrameId); if (injectedScript.hasNoValue()) { - *errorString = ASCIILiteral("Inspected frame has gone"); + errorString = ASCIILiteral("Could not find InjectedScript for callFrameId"); return; } - JSC::Debugger::PauseOnExceptionsState previousPauseOnExceptionsState = scriptDebugServer().pauseOnExceptionsState(); + JSC::Debugger::PauseOnExceptionsState previousPauseOnExceptionsState = m_scriptDebugServer.pauseOnExceptionsState(); if (doNotPauseOnExceptionsAndMuteConsole ? *doNotPauseOnExceptionsAndMuteConsole : false) { if (previousPauseOnExceptionsState != JSC::Debugger::DontPauseOnExceptions) - scriptDebugServer().setPauseOnExceptionsState(JSC::Debugger::DontPauseOnExceptions); + m_scriptDebugServer.setPauseOnExceptionsState(JSC::Debugger::DontPauseOnExceptions); muteConsole(); } - injectedScript.evaluateOnCallFrame(errorString, m_currentCallStack, callFrameId, expression, objectGroup ? *objectGroup : "", includeCommandLineAPI ? *includeCommandLineAPI : false, returnByValue ? *returnByValue : false, generatePreview ? *generatePreview : false, &result, wasThrown); + injectedScript.evaluateOnCallFrame(errorString, m_currentCallStack, callFrameId, expression, objectGroup ? *objectGroup : "", includeCommandLineAPI ? *includeCommandLineAPI : false, returnByValue ? *returnByValue : false, generatePreview ? *generatePreview : false, saveResult ? *saveResult : false, &result, wasThrown, savedResultIndex); if (doNotPauseOnExceptionsAndMuteConsole ? *doNotPauseOnExceptionsAndMuteConsole : false) { unmuteConsole(); - if (scriptDebugServer().pauseOnExceptionsState() != previousPauseOnExceptionsState) - scriptDebugServer().setPauseOnExceptionsState(previousPauseOnExceptionsState); + if (m_scriptDebugServer.pauseOnExceptionsState() != previousPauseOnExceptionsState) + m_scriptDebugServer.setPauseOnExceptionsState(previousPauseOnExceptionsState); } } -void InspectorDebuggerAgent::setOverlayMessage(ErrorString*, const String*) +void InspectorDebuggerAgent::setOverlayMessage(ErrorString&, const String*) { } void InspectorDebuggerAgent::scriptExecutionBlockedByCSP(const String& directiveText) { - if (scriptDebugServer().pauseOnExceptionsState() != JSC::Debugger::DontPauseOnExceptions) { - RefPtr<InspectorObject> directive = InspectorObject::create(); - directive->setString(ASCIILiteral("directiveText"), directiveText); - breakProgram(InspectorDebuggerFrontendDispatcher::Reason::CSPViolation, directive.release()); - } + if (m_scriptDebugServer.pauseOnExceptionsState() != JSC::Debugger::DontPauseOnExceptions) + breakProgram(DebuggerFrontendDispatcher::Reason::CSPViolation, buildCSPViolationPauseReason(directiveText)); } -PassRefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::CallFrame>> InspectorDebuggerAgent::currentCallFrames() +Ref<Inspector::Protocol::Array<Inspector::Protocol::Debugger::CallFrame>> InspectorDebuggerAgent::currentCallFrames(const InjectedScript& injectedScript) { - if (!m_pausedScriptState) - return Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::CallFrame>::create(); - - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(m_pausedScriptState); - if (injectedScript.hasNoValue()) { - ASSERT_NOT_REACHED(); - return Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::CallFrame>::create(); - } + ASSERT(!injectedScript.hasNoValue()); + if (injectedScript.hasNoValue()) + return Inspector::Protocol::Array<Inspector::Protocol::Debugger::CallFrame>::create(); return injectedScript.wrapCallFrames(m_currentCallStack); } String InspectorDebuggerAgent::sourceMapURLForScript(const Script& script) { - return ContentSearchUtilities::findScriptSourceMapURL(script.source); + return script.sourceMappingURL; } -void InspectorDebuggerAgent::didParseSource(JSC::SourceID sourceID, const Script& inScript) +static bool isWebKitInjectedScript(const String& sourceURL) { - Script script = inScript; - if (script.startLine <= 0 && !script.startColumn) - script.sourceURL = ContentSearchUtilities::findScriptSourceURL(script.source); - script.sourceMappingURL = sourceMapURLForScript(script); + return sourceURL.startsWith("__InjectedScript_") && sourceURL.endsWith(".js"); +} +void InspectorDebuggerAgent::didParseSource(JSC::SourceID sourceID, const Script& script) +{ + String scriptIDStr = String::number(sourceID); bool hasSourceURL = !script.sourceURL.isEmpty(); - String scriptURL = hasSourceURL ? script.sourceURL : script.url; - bool* hasSourceURLParam = hasSourceURL ? &hasSourceURL : nullptr; - String* sourceMapURLParam = script.sourceMappingURL.isNull() ? nullptr : &script.sourceMappingURL; + String sourceURL = script.sourceURL; + String sourceMappingURL = sourceMapURLForScript(script); + + const bool isModule = script.sourceProvider->sourceType() == JSC::SourceProviderSourceType::Module; const bool* isContentScript = script.isContentScript ? &script.isContentScript : nullptr; - String scriptIDStr = String::number(sourceID); - m_frontendDispatcher->scriptParsed(scriptIDStr, scriptURL, script.startLine, script.startColumn, script.endLine, script.endColumn, isContentScript, sourceMapURLParam, hasSourceURLParam); + String* sourceURLParam = hasSourceURL ? &sourceURL : nullptr; + String* sourceMapURLParam = sourceMappingURL.isEmpty() ? nullptr : &sourceMappingURL; + + m_frontendDispatcher->scriptParsed(scriptIDStr, script.url, script.startLine, script.startColumn, script.endLine, script.endColumn, isContentScript, sourceURLParam, sourceMapURLParam, isModule ? &isModule : nullptr); m_scripts.set(sourceID, script); - if (scriptURL.isEmpty()) + if (hasSourceURL && isWebKitInjectedScript(sourceURL)) + m_scriptDebugServer.addToBlacklist(sourceID); + + String scriptURLForBreakpoints = hasSourceURL ? script.sourceURL : script.url; + if (scriptURLForBreakpoints.isEmpty()) return; - for (auto it = m_javaScriptBreakpoints.begin(), end = m_javaScriptBreakpoints.end(); it != end; ++it) { - RefPtr<InspectorObject> breakpointObject = it->value->asObject(); + for (auto& entry : m_javaScriptBreakpoints) { + RefPtr<InspectorObject> breakpointObject = entry.value; + bool isRegex; - breakpointObject->getBoolean(ASCIILiteral("isRegex"), &isRegex); String url; - breakpointObject->getString(ASCIILiteral("url"), &url); - if (!matches(scriptURL, url, isRegex)) + breakpointObject->getBoolean(ASCIILiteral("isRegex"), isRegex); + breakpointObject->getString(ASCIILiteral("url"), url); + if (!matches(scriptURLForBreakpoints, url, isRegex)) continue; - ScriptBreakpoint breakpoint; - breakpointObject->getNumber(ASCIILiteral("lineNumber"), &breakpoint.lineNumber); - breakpointObject->getNumber(ASCIILiteral("columnNumber"), &breakpoint.columnNumber); - breakpointObject->getString(ASCIILiteral("condition"), &breakpoint.condition); - breakpointObject->getBoolean(ASCIILiteral("autoContinue"), &breakpoint.autoContinue); + + ScriptBreakpoint scriptBreakpoint; + breakpointObject->getInteger(ASCIILiteral("lineNumber"), scriptBreakpoint.lineNumber); + breakpointObject->getInteger(ASCIILiteral("columnNumber"), scriptBreakpoint.columnNumber); + breakpointObject->getString(ASCIILiteral("condition"), scriptBreakpoint.condition); + breakpointObject->getBoolean(ASCIILiteral("autoContinue"), scriptBreakpoint.autoContinue); + breakpointObject->getInteger(ASCIILiteral("ignoreCount"), scriptBreakpoint.ignoreCount); ErrorString errorString; - RefPtr<InspectorArray> actions = breakpointObject->getArray(ASCIILiteral("actions")); - if (!breakpointActionsFromProtocol(&errorString, actions, &breakpoint.actions)) { + RefPtr<InspectorArray> actions; + breakpointObject->getArray(ASCIILiteral("actions"), actions); + if (!breakpointActionsFromProtocol(errorString, actions, &scriptBreakpoint.actions)) { ASSERT_NOT_REACHED(); continue; } - RefPtr<Inspector::TypeBuilder::Debugger::Location> location = resolveBreakpoint(it->key, sourceID, breakpoint); - if (location) - m_frontendDispatcher->breakpointResolved(it->key, location); + JSC::Breakpoint breakpoint(sourceID, scriptBreakpoint.lineNumber, scriptBreakpoint.columnNumber, scriptBreakpoint.condition, scriptBreakpoint.autoContinue, scriptBreakpoint.ignoreCount); + resolveBreakpoint(script, breakpoint); + if (!breakpoint.resolved) + continue; + + bool existing; + setBreakpoint(breakpoint, existing); + if (existing) + continue; + + String breakpointIdentifier = entry.key; + didSetBreakpoint(breakpoint, breakpointIdentifier, scriptBreakpoint); + + m_frontendDispatcher->breakpointResolved(breakpointIdentifier, buildDebuggerLocation(breakpoint)); } } @@ -622,94 +948,173 @@ void InspectorDebuggerAgent::failedToParseSource(const String& url, const String m_frontendDispatcher->scriptFailedToParse(url, data, firstLine, errorLine, errorMessage); } -void InspectorDebuggerAgent::didPause(JSC::ExecState* scriptState, const Deprecated::ScriptValue& callFrames, const Deprecated::ScriptValue& exception) +void InspectorDebuggerAgent::didPause(JSC::ExecState& scriptState, JSC::JSValue callFrames, JSC::JSValue exceptionOrCaughtValue) { - ASSERT(scriptState && !m_pausedScriptState); - m_pausedScriptState = scriptState; - m_currentCallStack = callFrames; - - if (!exception.hasNoValue()) { - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(scriptState); - if (!injectedScript.hasNoValue()) { - m_breakReason = InspectorDebuggerFrontendDispatcher::Reason::Exception; - m_breakAuxData = injectedScript.wrapObject(exception, InspectorDebuggerAgent::backtraceObjectGroup)->openAccessors(); - // m_breakAuxData might be null after this. + ASSERT(!m_pausedScriptState); + m_pausedScriptState = &scriptState; + m_currentCallStack = { scriptState.vm(), callFrames }; + + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptFor(&scriptState); + + // If a high level pause pause reason is not already set, try to infer a reason from the debugger. + if (m_breakReason == DebuggerFrontendDispatcher::Reason::Other) { + switch (m_scriptDebugServer.reasonForPause()) { + case JSC::Debugger::PausedForBreakpoint: { + JSC::BreakpointID debuggerBreakpointId = m_scriptDebugServer.pausingBreakpointID(); + if (debuggerBreakpointId != m_continueToLocationBreakpointID) { + m_breakReason = DebuggerFrontendDispatcher::Reason::Breakpoint; + m_breakAuxData = buildBreakpointPauseReason(debuggerBreakpointId); + } + break; } + case JSC::Debugger::PausedForDebuggerStatement: + m_breakReason = DebuggerFrontendDispatcher::Reason::DebuggerStatement; + m_breakAuxData = nullptr; + break; + case JSC::Debugger::PausedForException: + m_breakReason = DebuggerFrontendDispatcher::Reason::Exception; + m_breakAuxData = buildExceptionPauseReason(exceptionOrCaughtValue, injectedScript); + break; + case JSC::Debugger::PausedAtStatement: + case JSC::Debugger::PausedAtExpression: + case JSC::Debugger::PausedBeforeReturn: + case JSC::Debugger::PausedAtEndOfProgram: + // Pause was just stepping. Nothing to report. + break; + case JSC::Debugger::NotPaused: + ASSERT_NOT_REACHED(); + break; + } + } + + // Set $exception to the exception or caught value. + if (exceptionOrCaughtValue && !injectedScript.hasNoValue()) { + injectedScript.setExceptionValue(exceptionOrCaughtValue); + m_hasExceptionValue = true; } - m_frontendDispatcher->paused(currentCallFrames(), m_breakReason, m_breakAuxData); + m_conditionToDispatchResumed = ShouldDispatchResumed::No; + m_enablePauseWhenIdle = false; + + RefPtr<Inspector::Protocol::Console::StackTrace> asyncStackTrace; + if (m_currentAsyncCallIdentifier) { + auto it = m_pendingAsyncCalls.find(m_currentAsyncCallIdentifier.value()); + if (it != m_pendingAsyncCalls.end()) + asyncStackTrace = it->value->buildInspectorObject(); + } + + m_frontendDispatcher->paused(currentCallFrames(injectedScript), m_breakReason, m_breakAuxData, asyncStackTrace); + m_javaScriptPauseScheduled = false; if (m_continueToLocationBreakpointID != JSC::noBreakpointID) { - scriptDebugServer().removeBreakpoint(m_continueToLocationBreakpointID); + m_scriptDebugServer.removeBreakpoint(m_continueToLocationBreakpointID); m_continueToLocationBreakpointID = JSC::noBreakpointID; } - if (m_listener) - m_listener->didPause(); + RefPtr<Stopwatch> stopwatch = m_injectedScriptManager.inspectorEnvironment().executionStopwatch(); + if (stopwatch && stopwatch->isActive()) { + stopwatch->stop(); + m_didPauseStopwatch = true; + } } -void InspectorDebuggerAgent::didSampleProbe(JSC::ExecState* scriptState, int probeIdentifier, int hitCount, const Deprecated::ScriptValue& sample) +void InspectorDebuggerAgent::breakpointActionSound(int breakpointActionIdentifier) { - int sampleId = m_nextProbeSampleId++; - - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(scriptState); - RefPtr<TypeBuilder::Runtime::RemoteObject> payload = injectedScript.wrapObject(sample, objectGroupForBreakpointAction(probeIdentifier)); - RefPtr<TypeBuilder::Debugger::ProbeSample> result = TypeBuilder::Debugger::ProbeSample::create() - .setProbeId(probeIdentifier) - .setSampleId(sampleId) - .setBatchId(hitCount) - .setTimestamp(monotonicallyIncreasingTime()) - .setPayload(payload.release()); - - m_frontendDispatcher->didSampleProbe(result.release()); + m_frontendDispatcher->playBreakpointActionSound(breakpointActionIdentifier); } -void InspectorDebuggerAgent::breakpointActionSound() +void InspectorDebuggerAgent::breakpointActionProbe(JSC::ExecState& scriptState, const ScriptBreakpointAction& action, unsigned batchId, unsigned sampleId, JSC::JSValue sample) { - // FIXME: We should send a message to the frontend to make the frontend beep. + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptFor(&scriptState); + auto payload = injectedScript.wrapObject(sample, objectGroupForBreakpointAction(action), true); + auto result = Protocol::Debugger::ProbeSample::create() + .setProbeId(action.identifier) + .setBatchId(batchId) + .setSampleId(sampleId) + .setTimestamp(m_injectedScriptManager.inspectorEnvironment().executionStopwatch()->elapsedTime()) + .setPayload(WTFMove(payload)) + .release(); + m_frontendDispatcher->didSampleProbe(WTFMove(result)); } void InspectorDebuggerAgent::didContinue() { + if (m_didPauseStopwatch) { + m_didPauseStopwatch = false; + m_injectedScriptManager.inspectorEnvironment().executionStopwatch()->start(); + } + m_pausedScriptState = nullptr; - m_currentCallStack = Deprecated::ScriptValue(); + m_currentCallStack = { }; + m_injectedScriptManager.releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup); clearBreakDetails(); + clearExceptionValue(); - m_frontendDispatcher->resumed(); + if (m_conditionToDispatchResumed == ShouldDispatchResumed::WhenContinued) + m_frontendDispatcher->resumed(); } -void InspectorDebuggerAgent::breakProgram(InspectorDebuggerFrontendDispatcher::Reason::Enum breakReason, PassRefPtr<InspectorObject> data) +void InspectorDebuggerAgent::breakProgram(DebuggerFrontendDispatcher::Reason breakReason, RefPtr<InspectorObject>&& data) { m_breakReason = breakReason; - m_breakAuxData = data; - scriptDebugServer().breakProgram(); + m_breakAuxData = WTFMove(data); + m_scriptDebugServer.breakProgram(); } -void InspectorDebuggerAgent::clearResolvedBreakpointState() +void InspectorDebuggerAgent::clearInspectorBreakpointState() { ErrorString dummyError; Vector<String> breakpointIdentifiers; copyKeysToVector(m_breakpointIdentifierToDebugServerBreakpointIDs, breakpointIdentifiers); for (const String& identifier : breakpointIdentifiers) - removeBreakpoint(&dummyError, identifier); + removeBreakpoint(dummyError, identifier); - scriptDebugServer().continueProgram(); + m_javaScriptBreakpoints.clear(); + + clearDebuggerBreakpointState(); +} + +void InspectorDebuggerAgent::clearDebuggerBreakpointState() +{ + { + JSC::JSLockHolder holder(m_scriptDebugServer.vm()); + m_scriptDebugServer.clearBreakpointActions(); + m_scriptDebugServer.clearBreakpoints(); + m_scriptDebugServer.clearBlacklist(); + } m_pausedScriptState = nullptr; - m_currentCallStack = Deprecated::ScriptValue(); + m_currentCallStack = { }; m_scripts.clear(); m_breakpointIdentifierToDebugServerBreakpointIDs.clear(); + m_debuggerBreakpointIdentifierToInspectorBreakpointIdentifier.clear(); m_continueToLocationBreakpointID = JSC::noBreakpointID; clearBreakDetails(); m_javaScriptPauseScheduled = false; - setOverlayMessage(&dummyError, nullptr); + m_hasExceptionValue = false; + + if (isPaused()) { + m_scriptDebugServer.continueProgram(); + m_frontendDispatcher->resumed(); + } } -bool InspectorDebuggerAgent::assertPaused(ErrorString* errorString) +void InspectorDebuggerAgent::didClearGlobalObject() +{ + // Clear breakpoints from the debugger, but keep the inspector's model of which + // pages have what breakpoints, as the mapping is only sent to DebuggerAgent once. + clearDebuggerBreakpointState(); + + clearAsyncStackTraceData(); + + m_frontendDispatcher->globalObjectCleared(); +} + +bool InspectorDebuggerAgent::assertPaused(ErrorString& errorString) { if (!m_pausedScriptState) { - *errorString = ASCIILiteral("Can only perform operation while paused."); + errorString = ASCIILiteral("Can only perform operation while paused."); return false; } @@ -718,18 +1123,22 @@ bool InspectorDebuggerAgent::assertPaused(ErrorString* errorString) void InspectorDebuggerAgent::clearBreakDetails() { - m_breakReason = InspectorDebuggerFrontendDispatcher::Reason::Other; + m_breakReason = DebuggerFrontendDispatcher::Reason::Other; m_breakAuxData = nullptr; } -void InspectorDebuggerAgent::didClearGlobalObject() +void InspectorDebuggerAgent::clearExceptionValue() { - if (m_frontendDispatcher) - m_frontendDispatcher->globalObjectCleared(); + if (m_hasExceptionValue) { + m_injectedScriptManager.clearExceptionValue(); + m_hasExceptionValue = false; + } +} - clearResolvedBreakpointState(); +void InspectorDebuggerAgent::clearAsyncStackTraceData() +{ + m_pendingAsyncCalls.clear(); + m_currentAsyncCallIdentifier = std::nullopt; } } // namespace Inspector - -#endif // ENABLE(INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.h b/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.h index 0e652499d..6f8132ac2 100644 --- a/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.h +++ b/Source/JavaScriptCore/inspector/agents/InspectorDebuggerAgent.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2010, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2010-2011 Google Inc. All rights reserved. + * Copyright (C) 2010, 2013, 2015-2016 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -11,7 +11,7 @@ * 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 Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -27,37 +27,32 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorDebuggerAgent_h -#define InspectorDebuggerAgent_h +#pragma once -#if ENABLE(INSPECTOR) - -#include "InspectorJSBackendDispatchers.h" -#include "InspectorJSFrontendDispatchers.h" +#include "InspectorBackendDispatchers.h" +#include "InspectorFrontendDispatchers.h" #include "bindings/ScriptValue.h" #include "debugger/Debugger.h" #include "inspector/InspectorAgentBase.h" #include "inspector/ScriptBreakpoint.h" +#include "inspector/ScriptCallStack.h" #include "inspector/ScriptDebugListener.h" #include <wtf/Forward.h> #include <wtf/HashMap.h> #include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/PassRefPtr.h> #include <wtf/Vector.h> -#include <wtf/text/StringHash.h> namespace Inspector { +class AsyncStackTrace; class InjectedScript; class InjectedScriptManager; class InspectorArray; class InspectorObject; -class InspectorValue; class ScriptDebugServer; typedef String ErrorString; -class JS_EXPORT_PRIVATE InspectorDebuggerAgent : public InspectorAgentBase, public ScriptDebugListener, public InspectorDebuggerBackendDispatcherHandler { +class JS_EXPORT_PRIVATE InspectorDebuggerAgent : public InspectorAgentBase, public ScriptDebugListener, public DebuggerBackendDispatcherHandler { WTF_MAKE_NONCOPYABLE(InspectorDebuggerAgent); WTF_MAKE_FAST_ALLOCATED; public: @@ -65,35 +60,48 @@ public: virtual ~InspectorDebuggerAgent(); - virtual void didCreateFrontendAndBackend(InspectorFrontendChannel*, InspectorBackendDispatcher*) override; - virtual void willDestroyFrontendAndBackend(InspectorDisconnectReason) override; - - virtual void enable(ErrorString*) override; - virtual void disable(ErrorString*) override; - virtual void setBreakpointsActive(ErrorString*, bool active) override; - virtual void setBreakpointByUrl(ErrorString*, int lineNumber, const String* optionalURL, const String* optionalURLRegex, const int* optionalColumnNumber, const RefPtr<Inspector::InspectorObject>* options, Inspector::TypeBuilder::Debugger::BreakpointId*, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::Location>>& locations, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::BreakpointActionIdentifier>>& breakpointActionIdentifiers) override; - virtual void setBreakpoint(ErrorString*, const RefPtr<Inspector::InspectorObject>& location, const RefPtr<Inspector::InspectorObject>* options, Inspector::TypeBuilder::Debugger::BreakpointId*, RefPtr<Inspector::TypeBuilder::Debugger::Location>& actualLocation, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::BreakpointActionIdentifier>>& breakpointActionIdentifiers) override; - virtual void removeBreakpoint(ErrorString*, const String& breakpointIdentifier) override; - virtual void continueToLocation(ErrorString*, const RefPtr<InspectorObject>& location) override; - virtual void searchInContent(ErrorString*, const String& scriptID, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::GenericTypes::SearchMatch>>&) override; - virtual void getScriptSource(ErrorString*, const String& scriptID, String* scriptSource) override; - virtual void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<Inspector::TypeBuilder::Debugger::FunctionDetails>&) override; - virtual void pause(ErrorString*) override; - virtual void resume(ErrorString*) override; - virtual void stepOver(ErrorString*) override; - virtual void stepInto(ErrorString*) override; - virtual void stepOut(ErrorString*) override; - virtual void setPauseOnExceptions(ErrorString*, const String& pauseState) override; - virtual void evaluateOnCallFrame(ErrorString*, const String& callFrameId, const String& expression, const String* objectGroup, const bool* includeCommandLineAPI, const bool* doNotPauseOnExceptionsAndMuteConsole, const bool* returnByValue, const bool* generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>& result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) override; - virtual void setOverlayMessage(ErrorString*, const String*) override; - - bool isPaused(); - - void handleConsoleAssert(); - - void schedulePauseOnNextStatement(InspectorDebuggerFrontendDispatcher::Reason::Enum breakReason, PassRefPtr<InspectorObject> data); + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) final; + void willDestroyFrontendAndBackend(DisconnectReason) final; + + void enable(ErrorString&) final; + void disable(ErrorString&) final; + void setAsyncStackTraceDepth(ErrorString&, int depth) final; + void setBreakpointsActive(ErrorString&, bool active) final; + void setBreakpointByUrl(ErrorString&, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const Inspector::InspectorObject* options, Inspector::Protocol::Debugger::BreakpointId*, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Debugger::Location>>& locations) final; + void setBreakpoint(ErrorString&, const Inspector::InspectorObject& location, const Inspector::InspectorObject* options, Inspector::Protocol::Debugger::BreakpointId*, RefPtr<Inspector::Protocol::Debugger::Location>& actualLocation) final; + void removeBreakpoint(ErrorString&, const String& breakpointIdentifier) final; + void continueUntilNextRunLoop(ErrorString&) final; + void continueToLocation(ErrorString&, const InspectorObject& location) final; + void searchInContent(ErrorString&, const String& scriptID, const String& query, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>>&) final; + void getScriptSource(ErrorString&, const String& scriptID, String* scriptSource) final; + void getFunctionDetails(ErrorString&, const String& functionId, RefPtr<Inspector::Protocol::Debugger::FunctionDetails>&) final; + void pause(ErrorString&) final; + void resume(ErrorString&) final; + void stepOver(ErrorString&) final; + void stepInto(ErrorString&) final; + void stepOut(ErrorString&) final; + void setPauseOnExceptions(ErrorString&, const String& pauseState) final; + void setPauseOnAssertions(ErrorString&, bool enabled) final; + void evaluateOnCallFrame(ErrorString&, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* const generatePreview, const bool* const saveResult, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result, Inspector::Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex) final; + void setOverlayMessage(ErrorString&, const String* const) override; + + bool isPaused() const; + bool breakpointsActive() const; + + void setSuppressAllPauses(bool); + + void handleConsoleAssert(const String& message); + + void didScheduleAsyncCall(JSC::ExecState*, int asyncCallType, int callbackIdentifier, bool singleShot); + void didCancelAsyncCall(int asyncCallType, int callbackIdentifier); + void willDispatchAsyncCall(int asyncCallType, int callbackIdentifier); + void didDispatchAsyncCall(); + + void schedulePauseOnNextStatement(DebuggerFrontendDispatcher::Reason breakReason, RefPtr<InspectorObject>&& data); void cancelPauseOnNextStatement(); - void breakProgram(InspectorDebuggerFrontendDispatcher::Reason::Enum breakReason, PassRefPtr<InspectorObject> data); + bool pauseOnNextStatementEnabled() const { return m_javaScriptPauseScheduled; } + + void breakProgram(DebuggerFrontendDispatcher::Reason breakReason, RefPtr<InspectorObject>&& data); void scriptExecutionBlockedByCSP(const String& directiveText); class Listener { @@ -101,73 +109,91 @@ public: virtual ~Listener() { } virtual void debuggerWasEnabled() = 0; virtual void debuggerWasDisabled() = 0; - virtual void stepInto() = 0; - virtual void didPause() = 0; }; void setListener(Listener* listener) { m_listener = listener; } - virtual ScriptDebugServer& scriptDebugServer() = 0; - protected: - InspectorDebuggerAgent(InjectedScriptManager*); + InspectorDebuggerAgent(AgentContext&); - InjectedScriptManager* injectedScriptManager() const { return m_injectedScriptManager; } - virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) = 0; + InjectedScriptManager& injectedScriptManager() const { return m_injectedScriptManager; } + virtual InjectedScript injectedScriptForEval(ErrorString&, const int* executionContextId) = 0; + + ScriptDebugServer& scriptDebugServer() { return m_scriptDebugServer; } - virtual void startListeningScriptDebugServer() = 0; - virtual void stopListeningScriptDebugServer(bool skipRecompile) = 0; virtual void muteConsole() = 0; virtual void unmuteConsole() = 0; virtual void enable(); virtual void disable(bool skipRecompile); - virtual void didPause(JSC::ExecState*, const Deprecated::ScriptValue& callFrames, const Deprecated::ScriptValue& exception) override; - virtual void didContinue() override; + void didPause(JSC::ExecState&, JSC::JSValue callFrames, JSC::JSValue exceptionOrCaughtValue) final; + void didContinue() final; virtual String sourceMapURLForScript(const Script&); void didClearGlobalObject(); private: - PassRefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Debugger::CallFrame>> currentCallFrames(); + Ref<Inspector::Protocol::Array<Inspector::Protocol::Debugger::CallFrame>> currentCallFrames(const InjectedScript&); + + void didParseSource(JSC::SourceID, const Script&) final; + void failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage) final; - virtual void didParseSource(JSC::SourceID, const Script&) override final; - virtual void failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage) override final; - virtual void didSampleProbe(JSC::ExecState*, int probeIdentifier, int hitCount, const Deprecated::ScriptValue& sample) override final; + void breakpointActionSound(int breakpointActionIdentifier) final; + void breakpointActionProbe(JSC::ExecState&, const ScriptBreakpointAction&, unsigned batchId, unsigned sampleId, JSC::JSValue sample) final; - virtual void breakpointActionSound() override; + void resolveBreakpoint(const Script&, JSC::Breakpoint&); + void setBreakpoint(JSC::Breakpoint&, bool& existing); + void didSetBreakpoint(const JSC::Breakpoint&, const String&, const ScriptBreakpoint&); - PassRefPtr<Inspector::TypeBuilder::Debugger::Location> resolveBreakpoint(const String& breakpointIdentifier, JSC::SourceID, const ScriptBreakpoint&); - bool assertPaused(ErrorString*); - void clearResolvedBreakpointState(); + bool assertPaused(ErrorString&); + void clearDebuggerBreakpointState(); + void clearInspectorBreakpointState(); void clearBreakDetails(); + void clearExceptionValue(); + void clearAsyncStackTraceData(); + + enum class ShouldDispatchResumed { No, WhenIdle, WhenContinued }; + void registerIdleHandler(); + void willStepAndMayBecomeIdle(); + void didBecomeIdle(); - bool breakpointActionsFromProtocol(ErrorString*, RefPtr<InspectorArray>& actions, Vector<ScriptBreakpointAction>* result); + RefPtr<InspectorObject> buildBreakpointPauseReason(JSC::BreakpointID); + RefPtr<InspectorObject> buildExceptionPauseReason(JSC::JSValue exception, const InjectedScript&); + + bool breakpointActionsFromProtocol(ErrorString&, RefPtr<InspectorArray>& actions, BreakpointActions* result); + + typedef std::pair<int, int> AsyncCallIdentifier; typedef HashMap<JSC::SourceID, Script> ScriptsMap; typedef HashMap<String, Vector<JSC::BreakpointID>> BreakpointIdentifierToDebugServerBreakpointIDsMap; typedef HashMap<String, RefPtr<InspectorObject>> BreakpointIdentifierToBreakpointMap; - - InjectedScriptManager* m_injectedScriptManager; - std::unique_ptr<InspectorDebuggerFrontendDispatcher> m_frontendDispatcher; - RefPtr<InspectorDebuggerBackendDispatcher> m_backendDispatcher; - Listener* m_listener; - JSC::ExecState* m_pausedScriptState; + typedef HashMap<JSC::BreakpointID, String> DebugServerBreakpointIDToBreakpointIdentifier; + + InjectedScriptManager& m_injectedScriptManager; + std::unique_ptr<DebuggerFrontendDispatcher> m_frontendDispatcher; + RefPtr<DebuggerBackendDispatcher> m_backendDispatcher; + ScriptDebugServer& m_scriptDebugServer; + Listener* m_listener { nullptr }; + JSC::ExecState* m_pausedScriptState { nullptr }; Deprecated::ScriptValue m_currentCallStack; ScriptsMap m_scripts; BreakpointIdentifierToDebugServerBreakpointIDsMap m_breakpointIdentifierToDebugServerBreakpointIDs; BreakpointIdentifierToBreakpointMap m_javaScriptBreakpoints; + DebugServerBreakpointIDToBreakpointIdentifier m_debuggerBreakpointIdentifierToInspectorBreakpointIdentifier; JSC::BreakpointID m_continueToLocationBreakpointID; - InspectorDebuggerFrontendDispatcher::Reason::Enum m_breakReason; + DebuggerFrontendDispatcher::Reason m_breakReason; RefPtr<InspectorObject> m_breakAuxData; - bool m_enabled; - bool m_javaScriptPauseScheduled; - int m_nextProbeSampleId; - int m_nextBreakpointActionIdentifier; + ShouldDispatchResumed m_conditionToDispatchResumed { ShouldDispatchResumed::No }; + bool m_enablePauseWhenIdle { false }; + HashMap<AsyncCallIdentifier, RefPtr<AsyncStackTrace>> m_pendingAsyncCalls; + std::optional<AsyncCallIdentifier> m_currentAsyncCallIdentifier { std::nullopt }; + bool m_enabled { false }; + bool m_javaScriptPauseScheduled { false }; + bool m_hasExceptionValue { false }; + bool m_didPauseStopwatch { false }; + bool m_pauseOnAssertionFailures { false }; + bool m_registeredIdleCallback { false }; + int m_asyncStackTraceDepth { 0 }; }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(InspectorDebuggerAgent_h) diff --git a/Source/JavaScriptCore/inspector/agents/InspectorHeapAgent.cpp b/Source/JavaScriptCore/inspector/agents/InspectorHeapAgent.cpp new file mode 100644 index 000000000..b33ae982d --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/InspectorHeapAgent.cpp @@ -0,0 +1,314 @@ +/* + * Copyright (C) 2015-2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InspectorHeapAgent.h" + +#include "HeapProfiler.h" +#include "InjectedScript.h" +#include "InjectedScriptManager.h" +#include "InspectorEnvironment.h" +#include "JSCInlines.h" +#include "VM.h" +#include <wtf/Stopwatch.h> + +using namespace JSC; + +namespace Inspector { + +InspectorHeapAgent::InspectorHeapAgent(AgentContext& context) + : InspectorAgentBase(ASCIILiteral("Heap")) + , m_injectedScriptManager(context.injectedScriptManager) + , m_frontendDispatcher(std::make_unique<HeapFrontendDispatcher>(context.frontendRouter)) + , m_backendDispatcher(HeapBackendDispatcher::create(context.backendDispatcher, this)) + , m_environment(context.environment) +{ +} + +InspectorHeapAgent::~InspectorHeapAgent() +{ +} + +void InspectorHeapAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) +{ +} + +void InspectorHeapAgent::willDestroyFrontendAndBackend(DisconnectReason) +{ + // Stop tracking without taking a snapshot. + m_tracking = false; + + ErrorString ignored; + disable(ignored); +} + +void InspectorHeapAgent::enable(ErrorString&) +{ + if (m_enabled) + return; + + m_enabled = true; + + m_environment.vm().heap.addObserver(this); +} + +void InspectorHeapAgent::disable(ErrorString&) +{ + if (!m_enabled) + return; + + m_enabled = false; + + m_environment.vm().heap.removeObserver(this); + + clearHeapSnapshots(); +} + +void InspectorHeapAgent::gc(ErrorString&) +{ + VM& vm = m_environment.vm(); + JSLockHolder lock(vm); + sanitizeStackForVM(&vm); + vm.heap.collectAllGarbage(); +} + +void InspectorHeapAgent::snapshot(ErrorString&, double* timestamp, String* snapshotData) +{ + VM& vm = m_environment.vm(); + JSLockHolder lock(vm); + + HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler()); + snapshotBuilder.buildSnapshot(); + + *timestamp = m_environment.executionStopwatch()->elapsedTime(); + *snapshotData = snapshotBuilder.json([&] (const HeapSnapshotNode& node) { + if (Structure* structure = node.cell->structure(vm)) { + if (JSGlobalObject* globalObject = structure->globalObject()) { + if (!m_environment.canAccessInspectedScriptState(globalObject->globalExec())) + return false; + } + } + return true; + }); +} + +void InspectorHeapAgent::startTracking(ErrorString& errorString) +{ + if (m_tracking) + return; + + m_tracking = true; + + double timestamp; + String snapshotData; + snapshot(errorString, ×tamp, &snapshotData); + + m_frontendDispatcher->trackingStart(timestamp, snapshotData); +} + +void InspectorHeapAgent::stopTracking(ErrorString& errorString) +{ + if (!m_tracking) + return; + + m_tracking = false; + + double timestamp; + String snapshotData; + snapshot(errorString, ×tamp, &snapshotData); + + m_frontendDispatcher->trackingComplete(timestamp, snapshotData); +} + +std::optional<HeapSnapshotNode> InspectorHeapAgent::nodeForHeapObjectIdentifier(ErrorString& errorString, unsigned heapObjectIdentifier) +{ + HeapProfiler* heapProfiler = m_environment.vm().heapProfiler(); + if (!heapProfiler) { + errorString = ASCIILiteral("No heap snapshot"); + return std::nullopt; + } + + HeapSnapshot* snapshot = heapProfiler->mostRecentSnapshot(); + if (!snapshot) { + errorString = ASCIILiteral("No heap snapshot"); + return std::nullopt; + } + + const std::optional<HeapSnapshotNode> optionalNode = snapshot->nodeForObjectIdentifier(heapObjectIdentifier); + if (!optionalNode) { + errorString = ASCIILiteral("No object for identifier, it may have been collected"); + return std::nullopt; + } + + return optionalNode; +} + +void InspectorHeapAgent::getPreview(ErrorString& errorString, int heapObjectId, Inspector::Protocol::OptOutput<String>* resultString, RefPtr<Inspector::Protocol::Debugger::FunctionDetails>& functionDetails, RefPtr<Inspector::Protocol::Runtime::ObjectPreview>& objectPreview) +{ + // Prevent the cell from getting collected as we look it up. + VM& vm = m_environment.vm(); + JSLockHolder lock(vm); + DeferGC deferGC(vm.heap); + + unsigned heapObjectIdentifier = static_cast<unsigned>(heapObjectId); + const std::optional<HeapSnapshotNode> optionalNode = nodeForHeapObjectIdentifier(errorString, heapObjectIdentifier); + if (!optionalNode) + return; + + // String preview. + JSCell* cell = optionalNode->cell; + if (cell->isString()) { + *resultString = asString(cell)->tryGetValue(); + return; + } + + // FIXME: Provide preview information for Internal Objects? CodeBlock, Executable, etc. + + Structure* structure = cell->structure(vm); + if (!structure) { + errorString = ASCIILiteral("Unable to get object details - Structure"); + return; + } + + JSGlobalObject* globalObject = structure->globalObject(); + if (!globalObject) { + errorString = ASCIILiteral("Unable to get object details - GlobalObject"); + return; + } + + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptFor(globalObject->globalExec()); + if (injectedScript.hasNoValue()) { + errorString = ASCIILiteral("Unable to get object details - InjectedScript"); + return; + } + + // Function preview. + if (cell->inherits(vm, JSFunction::info())) { + injectedScript.functionDetails(errorString, cell, &functionDetails); + return; + } + + // Object preview. + objectPreview = injectedScript.previewValue(cell); +} + +void InspectorHeapAgent::getRemoteObject(ErrorString& errorString, int heapObjectId, const String* const optionalObjectGroup, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result) +{ + // Prevent the cell from getting collected as we look it up. + VM& vm = m_environment.vm(); + JSLockHolder lock(vm); + DeferGC deferGC(vm.heap); + + unsigned heapObjectIdentifier = static_cast<unsigned>(heapObjectId); + const std::optional<HeapSnapshotNode> optionalNode = nodeForHeapObjectIdentifier(errorString, heapObjectIdentifier); + if (!optionalNode) + return; + + JSCell* cell = optionalNode->cell; + Structure* structure = cell->structure(vm); + if (!structure) { + errorString = ASCIILiteral("Unable to get object details"); + return; + } + + JSGlobalObject* globalObject = structure->globalObject(); + if (!globalObject) { + errorString = ASCIILiteral("Unable to get object details"); + return; + } + + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptFor(globalObject->globalExec()); + if (injectedScript.hasNoValue()) { + errorString = ASCIILiteral("Unable to get object details - InjectedScript"); + return; + } + + String objectGroup = optionalObjectGroup ? *optionalObjectGroup : String(); + result = injectedScript.wrapObject(cell, objectGroup, true); +} + +static Inspector::Protocol::Heap::GarbageCollection::Type protocolTypeForHeapOperation(CollectionScope scope) +{ + switch (scope) { + case CollectionScope::Full: + return Inspector::Protocol::Heap::GarbageCollection::Type::Full; + case CollectionScope::Eden: + return Inspector::Protocol::Heap::GarbageCollection::Type::Partial; + } + ASSERT_NOT_REACHED(); + return Inspector::Protocol::Heap::GarbageCollection::Type::Full; +} + +void InspectorHeapAgent::willGarbageCollect() +{ + if (!m_enabled) + return; + + m_gcStartTime = m_environment.executionStopwatch()->elapsedTime(); +} + +void InspectorHeapAgent::didGarbageCollect(CollectionScope scope) +{ + if (!m_enabled) { + m_gcStartTime = NAN; + return; + } + + if (std::isnan(m_gcStartTime)) { + // We were not enabled when the GC began. + return; + } + + // FIXME: Include number of bytes freed by collection. + + double endTime = m_environment.executionStopwatch()->elapsedTime(); + dispatchGarbageCollectedEvent(protocolTypeForHeapOperation(scope), m_gcStartTime, endTime); + + m_gcStartTime = NAN; +} + +void InspectorHeapAgent::clearHeapSnapshots() +{ + VM& vm = m_environment.vm(); + JSLockHolder lock(vm); + + if (HeapProfiler* heapProfiler = vm.heapProfiler()) { + heapProfiler->clearSnapshots(); + HeapSnapshotBuilder::resetNextAvailableObjectIdentifier(); + } +} + +void InspectorHeapAgent::dispatchGarbageCollectedEvent(Inspector::Protocol::Heap::GarbageCollection::Type type, double startTime, double endTime) +{ + auto protocolObject = Inspector::Protocol::Heap::GarbageCollection::create() + .setType(type) + .setStartTime(startTime) + .setEndTime(endTime) + .release(); + + m_frontendDispatcher->garbageCollected(WTFMove(protocolObject)); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/InspectorHeapAgent.h b/Source/JavaScriptCore/inspector/agents/InspectorHeapAgent.h new file mode 100644 index 000000000..421566a04 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/InspectorHeapAgent.h @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2015-2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "HeapSnapshot.h" +#include "InspectorBackendDispatchers.h" +#include "InspectorFrontendDispatchers.h" +#include "heap/HeapObserver.h" +#include "inspector/InspectorAgentBase.h" +#include <wtf/Forward.h> +#include <wtf/Noncopyable.h> + +namespace Inspector { + +class InjectedScriptManager; +typedef String ErrorString; + +class JS_EXPORT_PRIVATE InspectorHeapAgent : public InspectorAgentBase, public HeapBackendDispatcherHandler, public JSC::HeapObserver { + WTF_MAKE_NONCOPYABLE(InspectorHeapAgent); +public: + InspectorHeapAgent(AgentContext&); + virtual ~InspectorHeapAgent(); + + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) override; + void willDestroyFrontendAndBackend(DisconnectReason) override; + + // HeapBackendDispatcherHandler + void enable(ErrorString&) override; + void disable(ErrorString&) override; + void gc(ErrorString&) final; + void snapshot(ErrorString&, double* timestamp, String* snapshotData) final; + void startTracking(ErrorString&) final; + void stopTracking(ErrorString&) final; + void getPreview(ErrorString&, int heapObjectId, Inspector::Protocol::OptOutput<String>* resultString, RefPtr<Inspector::Protocol::Debugger::FunctionDetails>& functionDetails, RefPtr<Inspector::Protocol::Runtime::ObjectPreview>& objectPreview) final; + void getRemoteObject(ErrorString&, int heapObjectId, const String* const optionalObjectGroup, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result) final; + + // HeapObserver + void willGarbageCollect() override; + void didGarbageCollect(JSC::CollectionScope) override; + +protected: + void clearHeapSnapshots(); + + virtual void dispatchGarbageCollectedEvent(Inspector::Protocol::Heap::GarbageCollection::Type, double startTime, double endTime); + +private: + std::optional<JSC::HeapSnapshotNode> nodeForHeapObjectIdentifier(ErrorString&, unsigned heapObjectIdentifier); + + InjectedScriptManager& m_injectedScriptManager; + std::unique_ptr<HeapFrontendDispatcher> m_frontendDispatcher; + RefPtr<HeapBackendDispatcher> m_backendDispatcher; + InspectorEnvironment& m_environment; + + bool m_enabled { false }; + bool m_tracking { false }; + double m_gcStartTime { NAN }; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.cpp b/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.cpp index 76a47fb3a..d42c8968c 100644 --- a/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.cpp +++ b/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013, 2014 Apple Inc. All rights reserved. + * Copyright (C) 2013-2015 Apple Inc. All rights reserved. * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -32,17 +32,20 @@ #include "config.h" #include "InspectorRuntimeAgent.h" -#if ENABLE(INSPECTOR) - #include "Completion.h" +#include "DFGWorklist.h" +#include "HeapIterationScope.h" #include "InjectedScript.h" #include "InjectedScriptManager.h" +#include "InspectorFrontendRouter.h" #include "InspectorValues.h" #include "JSLock.h" #include "ParserError.h" #include "ScriptDebugServer.h" #include "SourceCode.h" -#include <wtf/PassRefPtr.h> +#include "TypeProfiler.h" +#include "TypeProfilerLog.h" +#include <wtf/CurrentTime.h> using namespace JSC; @@ -53,11 +56,11 @@ static bool asBool(const bool* const b) return b ? *b : false; } -InspectorRuntimeAgent::InspectorRuntimeAgent(InjectedScriptManager* injectedScriptManager) +InspectorRuntimeAgent::InspectorRuntimeAgent(AgentContext& context) : InspectorAgentBase(ASCIILiteral("Runtime")) - , m_injectedScriptManager(injectedScriptManager) - , m_scriptDebugServer(nullptr) - , m_enabled(false) + , m_injectedScriptManager(context.injectedScriptManager) + , m_scriptDebugServer(context.environment.scriptDebugServer()) + , m_vm(context.environment.vm()) { } @@ -65,53 +68,51 @@ InspectorRuntimeAgent::~InspectorRuntimeAgent() { } -static ScriptDebugServer::PauseOnExceptionsState setPauseOnExceptionsState(ScriptDebugServer* scriptDebugServer, ScriptDebugServer::PauseOnExceptionsState newState) +static ScriptDebugServer::PauseOnExceptionsState setPauseOnExceptionsState(ScriptDebugServer& scriptDebugServer, ScriptDebugServer::PauseOnExceptionsState newState) { - ASSERT(scriptDebugServer); - ScriptDebugServer::PauseOnExceptionsState presentState = scriptDebugServer->pauseOnExceptionsState(); + ScriptDebugServer::PauseOnExceptionsState presentState = scriptDebugServer.pauseOnExceptionsState(); if (presentState != newState) - scriptDebugServer->setPauseOnExceptionsState(newState); + scriptDebugServer.setPauseOnExceptionsState(newState); return presentState; } -static PassRefPtr<Inspector::TypeBuilder::Runtime::ErrorRange> buildErrorRangeObject(const JSTokenLocation& tokenLocation) +static Ref<Inspector::Protocol::Runtime::ErrorRange> buildErrorRangeObject(const JSTokenLocation& tokenLocation) { - RefPtr<Inspector::TypeBuilder::Runtime::ErrorRange> result = Inspector::TypeBuilder::Runtime::ErrorRange::create() + return Inspector::Protocol::Runtime::ErrorRange::create() .setStartOffset(tokenLocation.startOffset) - .setEndOffset(tokenLocation.endOffset); - return result.release(); + .setEndOffset(tokenLocation.endOffset) + .release(); } -void InspectorRuntimeAgent::parse(ErrorString*, const String& expression, Inspector::TypeBuilder::Runtime::SyntaxErrorType::Enum* result, Inspector::TypeBuilder::OptOutput<String>* message, RefPtr<Inspector::TypeBuilder::Runtime::ErrorRange>& range) +void InspectorRuntimeAgent::parse(ErrorString&, const String& expression, Inspector::Protocol::Runtime::SyntaxErrorType* result, Inspector::Protocol::OptOutput<String>* message, RefPtr<Inspector::Protocol::Runtime::ErrorRange>& range) { - VM* vm = globalVM(); - JSLockHolder lock(vm); + JSLockHolder lock(m_vm); ParserError error; - checkSyntax(*vm, JSC::makeSource(expression), error); + checkSyntax(m_vm, JSC::makeSource(expression, { }), error); - switch (error.m_syntaxErrorType) { + switch (error.syntaxErrorType()) { case ParserError::SyntaxErrorNone: - *result = Inspector::TypeBuilder::Runtime::SyntaxErrorType::None; + *result = Inspector::Protocol::Runtime::SyntaxErrorType::None; break; case ParserError::SyntaxErrorIrrecoverable: - *result = Inspector::TypeBuilder::Runtime::SyntaxErrorType::Irrecoverable; + *result = Inspector::Protocol::Runtime::SyntaxErrorType::Irrecoverable; break; case ParserError::SyntaxErrorUnterminatedLiteral: - *result = Inspector::TypeBuilder::Runtime::SyntaxErrorType::UnterminatedLiteral; + *result = Inspector::Protocol::Runtime::SyntaxErrorType::UnterminatedLiteral; break; case ParserError::SyntaxErrorRecoverable: - *result = Inspector::TypeBuilder::Runtime::SyntaxErrorType::Recoverable; + *result = Inspector::Protocol::Runtime::SyntaxErrorType::Recoverable; break; } - if (error.m_syntaxErrorType != ParserError::SyntaxErrorNone) { - *message = error.m_message; - range = buildErrorRangeObject(error.m_token.m_location); + if (error.syntaxErrorType() != ParserError::SyntaxErrorNone) { + *message = error.message(); + range = buildErrorRangeObject(error.token().m_location); } } -void InspectorRuntimeAgent::evaluate(ErrorString* errorString, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const int* executionContextId, const bool* const returnByValue, const bool* generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>& result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) +void InspectorRuntimeAgent::evaluate(ErrorString& errorString, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const int* executionContextId, const bool* const returnByValue, const bool* generatePreview, const bool* saveResult, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result, Inspector::Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex) { InjectedScript injectedScript = injectedScriptForEval(errorString, executionContextId); if (injectedScript.hasNoValue()) @@ -123,7 +124,7 @@ void InspectorRuntimeAgent::evaluate(ErrorString* errorString, const String& exp if (asBool(doNotPauseOnExceptionsAndMuteConsole)) muteConsole(); - injectedScript.evaluate(errorString, expression, objectGroup ? *objectGroup : "", asBool(includeCommandLineAPI), asBool(returnByValue), asBool(generatePreview), &result, wasThrown); + injectedScript.evaluate(errorString, expression, objectGroup ? *objectGroup : String(), asBool(includeCommandLineAPI), asBool(returnByValue), asBool(generatePreview), asBool(saveResult), &result, wasThrown, savedResultIndex); if (asBool(doNotPauseOnExceptionsAndMuteConsole)) { unmuteConsole(); @@ -131,17 +132,17 @@ void InspectorRuntimeAgent::evaluate(ErrorString* errorString, const String& exp } } -void InspectorRuntimeAgent::callFunctionOn(ErrorString* errorString, const String& objectId, const String& expression, const RefPtr<InspectorArray>* const optionalArguments, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>& result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) +void InspectorRuntimeAgent::callFunctionOn(ErrorString& errorString, const String& objectId, const String& expression, const InspectorArray* optionalArguments, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result, Inspector::Protocol::OptOutput<bool>* wasThrown) { - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(objectId); + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(objectId); if (injectedScript.hasNoValue()) { - *errorString = ASCIILiteral("Inspected frame has gone"); + errorString = ASCIILiteral("Could not find InjectedScript for objectId"); return; } String arguments; if (optionalArguments) - arguments = (*optionalArguments)->toJSONString(); + arguments = optionalArguments->toJSONString(); ScriptDebugServer::PauseOnExceptionsState previousPauseOnExceptionsState = ScriptDebugServer::DontPauseOnExceptions; if (asBool(doNotPauseOnExceptionsAndMuteConsole)) @@ -157,40 +158,224 @@ void InspectorRuntimeAgent::callFunctionOn(ErrorString* errorString, const Strin } } -void InspectorRuntimeAgent::getProperties(ErrorString* errorString, const String& objectId, const bool* const ownProperties, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Runtime::PropertyDescriptor>>& result, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Runtime::InternalPropertyDescriptor>>& internalProperties) +void InspectorRuntimeAgent::getProperties(ErrorString& errorString, const String& objectId, const bool* const ownProperties, const bool* const generatePreview, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::PropertyDescriptor>>& result, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::InternalPropertyDescriptor>>& internalProperties) { - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(objectId); + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(objectId); if (injectedScript.hasNoValue()) { - *errorString = ASCIILiteral("Inspected frame has gone"); + errorString = ASCIILiteral("Could not find InjectedScript for objectId"); return; } ScriptDebugServer::PauseOnExceptionsState previousPauseOnExceptionsState = setPauseOnExceptionsState(m_scriptDebugServer, ScriptDebugServer::DontPauseOnExceptions); muteConsole(); - injectedScript.getProperties(errorString, objectId, ownProperties ? *ownProperties : false, &result); - injectedScript.getInternalProperties(errorString, objectId, &internalProperties); + injectedScript.getProperties(errorString, objectId, asBool(ownProperties), asBool(generatePreview), &result); + injectedScript.getInternalProperties(errorString, objectId, asBool(generatePreview), &internalProperties); unmuteConsole(); setPauseOnExceptionsState(m_scriptDebugServer, previousPauseOnExceptionsState); } -void InspectorRuntimeAgent::releaseObject(ErrorString*, const String& objectId) +void InspectorRuntimeAgent::getDisplayableProperties(ErrorString& errorString, const String& objectId, const bool* const generatePreview, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::PropertyDescriptor>>& result, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::InternalPropertyDescriptor>>& internalProperties) { - InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(objectId); + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(objectId); + if (injectedScript.hasNoValue()) { + errorString = ASCIILiteral("Could not find InjectedScript for objectId"); + return; + } + + ScriptDebugServer::PauseOnExceptionsState previousPauseOnExceptionsState = setPauseOnExceptionsState(m_scriptDebugServer, ScriptDebugServer::DontPauseOnExceptions); + muteConsole(); + + injectedScript.getDisplayableProperties(errorString, objectId, asBool(generatePreview), &result); + injectedScript.getInternalProperties(errorString, objectId, asBool(generatePreview), &internalProperties); + + unmuteConsole(); + setPauseOnExceptionsState(m_scriptDebugServer, previousPauseOnExceptionsState); +} + +void InspectorRuntimeAgent::getCollectionEntries(ErrorString& errorString, const String& objectId, const String* objectGroup, const int* startIndex, const int* numberToFetch, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::CollectionEntry>>& entries) +{ + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(objectId); + if (injectedScript.hasNoValue()) { + errorString = ASCIILiteral("Could not find InjectedScript for objectId"); + return; + } + + int start = startIndex && *startIndex >= 0 ? *startIndex : 0; + int fetch = numberToFetch && *numberToFetch >= 0 ? *numberToFetch : 0; + + injectedScript.getCollectionEntries(errorString, objectId, objectGroup ? *objectGroup : String(), start, fetch, &entries); +} + +void InspectorRuntimeAgent::saveResult(ErrorString& errorString, const Inspector::InspectorObject& callArgument, const int* executionContextId, Inspector::Protocol::OptOutput<int>* savedResultIndex) +{ + InjectedScript injectedScript; + + String objectId; + if (callArgument.getString(ASCIILiteral("objectId"), objectId)) { + injectedScript = m_injectedScriptManager.injectedScriptForObjectId(objectId); + if (injectedScript.hasNoValue()) { + errorString = ASCIILiteral("Could not find InjectedScript for objectId"); + return; + } + } else { + injectedScript = injectedScriptForEval(errorString, executionContextId); + if (injectedScript.hasNoValue()) + return; + } + + injectedScript.saveResult(errorString, callArgument.toJSONString(), savedResultIndex); +} + +void InspectorRuntimeAgent::releaseObject(ErrorString&, const String& objectId) +{ + InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(objectId); if (!injectedScript.hasNoValue()) injectedScript.releaseObject(objectId); } -void InspectorRuntimeAgent::releaseObjectGroup(ErrorString*, const String& objectGroup) +void InspectorRuntimeAgent::releaseObjectGroup(ErrorString&, const String& objectGroup) +{ + m_injectedScriptManager.releaseObjectGroup(objectGroup); +} + +void InspectorRuntimeAgent::getRuntimeTypesForVariablesAtOffsets(ErrorString& errorString, const Inspector::InspectorArray& locations, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::TypeDescription>>& typeDescriptions) +{ + static const bool verbose = false; + + typeDescriptions = Inspector::Protocol::Array<Inspector::Protocol::Runtime::TypeDescription>::create(); + if (!m_vm.typeProfiler()) { + errorString = ASCIILiteral("The VM does not currently have Type Information."); + return; + } + + double start = currentTimeMS(); + m_vm.typeProfilerLog()->processLogEntries(ASCIILiteral("User Query")); + + for (size_t i = 0; i < locations.length(); i++) { + RefPtr<Inspector::InspectorValue> value = locations.get(i); + RefPtr<InspectorObject> location; + if (!value->asObject(location)) { + errorString = ASCIILiteral("Array of TypeLocation objects has an object that does not have type of TypeLocation."); + return; + } + + int descriptor; + String sourceIDAsString; + int divot; + location->getInteger(ASCIILiteral("typeInformationDescriptor"), descriptor); + location->getString(ASCIILiteral("sourceID"), sourceIDAsString); + location->getInteger(ASCIILiteral("divot"), divot); + + bool okay; + TypeLocation* typeLocation = m_vm.typeProfiler()->findLocation(divot, sourceIDAsString.toIntPtrStrict(&okay), static_cast<TypeProfilerSearchDescriptor>(descriptor), m_vm); + ASSERT(okay); + + RefPtr<TypeSet> typeSet; + if (typeLocation) { + if (typeLocation->m_globalTypeSet && typeLocation->m_globalVariableID != TypeProfilerNoGlobalIDExists) + typeSet = typeLocation->m_globalTypeSet; + else + typeSet = typeLocation->m_instructionTypeSet; + } + + bool isValid = typeLocation && typeSet && !typeSet->isEmpty(); + auto description = Inspector::Protocol::Runtime::TypeDescription::create() + .setIsValid(isValid) + .release(); + + if (isValid) { + description->setLeastCommonAncestor(typeSet->leastCommonAncestor()); + description->setStructures(typeSet->allStructureRepresentations()); + description->setTypeSet(typeSet->inspectorTypeSet()); + description->setIsTruncated(typeSet->isOverflown()); + } + + typeDescriptions->addItem(WTFMove(description)); + } + + double end = currentTimeMS(); + if (verbose) + dataLogF("Inspector::getRuntimeTypesForVariablesAtOffsets took %lfms\n", end - start); +} + +void InspectorRuntimeAgent::willDestroyFrontendAndBackend(DisconnectReason reason) { - m_injectedScriptManager->releaseObjectGroup(objectGroup); + if (reason != DisconnectReason::InspectedTargetDestroyed && m_isTypeProfilingEnabled) + setTypeProfilerEnabledState(false); } -void InspectorRuntimeAgent::run(ErrorString*) +void InspectorRuntimeAgent::enableTypeProfiler(ErrorString&) { + setTypeProfilerEnabledState(true); } -} // namespace Inspector +void InspectorRuntimeAgent::disableTypeProfiler(ErrorString&) +{ + setTypeProfilerEnabledState(false); +} -#endif // ENABLE(INSPECTOR) +void InspectorRuntimeAgent::enableControlFlowProfiler(ErrorString&) +{ + setControlFlowProfilerEnabledState(true); +} + +void InspectorRuntimeAgent::disableControlFlowProfiler(ErrorString&) +{ + setControlFlowProfilerEnabledState(false); +} + +void InspectorRuntimeAgent::setTypeProfilerEnabledState(bool isTypeProfilingEnabled) +{ + if (m_isTypeProfilingEnabled == isTypeProfilingEnabled) + return; + m_isTypeProfilingEnabled = isTypeProfilingEnabled; + + VM& vm = m_vm; + vm.whenIdle([&vm, isTypeProfilingEnabled] () { + bool shouldRecompileFromTypeProfiler = (isTypeProfilingEnabled ? vm.enableTypeProfiler() : vm.disableTypeProfiler()); + if (shouldRecompileFromTypeProfiler) + vm.deleteAllCode(PreventCollectionAndDeleteAllCode); + }); +} + +void InspectorRuntimeAgent::setControlFlowProfilerEnabledState(bool isControlFlowProfilingEnabled) +{ + if (m_isControlFlowProfilingEnabled == isControlFlowProfilingEnabled) + return; + m_isControlFlowProfilingEnabled = isControlFlowProfilingEnabled; + + VM& vm = m_vm; + vm.whenIdle([&vm, isControlFlowProfilingEnabled] () { + bool shouldRecompileFromControlFlowProfiler = (isControlFlowProfilingEnabled ? vm.enableControlFlowProfiler() : vm.disableControlFlowProfiler()); + + if (shouldRecompileFromControlFlowProfiler) + vm.deleteAllCode(PreventCollectionAndDeleteAllCode); + }); +} + +void InspectorRuntimeAgent::getBasicBlocks(ErrorString& errorString, const String& sourceIDAsString, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::BasicBlock>>& basicBlocks) +{ + if (!m_vm.controlFlowProfiler()) { + errorString = ASCIILiteral("The VM does not currently have a Control Flow Profiler."); + return; + } + + bool okay; + intptr_t sourceID = sourceIDAsString.toIntPtrStrict(&okay); + ASSERT(okay); + const Vector<BasicBlockRange>& basicBlockRanges = m_vm.controlFlowProfiler()->getBasicBlocksForSourceID(sourceID, m_vm); + basicBlocks = Inspector::Protocol::Array<Inspector::Protocol::Runtime::BasicBlock>::create(); + for (const BasicBlockRange& block : basicBlockRanges) { + Ref<Inspector::Protocol::Runtime::BasicBlock> location = Inspector::Protocol::Runtime::BasicBlock::create() + .setStartOffset(block.m_startOffset) + .setEndOffset(block.m_endOffset) + .setHasExecuted(block.m_hasExecuted) + .setExecutionCount(block.m_executionCount) + .release(); + basicBlocks->addItem(WTFMove(location)); + } +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.h b/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.h index 2bc6e2994..2d2f626ec 100644 --- a/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.h +++ b/Source/JavaScriptCore/inspector/agents/InspectorRuntimeAgent.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2013, 2015-2016 Apple Inc. All rights reserved. * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -29,13 +29,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef InspectorRuntimeAgent_h -#define InspectorRuntimeAgent_h +#pragma once -#if ENABLE(INSPECTOR) - -#include "InspectorJSBackendDispatchers.h" -#include "InspectorJSFrontendDispatchers.h" +#include "InspectorBackendDispatchers.h" +#include "InspectorFrontendDispatchers.h" #include "inspector/InspectorAgentBase.h" #include <wtf/Forward.h> #include <wtf/Noncopyable.h> @@ -52,43 +49,53 @@ class InspectorArray; class ScriptDebugServer; typedef String ErrorString; -class JS_EXPORT_PRIVATE InspectorRuntimeAgent : public InspectorAgentBase, public InspectorRuntimeBackendDispatcherHandler { +class JS_EXPORT_PRIVATE InspectorRuntimeAgent : public InspectorAgentBase, public RuntimeBackendDispatcherHandler { WTF_MAKE_NONCOPYABLE(InspectorRuntimeAgent); public: virtual ~InspectorRuntimeAgent(); - virtual void enable(ErrorString*) override { m_enabled = true; } - virtual void disable(ErrorString*) override { m_enabled = false; } - virtual void parse(ErrorString*, const String& expression, Inspector::TypeBuilder::Runtime::SyntaxErrorType::Enum* result, Inspector::TypeBuilder::OptOutput<String>* message, RefPtr<Inspector::TypeBuilder::Runtime::ErrorRange>&) override final; - virtual void evaluate(ErrorString*, const String& expression, const String* objectGroup, const bool* includeCommandLineAPI, const bool* doNotPauseOnExceptionsAndMuteConsole, const int* executionContextId, const bool* returnByValue, const bool* generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>& result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) override final; - virtual void callFunctionOn(ErrorString*, const String& objectId, const String& expression, const RefPtr<Inspector::InspectorArray>* optionalArguments, const bool* doNotPauseOnExceptionsAndMuteConsole, const bool* returnByValue, const bool* generatePreview, RefPtr<Inspector::TypeBuilder::Runtime::RemoteObject>& result, Inspector::TypeBuilder::OptOutput<bool>* wasThrown) override final; - virtual void releaseObject(ErrorString*, const ErrorString& objectId) override final; - virtual void getProperties(ErrorString*, const String& objectId, const bool* ownProperties, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Runtime::PropertyDescriptor>>& result, RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::Runtime::InternalPropertyDescriptor>>& internalProperties) override final; - virtual void releaseObjectGroup(ErrorString*, const String& objectGroup) override final; - virtual void run(ErrorString*) override; - - void setScriptDebugServer(ScriptDebugServer* scriptDebugServer) { m_scriptDebugServer = scriptDebugServer; } + void willDestroyFrontendAndBackend(DisconnectReason) override; + + void enable(ErrorString&) override { m_enabled = true; } + void disable(ErrorString&) override { m_enabled = false; } + void parse(ErrorString&, const String& expression, Inspector::Protocol::Runtime::SyntaxErrorType* result, Inspector::Protocol::OptOutput<String>* message, RefPtr<Inspector::Protocol::Runtime::ErrorRange>&) final; + void evaluate(ErrorString&, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const int* const executionContextId, const bool* const returnByValue, const bool* const generatePreview, const bool* const saveResult, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result, Inspector::Protocol::OptOutput<bool>* wasThrown, Inspector::Protocol::OptOutput<int>* savedResultIndex) final; + void callFunctionOn(ErrorString&, const String& objectId, const String& expression, const Inspector::InspectorArray* optionalArguments, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* const generatePreview, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result, Inspector::Protocol::OptOutput<bool>* wasThrown) final; + void releaseObject(ErrorString&, const ErrorString& objectId) final; + void getProperties(ErrorString&, const String& objectId, const bool* const ownProperties, const bool* const generatePreview, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::PropertyDescriptor>>& result, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::InternalPropertyDescriptor>>& internalProperties) final; + void getDisplayableProperties(ErrorString&, const String& objectId, const bool* const generatePreview, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::PropertyDescriptor>>& result, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::InternalPropertyDescriptor>>& internalProperties) final; + void getCollectionEntries(ErrorString&, const String& objectId, const String* const objectGroup, const int* const startIndex, const int* const numberToFetch, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::CollectionEntry>>& entries) final; + void saveResult(ErrorString&, const Inspector::InspectorObject& callArgument, const int* const executionContextId, Inspector::Protocol::OptOutput<int>* savedResultIndex) final; + void releaseObjectGroup(ErrorString&, const String& objectGroup) final; + void getRuntimeTypesForVariablesAtOffsets(ErrorString&, const Inspector::InspectorArray& locations, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::TypeDescription>>&) override; + void enableTypeProfiler(ErrorString&) override; + void disableTypeProfiler(ErrorString&) override; + void enableControlFlowProfiler(ErrorString&) override; + void disableControlFlowProfiler(ErrorString&) override; + void getBasicBlocks(ErrorString&, const String& in_sourceID, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::BasicBlock>>& out_basicBlocks) override; bool enabled() const { return m_enabled; } protected: - InspectorRuntimeAgent(InjectedScriptManager*); + InspectorRuntimeAgent(AgentContext&); - InjectedScriptManager* injectedScriptManager() { return m_injectedScriptManager; } + InjectedScriptManager& injectedScriptManager() { return m_injectedScriptManager; } - virtual JSC::VM* globalVM() = 0; - virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) = 0; + virtual InjectedScript injectedScriptForEval(ErrorString&, const int* executionContextId) = 0; virtual void muteConsole() = 0; virtual void unmuteConsole() = 0; private: - InjectedScriptManager* m_injectedScriptManager; - ScriptDebugServer* m_scriptDebugServer; - bool m_enabled; + void setTypeProfilerEnabledState(bool); + void setControlFlowProfilerEnabledState(bool); + + InjectedScriptManager& m_injectedScriptManager; + ScriptDebugServer& m_scriptDebugServer; + JSC::VM& m_vm; + bool m_enabled {false}; + bool m_isTypeProfilingEnabled {false}; + bool m_isControlFlowProfilingEnabled {false}; }; } // namespace Inspector - -#endif // ENABLE(INSPECTOR) -#endif // InspectorRuntimeAgent_h diff --git a/Source/JavaScriptCore/inspector/agents/InspectorScriptProfilerAgent.cpp b/Source/JavaScriptCore/inspector/agents/InspectorScriptProfilerAgent.cpp new file mode 100644 index 000000000..c266f4309 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/InspectorScriptProfilerAgent.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (C) 2015-2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InspectorScriptProfilerAgent.h" + +#include "DeferGC.h" +#include "HeapInlines.h" +#include "InspectorEnvironment.h" +#include "SamplingProfiler.h" +#include <wtf/Stopwatch.h> + +using namespace JSC; + +namespace Inspector { + +InspectorScriptProfilerAgent::InspectorScriptProfilerAgent(AgentContext& context) + : InspectorAgentBase(ASCIILiteral("ScriptProfiler")) + , m_frontendDispatcher(std::make_unique<ScriptProfilerFrontendDispatcher>(context.frontendRouter)) + , m_backendDispatcher(ScriptProfilerBackendDispatcher::create(context.backendDispatcher, this)) + , m_environment(context.environment) +{ +} + +InspectorScriptProfilerAgent::~InspectorScriptProfilerAgent() +{ +} + +void InspectorScriptProfilerAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) +{ +} + +void InspectorScriptProfilerAgent::willDestroyFrontendAndBackend(DisconnectReason) +{ + // Stop tracking without sending results. + if (m_tracking) { + m_tracking = false; + m_activeEvaluateScript = false; + m_environment.scriptDebugServer().setProfilingClient(nullptr); + + // Stop sampling without processing the samples. + stopSamplingWhenDisconnecting(); + } +} + +void InspectorScriptProfilerAgent::startTracking(ErrorString&, const bool* const includeSamples) +{ + if (m_tracking) + return; + + m_tracking = true; + +#if ENABLE(SAMPLING_PROFILER) + if (includeSamples && *includeSamples) { + VM& vm = m_environment.scriptDebugServer().vm(); + SamplingProfiler& samplingProfiler = vm.ensureSamplingProfiler(m_environment.executionStopwatch()); + + LockHolder locker(samplingProfiler.getLock()); + samplingProfiler.setStopWatch(locker, m_environment.executionStopwatch()); + samplingProfiler.noticeCurrentThreadAsJSCExecutionThread(locker); + samplingProfiler.start(locker); + m_enabledSamplingProfiler = true; + } +#else + UNUSED_PARAM(includeSamples); +#endif // ENABLE(SAMPLING_PROFILER) + + m_environment.scriptDebugServer().setProfilingClient(this); + + m_frontendDispatcher->trackingStart(m_environment.executionStopwatch()->elapsedTime()); +} + +void InspectorScriptProfilerAgent::stopTracking(ErrorString&) +{ + if (!m_tracking) + return; + + m_tracking = false; + m_activeEvaluateScript = false; + + m_environment.scriptDebugServer().setProfilingClient(nullptr); + + trackingComplete(); +} + +bool InspectorScriptProfilerAgent::isAlreadyProfiling() const +{ + return m_activeEvaluateScript; +} + +double InspectorScriptProfilerAgent::willEvaluateScript() +{ + m_activeEvaluateScript = true; + +#if ENABLE(SAMPLING_PROFILER) + if (m_enabledSamplingProfiler) { + SamplingProfiler* samplingProfiler = m_environment.scriptDebugServer().vm().samplingProfiler(); + RELEASE_ASSERT(samplingProfiler); + samplingProfiler->noticeCurrentThreadAsJSCExecutionThread(); + } +#endif + + return m_environment.executionStopwatch()->elapsedTime(); +} + +void InspectorScriptProfilerAgent::didEvaluateScript(double startTime, ProfilingReason reason) +{ + m_activeEvaluateScript = false; + + double endTime = m_environment.executionStopwatch()->elapsedTime(); + + addEvent(startTime, endTime, reason); +} + +static Inspector::Protocol::ScriptProfiler::EventType toProtocol(ProfilingReason reason) +{ + switch (reason) { + case ProfilingReason::API: + return Inspector::Protocol::ScriptProfiler::EventType::API; + case ProfilingReason::Microtask: + return Inspector::Protocol::ScriptProfiler::EventType::Microtask; + case ProfilingReason::Other: + return Inspector::Protocol::ScriptProfiler::EventType::Other; + } + + ASSERT_NOT_REACHED(); + return Inspector::Protocol::ScriptProfiler::EventType::Other; +} + +void InspectorScriptProfilerAgent::addEvent(double startTime, double endTime, ProfilingReason reason) +{ + ASSERT(endTime >= startTime); + + auto event = Inspector::Protocol::ScriptProfiler::Event::create() + .setStartTime(startTime) + .setEndTime(endTime) + .setType(toProtocol(reason)) + .release(); + + m_frontendDispatcher->trackingUpdate(WTFMove(event)); +} + +#if ENABLE(SAMPLING_PROFILER) +static Ref<Protocol::ScriptProfiler::Samples> buildSamples(VM& vm, Vector<SamplingProfiler::StackTrace>&& samplingProfilerStackTraces) +{ + Ref<Protocol::Array<Protocol::ScriptProfiler::StackTrace>> stackTraces = Protocol::Array<Protocol::ScriptProfiler::StackTrace>::create(); + for (SamplingProfiler::StackTrace& stackTrace : samplingProfilerStackTraces) { + Ref<Protocol::Array<Protocol::ScriptProfiler::StackFrame>> frames = Protocol::Array<Protocol::ScriptProfiler::StackFrame>::create(); + for (SamplingProfiler::StackFrame& stackFrame : stackTrace.frames) { + Ref<Protocol::ScriptProfiler::StackFrame> frame = Protocol::ScriptProfiler::StackFrame::create() + .setSourceID(String::number(stackFrame.sourceID())) + .setName(stackFrame.displayName(vm)) + .setLine(stackFrame.functionStartLine()) + .setColumn(stackFrame.functionStartColumn()) + .setUrl(stackFrame.url()) + .release(); + + if (stackFrame.hasExpressionInfo()) { + Ref<Protocol::ScriptProfiler::ExpressionLocation> expressionLocation = Protocol::ScriptProfiler::ExpressionLocation::create() + .setLine(stackFrame.lineNumber()) + .setColumn(stackFrame.columnNumber()) + .release(); + frame->setExpressionLocation(WTFMove(expressionLocation)); + } + + frames->addItem(WTFMove(frame)); + } + Ref<Protocol::ScriptProfiler::StackTrace> inspectorStackTrace = Protocol::ScriptProfiler::StackTrace::create() + .setTimestamp(stackTrace.timestamp) + .setStackFrames(WTFMove(frames)) + .release(); + stackTraces->addItem(WTFMove(inspectorStackTrace)); + } + + return Protocol::ScriptProfiler::Samples::create() + .setStackTraces(WTFMove(stackTraces)) + .release(); +} +#endif // ENABLE(SAMPLING_PROFILER) + +void InspectorScriptProfilerAgent::trackingComplete() +{ +#if ENABLE(SAMPLING_PROFILER) + if (m_enabledSamplingProfiler) { + VM& vm = m_environment.scriptDebugServer().vm(); + JSLockHolder lock(vm); + DeferGC deferGC(vm.heap); + SamplingProfiler* samplingProfiler = vm.samplingProfiler(); + RELEASE_ASSERT(samplingProfiler); + + LockHolder locker(samplingProfiler->getLock()); + samplingProfiler->pause(locker); + Vector<SamplingProfiler::StackTrace> stackTraces = samplingProfiler->releaseStackTraces(locker); + locker.unlockEarly(); + + Ref<Protocol::ScriptProfiler::Samples> samples = buildSamples(vm, WTFMove(stackTraces)); + + m_enabledSamplingProfiler = false; + + m_frontendDispatcher->trackingComplete(WTFMove(samples)); + } else + m_frontendDispatcher->trackingComplete(nullptr); +#else + m_frontendDispatcher->trackingComplete(nullptr); +#endif // ENABLE(SAMPLING_PROFILER) +} + +void InspectorScriptProfilerAgent::stopSamplingWhenDisconnecting() +{ +#if ENABLE(SAMPLING_PROFILER) + if (!m_enabledSamplingProfiler) + return; + + VM& vm = m_environment.scriptDebugServer().vm(); + JSLockHolder lock(vm); + SamplingProfiler* samplingProfiler = vm.samplingProfiler(); + RELEASE_ASSERT(samplingProfiler); + LockHolder locker(samplingProfiler->getLock()); + samplingProfiler->pause(locker); + samplingProfiler->clearData(locker); + + m_enabledSamplingProfiler = false; +#endif +} + +void InspectorScriptProfilerAgent::programmaticCaptureStarted() +{ + m_frontendDispatcher->programmaticCaptureStarted(); +} + +void InspectorScriptProfilerAgent::programmaticCaptureStopped() +{ + m_frontendDispatcher->programmaticCaptureStopped(); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/InspectorScriptProfilerAgent.h b/Source/JavaScriptCore/inspector/agents/InspectorScriptProfilerAgent.h new file mode 100644 index 000000000..ca1bb8a61 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/InspectorScriptProfilerAgent.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2015-2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorBackendDispatchers.h" +#include "InspectorFrontendDispatchers.h" +#include "inspector/InspectorAgentBase.h" +#include "inspector/ScriptDebugServer.h" +#include <wtf/Noncopyable.h> + +namespace JSC { +class Profile; +} + +namespace Inspector { + +typedef String ErrorString; + +class JS_EXPORT_PRIVATE InspectorScriptProfilerAgent final : public InspectorAgentBase, public ScriptProfilerBackendDispatcherHandler, public JSC::Debugger::ProfilingClient { + WTF_MAKE_NONCOPYABLE(InspectorScriptProfilerAgent); +public: + InspectorScriptProfilerAgent(AgentContext&); + virtual ~InspectorScriptProfilerAgent(); + + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) override; + void willDestroyFrontendAndBackend(DisconnectReason) override; + + // ScriptProfilerBackendDispatcherHandler + void startTracking(ErrorString&, const bool* const includeSamples) override; + void stopTracking(ErrorString&) override; + + void programmaticCaptureStarted(); + void programmaticCaptureStopped(); + + // Debugger::ProfilingClient + bool isAlreadyProfiling() const override; + double willEvaluateScript() override; + void didEvaluateScript(double, JSC::ProfilingReason) override; + +private: + struct Event { + Event(double start, double end) : startTime(start), endTime(end) { } + double startTime { 0 }; + double endTime { 0 }; + }; + + void addEvent(double startTime, double endTime, JSC::ProfilingReason); + void trackingComplete(); + void stopSamplingWhenDisconnecting(); + + std::unique_ptr<ScriptProfilerFrontendDispatcher> m_frontendDispatcher; + RefPtr<ScriptProfilerBackendDispatcher> m_backendDispatcher; + InspectorEnvironment& m_environment; + bool m_tracking { false }; +#if ENABLE(SAMPLING_PROFILER) + bool m_enabledSamplingProfiler { false }; +#endif + bool m_activeEvaluateScript { false }; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/JSGlobalObjectConsoleAgent.cpp b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectConsoleAgent.cpp new file mode 100644 index 000000000..401162bc2 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectConsoleAgent.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSGlobalObjectConsoleAgent.h" + +namespace Inspector { + +JSGlobalObjectConsoleAgent::JSGlobalObjectConsoleAgent(AgentContext& context, InspectorHeapAgent* heapAgent) + : InspectorConsoleAgent(context, heapAgent) +{ +} + +void JSGlobalObjectConsoleAgent::setMonitoringXHREnabled(ErrorString& errorString, bool) +{ + errorString = ASCIILiteral("Not supported for JavaScript context"); +} + +void JSGlobalObjectConsoleAgent::addInspectedNode(ErrorString& errorString, int) +{ + errorString = ASCIILiteral("Not supported for JavaScript context"); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/JSGlobalObjectConsoleAgent.h b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectConsoleAgent.h new file mode 100644 index 000000000..91dade3d2 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectConsoleAgent.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorConsoleAgent.h" +#include "JSGlobalObjectScriptDebugServer.h" + +namespace Inspector { + +class JSGlobalObjectConsoleAgent final : public InspectorConsoleAgent { + WTF_MAKE_NONCOPYABLE(JSGlobalObjectConsoleAgent); + WTF_MAKE_FAST_ALLOCATED; +public: + JSGlobalObjectConsoleAgent(AgentContext&, InspectorHeapAgent*); + virtual ~JSGlobalObjectConsoleAgent() { } + + // FIXME: XHRs and Nodes only makes sense debugging a Web context. Can this be moved to a different agent? + void setMonitoringXHREnabled(ErrorString&, bool enabled) override; + void addInspectedNode(ErrorString&, int nodeId) override; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/JSGlobalObjectDebuggerAgent.cpp b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectDebuggerAgent.cpp new file mode 100644 index 000000000..19ba13db5 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectDebuggerAgent.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSGlobalObjectDebuggerAgent.h" + +#include "ConsoleMessage.h" +#include "InjectedScriptManager.h" +#include "InspectorConsoleAgent.h" +#include "JSGlobalObject.h" +#include "ScriptArguments.h" +#include "ScriptCallStack.h" +#include "ScriptCallStackFactory.h" + +using namespace JSC; + +namespace Inspector { + +JSGlobalObjectDebuggerAgent::JSGlobalObjectDebuggerAgent(JSAgentContext& context, InspectorConsoleAgent* consoleAgent) + : InspectorDebuggerAgent(context) + , m_consoleAgent(consoleAgent) +{ +} + +InjectedScript JSGlobalObjectDebuggerAgent::injectedScriptForEval(ErrorString& error, const int* executionContextId) +{ + if (executionContextId) { + error = ASCIILiteral("Execution context id is not supported for JSContext inspection as there is only one execution context."); + return InjectedScript(); + } + + ExecState* exec = static_cast<JSGlobalObjectScriptDebugServer&>(scriptDebugServer()).globalObject().globalExec(); + return injectedScriptManager().injectedScriptFor(exec); +} + +void JSGlobalObjectDebuggerAgent::breakpointActionLog(JSC::ExecState& state, const String& message) +{ + m_consoleAgent->addMessageToConsole(std::make_unique<ConsoleMessage>(MessageSource::JS, MessageType::Log, MessageLevel::Log, message, createScriptCallStack(&state, ScriptCallStack::maxCallStackSizeToCapture), 0)); +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/JSGlobalObjectDebuggerAgent.h b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectDebuggerAgent.h new file mode 100644 index 000000000..5476f55ce --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectDebuggerAgent.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorDebuggerAgent.h" +#include "JSGlobalObjectScriptDebugServer.h" + +namespace Inspector { + +class InspectorConsoleAgent; + +class JSGlobalObjectDebuggerAgent final : public InspectorDebuggerAgent { + WTF_MAKE_NONCOPYABLE(JSGlobalObjectDebuggerAgent); + WTF_MAKE_FAST_ALLOCATED; +public: + JSGlobalObjectDebuggerAgent(JSAgentContext&, InspectorConsoleAgent*); + virtual ~JSGlobalObjectDebuggerAgent() { } + + InjectedScript injectedScriptForEval(ErrorString&, const int* executionContextId) override; + + void breakpointActionLog(JSC::ExecState&, const String&) final; + + // NOTE: JavaScript inspector does not yet need to mute a console because no messages + // are sent to the console outside of the API boundary or console object. + void muteConsole() final { } + void unmuteConsole() final { } + +private: + InspectorConsoleAgent* m_consoleAgent { nullptr }; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/JSGlobalObjectRuntimeAgent.cpp b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectRuntimeAgent.cpp new file mode 100644 index 000000000..b748eeb0a --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectRuntimeAgent.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSGlobalObjectRuntimeAgent.h" + +#include "InjectedScript.h" +#include "InjectedScriptManager.h" +#include "JSGlobalObject.h" + +using namespace JSC; + +namespace Inspector { + +JSGlobalObjectRuntimeAgent::JSGlobalObjectRuntimeAgent(JSAgentContext& context) + : InspectorRuntimeAgent(context) + , m_frontendDispatcher(std::make_unique<RuntimeFrontendDispatcher>(context.frontendRouter)) + , m_backendDispatcher(RuntimeBackendDispatcher::create(context.backendDispatcher, this)) + , m_globalObject(context.inspectedGlobalObject) +{ +} + +void JSGlobalObjectRuntimeAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) +{ +} + +InjectedScript JSGlobalObjectRuntimeAgent::injectedScriptForEval(ErrorString& errorString, const int* executionContextId) +{ + ASSERT_UNUSED(executionContextId, !executionContextId); + + JSC::ExecState* scriptState = m_globalObject.globalExec(); + InjectedScript injectedScript = injectedScriptManager().injectedScriptFor(scriptState); + if (injectedScript.hasNoValue()) + errorString = ASCIILiteral("Internal error: main world execution context not found."); + + return injectedScript; +} + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/agents/JSGlobalObjectRuntimeAgent.h b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectRuntimeAgent.h new file mode 100644 index 000000000..06809ad28 --- /dev/null +++ b/Source/JavaScriptCore/inspector/agents/JSGlobalObjectRuntimeAgent.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "InspectorRuntimeAgent.h" + +namespace JSC { +class JSGlobalObject; +} + +namespace Inspector { + +class JSGlobalObjectRuntimeAgent final : public InspectorRuntimeAgent { +public: + JSGlobalObjectRuntimeAgent(JSAgentContext&); + + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) override; + + InjectedScript injectedScriptForEval(ErrorString&, const int* executionContextId) override; + + // NOTE: JavaScript inspector does not yet need to mute a console because no messages + // are sent to the console outside of the API boundary or console object. + void muteConsole() override { } + void unmuteConsole() override { } + +private: + std::unique_ptr<RuntimeFrontendDispatcher> m_frontendDispatcher; + RefPtr<RuntimeBackendDispatcher> m_backendDispatcher; + JSC::JSGlobalObject& m_globalObject; +}; + +} // namespace Inspector diff --git a/Source/JavaScriptCore/inspector/augmentable/AlternateDispatchableAgent.h b/Source/JavaScriptCore/inspector/augmentable/AlternateDispatchableAgent.h new file mode 100644 index 000000000..cd3f3c326 --- /dev/null +++ b/Source/JavaScriptCore/inspector/augmentable/AlternateDispatchableAgent.h @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "InspectorAlternateBackendDispatchers.h" +#include "InspectorBackendDispatchers.h" +#include <JavaScriptCore/InspectorAgentBase.h> +#include <wtf/Forward.h> + +namespace Inspector { + +template<typename TBackendDispatcher, typename TAlternateDispatcher> +class AlternateDispatchableAgent final : public InspectorAgentBase { + WTF_MAKE_FAST_ALLOCATED; +public: + AlternateDispatchableAgent(const String& domainName, AugmentableInspectorController& controller, std::unique_ptr<TAlternateDispatcher> alternateDispatcher) + : InspectorAgentBase(domainName) + , m_alternateDispatcher(WTFMove(alternateDispatcher)) + , m_backendDispatcher(TBackendDispatcher::create(controller.backendDispatcher(), nullptr)) + { + m_backendDispatcher->setAlternateDispatcher(m_alternateDispatcher.get()); + m_alternateDispatcher->setBackendDispatcher(&controller.backendDispatcher()); + } + + virtual ~AlternateDispatchableAgent() + { + m_alternateDispatcher->setBackendDispatcher(nullptr); + } + + void didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*) override + { + } + + void willDestroyFrontendAndBackend(DisconnectReason) override + { + } + +private: + std::unique_ptr<TAlternateDispatcher> m_alternateDispatcher; + RefPtr<TBackendDispatcher> m_backendDispatcher; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) diff --git a/Source/JavaScriptCore/inspector/augmentable/AugmentableInspectorController.h b/Source/JavaScriptCore/inspector/augmentable/AugmentableInspectorController.h new file mode 100644 index 000000000..7025f2355 --- /dev/null +++ b/Source/JavaScriptCore/inspector/augmentable/AugmentableInspectorController.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include <JavaScriptCore/AugmentableInspectorControllerClient.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> +#include <JavaScriptCore/InspectorFrontendRouter.h> + +namespace Inspector { + +class InspectorAgentBase; + +class AugmentableInspectorController { +public: + virtual ~AugmentableInspectorController() { } + + virtual AugmentableInspectorControllerClient* augmentableInspectorControllerClient() const = 0; + virtual void setAugmentableInspectorControllerClient(AugmentableInspectorControllerClient*) = 0; + + virtual const FrontendRouter& frontendRouter() const = 0; + virtual BackendDispatcher& backendDispatcher() = 0; + virtual void appendExtraAgent(std::unique_ptr<InspectorAgentBase>) = 0; + + bool connected() const { return frontendRouter().hasFrontends(); } +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) diff --git a/Source/JavaScriptCore/inspector/augmentable/AugmentableInspectorControllerClient.h b/Source/JavaScriptCore/inspector/augmentable/AugmentableInspectorControllerClient.h new file mode 100644 index 000000000..7124fca5b --- /dev/null +++ b/Source/JavaScriptCore/inspector/augmentable/AugmentableInspectorControllerClient.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2014 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +namespace Inspector { + +class AugmentableInspectorControllerClient { +public: + virtual ~AugmentableInspectorControllerClient() { } + virtual void inspectorControllerDestroyed() = 0; + virtual void inspectorConnected() = 0; + virtual void inspectorDisconnected() = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) diff --git a/Source/JavaScriptCore/inspector/protocol/ApplicationCache.json b/Source/JavaScriptCore/inspector/protocol/ApplicationCache.json new file mode 100644 index 000000000..86a984a12 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/ApplicationCache.json @@ -0,0 +1,87 @@ +{ + "domain": "ApplicationCache", + "availability": "web", + "types": [ + { + "id": "ApplicationCacheResource", + "type": "object", + "description": "Detailed application cache resource information.", + "properties": [ + { "name": "url", "type": "string", "description": "Resource url." }, + { "name": "size", "type": "integer", "description": "Resource size." }, + { "name": "type", "type": "string", "description": "Resource type." } + ] + }, + { + "id": "ApplicationCache", + "type": "object", + "description": "Detailed application cache information.", + "properties": [ + { "name": "manifestURL", "type": "string", "description": "Manifest URL." }, + { "name": "size", "type": "number", "description": "Application cache size." }, + { "name": "creationTime", "type": "number", "description": "Application cache creation time." }, + { "name": "updateTime", "type": "number", "description": "Application cache update time." }, + { "name": "resources", "type": "array", "items": { "$ref": "ApplicationCacheResource" }, "description": "Application cache resources." } + ] + }, + { + "id": "FrameWithManifest", + "type": "object", + "description": "Frame identifier - manifest URL pair.", + "properties": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Frame identifier." }, + { "name": "manifestURL", "type": "string", "description": "Manifest URL." }, + { "name": "status", "type": "integer", "description": "Application cache status." } + ] + } + ], + "commands": [ + { + "name": "getFramesWithManifests", + "returns": [ + { "name": "frameIds", "type": "array", "items": { "$ref": "FrameWithManifest" }, "description": "Array of frame identifiers with manifest urls for each frame containing a document associated with some application cache." } + ], + "description": "Returns array of frame identifiers with manifest urls for each frame containing a document associated with some application cache." + }, + { + "name": "enable", + "description": "Enables application cache domain notifications." + }, + { + "name": "getManifestForFrame", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Identifier of the frame containing document whose manifest is retrieved." } + ], + "returns": [ + { "name": "manifestURL", "type": "string", "description": "Manifest URL for document in the given frame." } + ], + "description": "Returns manifest URL for document in the given frame." + }, + { + "name": "getApplicationCacheForFrame", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Identifier of the frame containing document whose application cache is retrieved." } + ], + "returns": [ + { "name": "applicationCache", "$ref": "ApplicationCache", "description": "Relevant application cache data for the document in given frame." } + ], + "description": "Returns relevant application cache data for the document in given frame." + } + ], + "events": [ + { + "name": "applicationCacheStatusUpdated", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Identifier of the frame containing document whose application cache updated status." }, + { "name": "manifestURL", "type": "string", "description": "Manifest URL." }, + { "name": "status", "type": "integer", "description": "Updated application cache status." } + ] + }, + { + "name": "networkStateUpdated", + "parameters": [ + { "name": "isNowOnline", "type": "boolean" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/CSS.json b/Source/JavaScriptCore/inspector/protocol/CSS.json new file mode 100644 index 000000000..7abbe227f --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/CSS.json @@ -0,0 +1,457 @@ +{ + "domain": "CSS", + "description": "This domain exposes CSS read/write operations. All CSS objects, like stylesheets, rules, and styles, have an associated <code>id</code> used in subsequent operations on the related object. Each object type has a specific <code>id</code> structure, and those are not interchangeable between objects of different kinds. CSS objects can be loaded using the <code>get*ForNode()</code> calls (which accept a DOM node id). Alternatively, a client can discover all the existing stylesheets with the <code>getAllStyleSheets()</code> method and subsequently load the required stylesheet contents using the <code>getStyleSheet[Text]()</code> methods.", + "availability": "web", + "types": [ + { + "id": "StyleSheetId", + "type": "string" + }, + { + "id": "CSSStyleId", + "type": "object", + "properties": [ + { "name": "styleSheetId", "$ref": "StyleSheetId", "description": "Enclosing stylesheet identifier." }, + { "name": "ordinal", "type": "integer", "description": "The style ordinal within the stylesheet." } + ], + "description": "This object identifies a CSS style in a unique way." + }, + { + "id": "StyleSheetOrigin", + "type": "string", + "enum": ["user", "user-agent", "inspector", "regular"], + "description": "Stylesheet type: \"user\" for user stylesheets, \"user-agent\" for user-agent stylesheets, \"inspector\" for stylesheets created by the inspector (i.e. those holding the \"via inspector\" rules), \"regular\" for regular stylesheets." + }, + { + "id": "CSSRuleId", + "type": "object", + "properties": [ + { "name": "styleSheetId", "$ref": "StyleSheetId", "description": "Enclosing stylesheet identifier." }, + { "name": "ordinal", "type": "integer", "description": "The rule ordinal within the stylesheet." } + ], + "description": "This object identifies a CSS rule in a unique way." + }, + { + "id": "PseudoIdMatches", + "type": "object", + "properties": [ + { "name": "pseudoId", "type": "integer", "description": "Pseudo style identifier (see <code>enum PseudoId</code> in <code>RenderStyleConstants.h</code>)."}, + { "name": "matches", "type": "array", "items": { "$ref": "RuleMatch" }, "description": "Matches of CSS rules applicable to the pseudo style."} + ], + "description": "CSS rule collection for a single pseudo style." + }, + { + "id": "InheritedStyleEntry", + "type": "object", + "properties": [ + { "name": "inlineStyle", "$ref": "CSSStyle", "optional": true, "description": "The ancestor node's inline style, if any, in the style inheritance chain." }, + { "name": "matchedCSSRules", "type": "array", "items": { "$ref": "RuleMatch" }, "description": "Matches of CSS rules matching the ancestor node in the style inheritance chain." } + ], + "description": "CSS rule collection for a single pseudo style." + }, + { + "id": "RuleMatch", + "type": "object", + "properties": [ + { "name": "rule", "$ref": "CSSRule", "description": "CSS rule in the match." }, + { "name": "matchingSelectors", "type": "array", "items": { "type": "integer" }, "description": "Matching selector indices in the rule's selectorList selectors (0-based)." } + ], + "description": "Match data for a CSS rule." + }, + { + "id": "CSSSelector", + "type": "object", + "properties": [ + { "name": "text", "type": "string", "description": "Canonicalized selector text." }, + { "name": "specificity", "optional": true, "type": "array", "items": { "type": "integer" }, "description": "Specificity (a, b, c) tuple. Included if the selector is sent in response to CSS.getMatchedStylesForNode which provides a context element." }, + { "name": "dynamic", "optional": true, "type": "boolean", "description": "Whether or not the specificity can be dynamic. Included if the selector is sent in response to CSS.getMatchedStylesForNode which provides a context element." } + ], + "description": "CSS selector." + }, + { + "id": "SelectorList", + "type": "object", + "properties": [ + { "name": "selectors", "type": "array", "items": { "$ref": "CSSSelector" }, "description": "Selectors in the list." }, + { "name": "text", "type": "string", "description": "Rule selector text." }, + { "name": "range", "$ref": "SourceRange", "optional": true, "description": "Rule selector range in the underlying resource (if available)." } + ], + "description": "Selector list data." + }, + { + "id": "CSSStyleAttribute", + "type": "object", + "properties": [ + { "name": "name", "type": "string", "description": "DOM attribute name (e.g. \"width\")."}, + { "name": "style", "$ref": "CSSStyle", "description": "CSS style generated by the respective DOM attribute."} + ], + "description": "CSS style information for a DOM style attribute." + }, + { + "id": "CSSStyleSheetHeader", + "type": "object", + "properties": [ + { "name": "styleSheetId", "$ref": "StyleSheetId", "description": "The stylesheet identifier."}, + { "name": "frameId", "$ref": "Network.FrameId", "description": "Owner frame identifier."}, + { "name": "sourceURL", "type": "string", "description": "Stylesheet resource URL."}, + { "name": "origin", "$ref": "StyleSheetOrigin", "description": "Stylesheet origin."}, + { "name": "title", "type": "string", "description": "Stylesheet title."}, + { "name": "disabled", "type": "boolean", "description": "Denotes whether the stylesheet is disabled."}, + { "name": "isInline", "type": "boolean", "description": "Whether this stylesheet is a <style> tag created by the parser. This is not set for document.written <style> tags." }, + { "name": "startLine", "type": "number", "description": "Line offset of the stylesheet within the resource (zero based)." }, + { "name": "startColumn", "type": "number", "description": "Column offset of the stylesheet within the resource (zero based)." } + ], + "description": "CSS stylesheet metainformation." + }, + { + "id": "CSSStyleSheetBody", + "type": "object", + "properties": [ + { "name": "styleSheetId", "$ref": "StyleSheetId", "description": "The stylesheet identifier."}, + { "name": "rules", "type": "array", "items": { "$ref": "CSSRule" }, "description": "Stylesheet resource URL."}, + { "name": "text", "type": "string", "optional": true, "description": "Stylesheet resource contents (if available)."} + ], + "description": "CSS stylesheet contents." + }, + { + "id": "CSSRule", + "type": "object", + "properties": [ + { "name": "ruleId", "$ref": "CSSRuleId", "optional": true, "description": "The CSS rule identifier (absent for user agent stylesheet and user-specified stylesheet rules)."}, + { "name": "selectorList", "$ref": "SelectorList", "description": "Rule selector data." }, + { "name": "sourceURL", "type": "string", "optional": true, "description": "Parent stylesheet resource URL (for regular rules)."}, + { "name": "sourceLine", "type": "integer", "description": "Line ordinal of the rule selector start character in the resource."}, + { "name": "origin", "$ref": "StyleSheetOrigin", "description": "Parent stylesheet's origin."}, + { "name": "style", "$ref": "CSSStyle", "description": "Associated style declaration." }, + { "name": "media", "type": "array", "items": { "$ref": "CSSMedia" }, "optional": true, "description": "Media list array (for rules involving media queries). The array enumerates media queries starting with the innermost one, going outwards." } + ], + "description": "CSS rule representation." + }, + { + "id": "SourceRange", + "type": "object", + "properties": [ + { "name": "startLine", "type": "integer", "description": "Start line of range." }, + { "name": "startColumn", "type": "integer", "description": "Start column of range (inclusive)." }, + { "name": "endLine", "type": "integer", "description": "End line of range" }, + { "name": "endColumn", "type": "integer", "description": "End column of range (exclusive)." } + ], + "description": "Text range within a resource." + }, + { + "id": "ShorthandEntry", + "type": "object", + "properties": [ + { "name": "name", "type": "string", "description": "Shorthand name." }, + { "name": "value", "type": "string", "description": "Shorthand value." } + ] + }, + { + "id": "CSSPropertyInfo", + "type": "object", + "properties": [ + { "name": "name", "type": "string", "description": "Property name." }, + { "name": "longhands", "type": "array", "optional": true, "items": { "type": "string" }, "description": "Longhand property names." }, + { "name": "values", "type": "array", "optional": true, "items": { "type": "string" }, "description": "Supported values for this property." } + ] + }, + { + "id": "CSSComputedStyleProperty", + "type": "object", + "properties": [ + { "name": "name", "type": "string", "description": "Computed style property name." }, + { "name": "value", "type": "string", "description": "Computed style property value." } + ] + }, + { + "id": "CSSStyle", + "type": "object", + "properties": [ + { "name": "styleId", "$ref": "CSSStyleId", "optional": true, "description": "The CSS style identifier (absent for attribute styles)." }, + { "name": "cssProperties", "type": "array", "items": { "$ref": "CSSProperty" }, "description": "CSS properties in the style." }, + { "name": "shorthandEntries", "type": "array", "items": { "$ref": "ShorthandEntry" }, "description": "Computed values for all shorthands found in the style." }, + { "name": "cssText", "type": "string", "optional": true, "description": "Style declaration text (if available)." }, + { "name": "range", "$ref": "SourceRange", "optional": true, "description": "Style declaration range in the enclosing stylesheet (if available)." }, + { "name": "width", "type": "string", "optional": true, "description": "The effective \"width\" property value from this style." }, + { "name": "height", "type": "string", "optional": true, "description": "The effective \"height\" property value from this style." } + ], + "description": "CSS style representation." + }, + { + "id": "CSSPropertyStatus", + "type": "string", + "enum": ["active", "inactive", "disabled", "style"], + "description": "The property status: \"active\" if the property is effective in the style, \"inactive\" if the property is overridden by a same-named property in this style later on, \"disabled\" if the property is disabled by the user, \"style\" (implied if absent) if the property is reported by the browser rather than by the CSS source parser." + }, + { + "id": "CSSProperty", + "type": "object", + "properties": [ + { "name": "name", "type": "string", "description": "The property name." }, + { "name": "value", "type": "string", "description": "The property value." }, + { "name": "priority", "type": "string", "optional": true, "description": "The property priority (implies \"\" if absent)." }, + { "name": "implicit", "type": "boolean", "optional": true, "description": "Whether the property is implicit (implies <code>false</code> if absent)." }, + { "name": "text", "type": "string", "optional": true, "description": "The full property text as specified in the style." }, + { "name": "parsedOk", "type": "boolean", "optional": true, "description": "Whether the property is understood by the browser (implies <code>true</code> if absent)." }, + { "name": "status", "$ref": "CSSPropertyStatus", "optional": true, "description": "Whether the property is active or disabled." }, + { "name": "range", "$ref": "SourceRange", "optional": true, "description": "The entire property range in the enclosing style declaration (if available)." } + ], + "description": "CSS style effective visual dimensions and source offsets." + }, + { + "id": "CSSMedia", + "type": "object", + "properties": [ + { "name": "text", "type": "string", "description": "Media query text." }, + { "name": "source", "type": "string", "enum": ["mediaRule", "importRule", "linkedSheet", "inlineSheet"], "description": "Source of the media query: \"mediaRule\" if specified by a @media rule, \"importRule\" if specified by an @import rule, \"linkedSheet\" if specified by a \"media\" attribute in a linked stylesheet's LINK tag, \"inlineSheet\" if specified by a \"media\" attribute in an inline stylesheet's STYLE tag." }, + { "name": "sourceURL", "type": "string", "optional": true, "description": "URL of the document containing the media query description." }, + { "name": "sourceLine", "type": "integer", "optional": true, "description": "Line in the document containing the media query (not defined for the \"stylesheet\" source)." } + ], + "description": "CSS media query descriptor." + }, + { + "id": "Region", + "type": "object", + "properties": [ + { "name": "regionOverset", "type": "string", "enum": ["overset", "fit", "empty"], "description": "The \"overset\" attribute of a Named Flow." }, + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "The corresponding DOM node id." } + ], + "description": "This object represents a region that flows from a Named Flow." + }, + { + "id": "NamedFlow", + "type": "object", + "properties": [ + { "name": "documentNodeId", "$ref": "DOM.NodeId", "description": "The document node id." }, + { "name": "name", "type": "string", "description": "Named Flow identifier." }, + { "name": "overset", "type": "boolean", "description": "The \"overset\" attribute of a Named Flow." }, + { "name": "content", "type": "array", "items": { "$ref": "DOM.NodeId" }, "description": "An array of nodes that flow into the Named Flow." }, + { "name": "regions", "type": "array", "items": { "$ref": "Region" }, "description": "An array of regions associated with the Named Flow." } + ], + "description": "This object represents a Named Flow." + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables the CSS agent for the given page. Clients should not assume that the CSS agent has been enabled until the result of this command is received." + }, + { + "name": "disable", + "description": "Disables the CSS agent for the given page." + }, + { + "name": "getMatchedStylesForNode", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId" }, + { "name": "includePseudo", "type": "boolean", "optional": true, "description": "Whether to include pseudo styles (default: true)." }, + { "name": "includeInherited", "type": "boolean", "optional": true, "description": "Whether to include inherited styles (default: true)." } + ], + "returns": [ + { "name": "matchedCSSRules", "type": "array", "items": { "$ref": "RuleMatch" }, "optional": true, "description": "CSS rules matching this node, from all applicable stylesheets." }, + { "name": "pseudoElements", "type": "array", "items": { "$ref": "PseudoIdMatches" }, "optional": true, "description": "Pseudo style matches for this node." }, + { "name": "inherited", "type": "array", "items": { "$ref": "InheritedStyleEntry" }, "optional": true, "description": "A chain of inherited styles (from the immediate node parent up to the DOM tree root)." } + ], + "description": "Returns requested styles for a DOM node identified by <code>nodeId</code>." + }, + { + "name": "getInlineStylesForNode", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId" } + ], + "returns": [ + { "name": "inlineStyle", "$ref": "CSSStyle", "optional": true, "description": "Inline style for the specified DOM node." }, + { "name": "attributesStyle", "$ref": "CSSStyle", "optional": true, "description": "Attribute-defined element style (e.g. resulting from \"width=20 height=100%\")."} + ], + "description": "Returns the styles defined inline (explicitly in the \"style\" attribute and implicitly, using DOM attributes) for a DOM node identified by <code>nodeId</code>." + }, + { + "name": "getComputedStyleForNode", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId" } + ], + "returns": [ + { "name": "computedStyle", "type": "array", "items": { "$ref": "CSSComputedStyleProperty" }, "description": "Computed style for the specified DOM node." } + ], + "description": "Returns the computed style for a DOM node identified by <code>nodeId</code>." + }, + { + "name": "getAllStyleSheets", + "returns": [ + { "name": "headers", "type": "array", "items": { "$ref": "CSSStyleSheetHeader" }, "description": "Descriptor entries for all available stylesheets." } + ], + "description": "Returns metainfo entries for all known stylesheets." + }, + { + "name": "getStyleSheet", + "parameters": [ + { "name": "styleSheetId", "$ref": "StyleSheetId" } + ], + "returns": [ + { "name": "styleSheet", "$ref": "CSSStyleSheetBody", "description": "Stylesheet contents for the specified <code>styleSheetId</code>." } + ], + "description": "Returns stylesheet data for the specified <code>styleSheetId</code>." + }, + { + "name": "getStyleSheetText", + "parameters": [ + { "name": "styleSheetId", "$ref": "StyleSheetId" } + ], + "returns": [ + { "name": "text", "type": "string", "description": "The stylesheet text." } + ], + "description": "Returns the current textual content and the URL for a stylesheet." + }, + { + "name": "setStyleSheetText", + "parameters": [ + { "name": "styleSheetId", "$ref": "StyleSheetId" }, + { "name": "text", "type": "string" } + ], + "description": "Sets the new stylesheet text, thereby invalidating all existing <code>CSSStyleId</code>'s and <code>CSSRuleId</code>'s contained by this stylesheet." + }, + { + "name": "setStyleText", + "parameters": [ + { "name": "styleId", "$ref": "CSSStyleId" }, + { "name": "text", "type": "string" } + ], + "returns": [ + { "name": "style", "$ref": "CSSStyle", "description": "The resulting style after the text modification." } + ], + "description": "Sets the new <code>text</code> for the respective style." + }, + { + "name": "setRuleSelector", + "parameters": [ + { "name": "ruleId", "$ref": "CSSRuleId" }, + { "name": "selector", "type": "string" } + ], + "returns": [ + { "name": "rule", "$ref": "CSSRule", "description": "The resulting rule after the selector modification." } + ], + "description": "Modifies the rule selector." + }, + { + "name": "createStyleSheet", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Identifier of the frame where the new \"inspector\" stylesheet should be created." } + ], + "returns": [ + { "name": "styleSheetId", "$ref": "StyleSheetId", "description": "Identifier of the created \"inspector\" stylesheet." } + ], + "description": "Creates a new special \"inspector\" stylesheet in the frame with given <code>frameId</code>." + }, + { + "name": "addRule", + "parameters": [ + { "name": "styleSheetId", "$ref": "StyleSheetId" }, + { "name": "selector", "type": "string" } + ], + "returns": [ + { "name": "rule", "$ref": "CSSRule", "description": "The newly created rule." } + ], + "description": "Creates a new empty rule with the given <code>selector</code> in a stylesheet with given <code>styleSheetId</code>." + }, + { + "name": "getSupportedCSSProperties", + "returns": [ + { "name": "cssProperties", "type": "array", "items": { "$ref": "CSSPropertyInfo" }, "description": "Supported property metainfo." } + ], + "description": "Returns all supported CSS property names." + }, + { + "name": "getSupportedSystemFontFamilyNames", + "returns": [ + { "name": "fontFamilyNames", "type": "array", "items": { "type": "string" }, "description": "Supported system font families." } + ], + "description": "Returns all supported system font family names." + }, + { + "name": "forcePseudoState", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "The element id for which to force the pseudo state." }, + { "name": "forcedPseudoClasses", "type": "array", "items": { "type": "string", "enum": ["active", "focus", "hover", "visited"] }, "description": "Element pseudo classes to force when computing the element's style." } + ], + "description": "Ensures that the given node will have specified pseudo-classes whenever its style is computed by the browser." + }, + { + "name": "getNamedFlowCollection", + "parameters": [ + { "name": "documentNodeId", "$ref": "DOM.NodeId", "description": "The document node id for which to get the Named Flow Collection." } + ], + "returns": [ + { "name": "namedFlows", "type": "array", "items": { "$ref": "NamedFlow" }, "description": "An array containing the Named Flows in the document." } + ], + "description": "Returns the Named Flows from the document." + } + ], + "events": [ + { + "name": "mediaQueryResultChanged", + "description": "Fires whenever a MediaQuery result changes (for example, after a browser window has been resized.) The current implementation considers only viewport-dependent media features." + }, + { + "name": "styleSheetChanged", + "parameters": [ + { "name": "styleSheetId", "$ref": "StyleSheetId" } + ], + "description": "Fired whenever a stylesheet is changed as a result of the client operation." + }, + { + "name": "styleSheetAdded", + "parameters": [ + { "name": "header", "$ref": "CSSStyleSheetHeader", "description": "Added stylesheet metainfo." } + ], + "description": "Fired whenever an active document stylesheet is added." + }, + { + "name": "styleSheetRemoved", + "parameters": [ + { "name": "styleSheetId", "$ref": "StyleSheetId", "description": "Identifier of the removed stylesheet." } + ], + "description": "Fired whenever an active document stylesheet is removed." + }, + { + "name": "namedFlowCreated", + "parameters": [ + { "name": "namedFlow", "$ref": "NamedFlow", "description": "The new Named Flow." } + ], + "description": "Fires when a Named Flow is created." + }, + { + "name": "namedFlowRemoved", + "parameters": [ + { "name": "documentNodeId", "$ref": "DOM.NodeId", "description": "The document node id." }, + { "name": "flowName", "type": "string", "description": "Identifier of the removed Named Flow." } + ], + "description": "Fires when a Named Flow is removed: has no associated content nodes and regions." + }, + { + "name": "regionOversetChanged", + "parameters": [ + { "name": "namedFlow", "$ref": "NamedFlow", "description": "The Named Flow containing the regions whose regionOverset values changed." } + ], + "description": "Fires if any of the regionOverset values changed in a Named Flow's region chain." + }, + { + "name": "registeredNamedFlowContentElement", + "parameters": [ + { "name": "documentNodeId", "$ref": "DOM.NodeId", "description": "The document node id." }, + { "name": "flowName", "type": "string", "description": "Named Flow identifier for which the new content element was registered." }, + { "name": "contentNodeId", "$ref": "DOM.NodeId", "description": "The node id of the registered content node." }, + { "name": "nextContentNodeId", "$ref": "DOM.NodeId", "description": "The node id of the element following the registered content node." } + ], + "description": "Fires when a Named Flow's has been registered with a new content node." + }, + { + "name": "unregisteredNamedFlowContentElement", + "parameters": [ + { "name": "documentNodeId", "$ref": "DOM.NodeId", "description": "The document node id." }, + { "name": "flowName", "type": "string", "description": "Named Flow identifier for which the new content element was unregistered." }, + { "name": "contentNodeId", "$ref": "DOM.NodeId", "description": "The node id of the unregistered content node." } + ], + "description": "Fires when a Named Flow's has been registered with a new content node." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Console.json b/Source/JavaScriptCore/inspector/protocol/Console.json new file mode 100644 index 000000000..bc5fa8493 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Console.json @@ -0,0 +1,105 @@ +{ + "domain": "Console", + "description": "Console domain defines methods and events for interaction with the JavaScript console. Console collects messages created by means of the <a href='http://getfirebug.com/wiki/index.php/Console_API'>JavaScript Console API</a>. One needs to enable this domain using <code>enable</code> command in order to start receiving the console messages. Browser collects messages issued while console domain is not enabled as well and reports them using <code>messageAdded</code> notification upon enabling.", + "workerSupported": true, + "types": [ + { + "id": "ConsoleMessage", + "type": "object", + "description": "Console message.", + "properties": [ + { "name": "source", "type": "string", "enum": ["xml", "javascript", "network", "console-api", "storage", "appcache", "rendering", "css", "security", "content-blocker", "other"], "description": "Message source." }, + { "name": "level", "type": "string", "enum": ["log", "info", "warning", "error", "debug"], "description": "Message severity." }, + { "name": "text", "type": "string", "description": "Message text." }, + { "name": "type", "type": "string", "optional": true, "enum": ["log", "dir", "dirxml", "table", "trace", "clear", "startGroup", "startGroupCollapsed", "endGroup", "assert", "timing", "profile", "profileEnd"], "description": "Console message type." }, + { "name": "url", "type": "string", "optional": true, "description": "URL of the message origin." }, + { "name": "line", "type": "integer", "optional": true, "description": "Line number in the resource that generated this message." }, + { "name": "column", "type": "integer", "optional": true, "description": "Column number on the line in the resource that generated this message." }, + { "name": "repeatCount", "type": "integer", "optional": true, "description": "Repeat count for repeated messages." }, + { "name": "parameters", "type": "array", "items": { "$ref": "Runtime.RemoteObject" }, "optional": true, "description": "Message parameters in case of the formatted message." }, + { "name": "stackTrace", "type": "array", "items": { "$ref": "CallFrame" }, "optional": true, "description": "JavaScript stack trace for assertions and error messages." }, + { "name": "networkRequestId", "$ref": "Network.RequestId", "optional": true, "description": "Identifier of the network request associated with this message." } + ] + }, + { + "id": "CallFrame", + "type": "object", + "description": "Stack entry for console errors and assertions.", + "properties": [ + { "name": "functionName", "type": "string", "description": "JavaScript function name." }, + { "name": "url", "type": "string", "description": "JavaScript script name or url." }, + { "name": "scriptId", "$ref": "Debugger.ScriptId", "description": "Script identifier." }, + { "name": "lineNumber", "type": "integer", "description": "JavaScript script line number." }, + { "name": "columnNumber", "type": "integer", "description": "JavaScript script column number." } + ] + }, + { + "id": "StackTrace", + "description": "Call frames for async function calls, console assertions, and error messages.", + "type": "object", + "properties": [ + { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" } }, + { "name": "topCallFrameIsBoundary", "type": "boolean", "optional": true, "description": "Whether the first item in <code>callFrames</code> is the native function that scheduled the asynchronous operation (e.g. setTimeout)." }, + { "name": "truncated", "type": "boolean", "optional": true, "description": "Whether one or more frames have been truncated from the bottom of the stack." }, + { "name": "parentStackTrace", "$ref": "StackTrace", "optional": true, "description": "Parent StackTrace." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables console domain, sends the messages collected so far to the client by means of the <code>messageAdded</code> notification." + }, + { + "name": "disable", + "description": "Disables console domain, prevents further console messages from being reported to the client." + }, + { + "name": "clearMessages", + "description": "Clears console messages collected in the browser." + }, + { + "name": "setMonitoringXHREnabled", + "parameters": [ + { "name": "enabled", "type": "boolean", "description": "Monitoring enabled state." } + ], + "description": "Toggles monitoring of XMLHttpRequest. If <code>true</code>, console will receive messages upon each XHR issued." + }, + { + "name": "addInspectedNode", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "DOM node id to be accessible by means of $0 command line API." } + ], + "description": "Enables console to refer to the node with given id via $0 (see Command Line API for more details)." + } + ], + "events": [ + { + "name": "messageAdded", + "parameters": [ + { "name": "message", "$ref": "ConsoleMessage", "description": "Console message that has been added." } + ], + "description": "Issued when new console message is added." + }, + { + "name": "messageRepeatCountUpdated", + "parameters": [ + { "name": "count", "type": "integer", "description": "New repeat count value." } + ], + "description": "Issued when subsequent message(s) are equal to the previous one(s)." + }, + { + "name": "messagesCleared", + "description": "Issued when console is cleared. This happens either upon <code>clearMessages</code> command or after page navigation." + }, + { + "name": "heapSnapshot", + "description": "Issued from console.takeHeapSnapshot.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { "name": "snapshotData", "$ref": "Heap.HeapSnapshotData", "description": "Snapshot at the end of tracking." }, + { "name": "title", "type": "string", "optional": true, "description": "Optional title provided to console.takeHeapSnapshot." } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/DOM.json b/Source/JavaScriptCore/inspector/protocol/DOM.json new file mode 100644 index 000000000..a246336bd --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/DOM.json @@ -0,0 +1,581 @@ +{ + "domain": "DOM", + "description": "This domain exposes DOM read/write operations. Each DOM Node is represented with its mirror object that has an <code>id</code>. This <code>id</code> can be used to get additional information on the Node, resolve it into the JavaScript object wrapper, etc. It is important that client receives DOM events only for the nodes that are known to the client. Backend keeps track of the nodes that were sent to the client and never sends the same node twice. It is client's responsibility to collect information about the nodes that were sent to the client.<p>Note that <code>iframe</code> owner elements will return corresponding document elements as their child nodes.</p>", + "availability": "web", + "types": [ + { + "id": "NodeId", + "type": "integer", + "description": "Unique DOM node identifier." + }, + { + "id": "BackendNodeId", + "type": "integer", + "description": "Unique DOM node identifier used to reference a node that may not have been pushed to the front-end." + }, + { + "id": "PseudoType", + "type": "string", + "enum": ["before", "after"], + "description": "Pseudo element type." + }, + { + "id": "ShadowRootType", + "type": "string", + "enum": ["user-agent", "open", "closed"], + "description": "Shadow root type." + }, + { + "id": "CustomElementState", + "type": "string", + "enum": ["builtin", "custom", "waiting", "failed"], + "description": "Custom element state." + }, + { + "id": "LiveRegionRelevant", + "type": "string", + "enum": ["additions", "removals", "text"], + "description": "Token values of @aria-relevant attribute." + }, + { + "id": "Node", + "type": "object", + "properties": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Node identifier that is passed into the rest of the DOM messages as the <code>nodeId</code>. Backend will only push node with given <code>id</code> once. It is aware of all requested nodes and will only fire DOM events for nodes known to the client." }, + { "name": "nodeType", "type": "integer", "description": "<code>Node</code>'s nodeType." }, + { "name": "nodeName", "type": "string", "description": "<code>Node</code>'s nodeName." }, + { "name": "localName", "type": "string", "description": "<code>Node</code>'s localName." }, + { "name": "nodeValue", "type": "string", "description": "<code>Node</code>'s nodeValue." }, + { "name": "childNodeCount", "type": "integer", "optional": true, "description": "Child count for <code>Container</code> nodes." }, + { "name": "children", "type": "array", "optional": true, "items": { "$ref": "Node" }, "description": "Child nodes of this node when requested with children." }, + { "name": "attributes", "type": "array", "optional": true, "items": { "type": "string" }, "description": "Attributes of the <code>Element</code> node in the form of flat array <code>[name1, value1, name2, value2]</code>." }, + { "name": "documentURL", "type": "string", "optional": true, "description": "Document URL that <code>Document</code> or <code>FrameOwner</code> node points to." }, + { "name": "baseURL", "type": "string", "optional": true, "description": "Base URL that <code>Document</code> or <code>FrameOwner</code> node uses for URL completion." }, + { "name": "publicId", "type": "string", "optional": true, "description": "<code>DocumentType</code>'s publicId." }, + { "name": "systemId", "type": "string", "optional": true, "description": "<code>DocumentType</code>'s systemId." }, + { "name": "xmlVersion", "type": "string", "optional": true, "description": "<code>Document</code>'s XML version in case of XML documents." }, + { "name": "name", "type": "string", "optional": true, "description": "<code>Attr</code>'s name." }, + { "name": "value", "type": "string", "optional": true, "description": "<code>Attr</code>'s value." }, + { "name": "pseudoType", "$ref": "PseudoType", "optional": true, "description": "Pseudo element type for this node." }, + { "name": "shadowRootType", "$ref": "ShadowRootType", "optional": true, "description": "Shadow root type." }, + { "name": "customElementState", "$ref": "CustomElementState", "optional": true, "description": "Custom element state." }, + { "name": "frameId", "$ref": "Network.FrameId", "optional": true, "description": "Frame ID for frame owner elements." }, + { "name": "contentDocument", "$ref": "Node", "optional": true, "description": "Content document for frame owner elements." }, + { "name": "shadowRoots", "type": "array", "optional": true, "items": { "$ref": "Node" }, "description": "Shadow root list for given element host." }, + { "name": "templateContent", "$ref": "Node", "optional": true, "description": "Content document fragment for template elements" }, + { "name": "pseudoElements", "type": "array", "items": { "$ref": "Node" }, "optional": true, "description": "Pseudo elements associated with this node." }, + { "name": "role", "type": "string", "optional": true, "description": "Computed value for first recognized role token, default role per element, or overridden role." }, + { "name": "contentSecurityPolicyHash", "type": "string", "optional": true, "description": "Computed SHA-256 Content Security Policy hash source for given element." } + ], + "description": "DOM interaction is implemented in terms of mirror objects that represent the actual DOM nodes. DOMNode is a base node mirror type." + }, + { + "id": "EventListener", + "type": "object", + "properties": [ + { "name": "type", "type": "string", "description": "<code>EventListener</code>'s type." }, + { "name": "useCapture", "type": "boolean", "description": "<code>EventListener</code>'s useCapture." }, + { "name": "isAttribute", "type": "boolean", "description": "<code>EventListener</code>'s isAttribute." }, + { "name": "nodeId", "$ref": "NodeId", "description": "Target <code>DOMNode</code> id." }, + { "name": "handlerBody", "type": "string", "description": "Event handler function body." }, + { "name": "location", "$ref": "Debugger.Location", "optional": true, "description": "Handler code location." }, + { "name": "sourceName", "type": "string", "optional": true, "description": "Source script URL." }, + { "name": "handler", "$ref": "Runtime.RemoteObject", "optional": true, "description": "Event handler function value." } + ], + "description": "A structure holding event listener properties." + }, + { + "id": "AccessibilityProperties", + "description": "A structure holding accessibility properties.", + "type": "object", + "properties": [ + { "name": "activeDescendantNodeId", "$ref": "NodeId", "optional": true, "description": "<code>DOMNode</code> id of the accessibility object referenced by aria-activedescendant." }, + { "name": "busy", "type": "boolean", "optional": true, "description": "Value of @aria-busy on current or ancestor node." }, + { "name": "checked", "type": "string", "optional": true, "enum": ["true", "false", "mixed"], "description": "Checked state of certain form controls." }, + { "name": "childNodeIds", "type": "array", "items": { "$ref": "NodeId" }, "optional": true, "description": "Array of <code>DOMNode</code> ids of the accessibility tree children if available." }, + { "name": "controlledNodeIds", "type": "array", "items": { "$ref": "NodeId" }, "optional": true, "description": "Array of <code>DOMNode</code> ids of any nodes referenced via @aria-controls." }, + { "name": "current", "type": "string", "optional": true, "enum": ["true", "false", "page", "step", "location", "date", "time"], "description": "Current item within a container or set of related elements." }, + { "name": "disabled", "type": "boolean", "optional": true, "description": "Disabled state of form controls." }, + { "name": "headingLevel", "type": "number", "optional": true, "description": "Heading level of a heading element." }, + { "name": "hierarchyLevel", "type": "number", "optional": true, "description": "The hierarchical level of an element." }, + { "name": "isPopUpButton", "type": "boolean", "optional": true, "description": "Whether an element is a popup button." }, + { "name": "exists", "type": "boolean", "description": "Indicates whether there is an existing AX object for the DOM node. If this is false, all the other properties will be default values." }, + { "name": "expanded", "type": "boolean", "optional": true, "description": "Expanded state." }, + { "name": "flowedNodeIds", "type": "array", "items": { "$ref": "NodeId" }, "optional": true, "description": "Array of <code>DOMNode</code> ids of any nodes referenced via @aria-flowto." }, + { "name": "focused", "type": "boolean", "optional": true, "description": "Focused state. Only defined on focusable elements." }, + { "name": "ignored", "type": "boolean", "optional": true, "description": "Indicates whether the accessibility of the associated AX object node is ignored, whether heuristically or explicitly." }, + { "name": "ignoredByDefault", "type": "boolean", "optional": true, "description": "State indicating whether the accessibility of the associated AX object node is ignored by default for node type." }, + { "name": "invalid", "type": "string", "optional": true, "enum": ["true", "false", "grammar", "spelling"], "description": "Invalid status of form controls." }, + { "name": "hidden", "type": "boolean", "optional": true, "description": "Hidden state. True if node or an ancestor is hidden via CSS or explicit @aria-hidden, to clarify why the element is ignored." }, + { "name": "label", "type": "string", "description": "Computed label value for the node, sometimes calculated by referencing other nodes." }, + { "name": "liveRegionAtomic", "type": "boolean", "optional": true, "description": "Value of @aria-atomic." }, + { "name": "liveRegionRelevant", "type": "array", "items": { "type": "string" }, "optional": true, "description": "Token value(s) of element's @aria-relevant attribute. Array of string values matching $ref LiveRegionRelevant. FIXME: Enum values blocked by http://webkit.org/b/133711" }, + { "name": "liveRegionStatus", "type": "string", "optional": true, "enum": ["assertive", "polite", "off"], "description": "Value of element's @aria-live attribute." }, + { "name": "mouseEventNodeId", "$ref": "NodeId", "optional": true, "description": "<code>DOMNode</code> id of node or closest ancestor node that has a mousedown, mouseup, or click event handler." }, + { "name": "nodeId", "$ref": "NodeId", "description": "Target <code>DOMNode</code> id." }, + { "name": "ownedNodeIds", "type": "array", "items": { "$ref": "NodeId" }, "optional": true, "description": "Array of <code>DOMNode</code> ids of any nodes referenced via @aria-owns." }, + { "name": "parentNodeId", "$ref": "NodeId", "optional": true, "description": "<code>DOMNode</code> id of the accessibility tree parent object if available." }, + { "name": "pressed", "type": "boolean", "optional": true, "description": "Pressed state for toggle buttons." }, + { "name": "readonly", "type": "boolean", "optional": true, "description": "Readonly state of text controls." }, + { "name": "required", "type": "boolean", "optional": true, "description": "Required state of form controls." }, + { "name": "role", "type": "string", "description": "Computed value for first recognized role token, default role per element, or overridden role." }, + { "name": "selected", "type": "boolean", "optional": true, "description": "Selected state of certain form controls." }, + { "name": "selectedChildNodeIds", "type": "array", "items": { "$ref": "NodeId" }, "optional": true, "description": "Array of <code>DOMNode</code> ids of any children marked as selected." } + ] + }, + { + "id": "RGBAColor", + "type": "object", + "properties": [ + { "name": "r", "type": "integer", "description": "The red component, in the [0-255] range." }, + { "name": "g", "type": "integer", "description": "The green component, in the [0-255] range." }, + { "name": "b", "type": "integer", "description": "The blue component, in the [0-255] range." }, + { "name": "a", "type": "number", "optional": true, "description": "The alpha component, in the [0-1] range (default: 1)." } + ], + "description": "A structure holding an RGBA color." + }, + { + "id": "Quad", + "type": "array", + "items": { "type": "number" }, + "minItems": 8, + "maxItems": 8, + "description": "An array of quad vertices, x immediately followed by y for each point, points clock-wise." + }, + { + "id": "HighlightConfig", + "type": "object", + "properties": [ + { "name": "showInfo", "type": "boolean", "optional": true, "description": "Whether the node info tooltip should be shown (default: false)." }, + { "name": "contentColor", "$ref": "RGBAColor", "optional": true, "description": "The content box highlight fill color (default: transparent)." }, + { "name": "paddingColor", "$ref": "RGBAColor", "optional": true, "description": "The padding highlight fill color (default: transparent)." }, + { "name": "borderColor", "$ref": "RGBAColor", "optional": true, "description": "The border highlight fill color (default: transparent)." }, + { "name": "marginColor", "$ref": "RGBAColor", "optional": true, "description": "The margin highlight fill color (default: transparent)." } + ], + "description": "Configuration data for the highlighting of page elements." + } + ], + "commands": [ + { + "name": "getDocument", + "returns": [ + { "name": "root", "$ref": "Node", "description": "Resulting node." } + ], + "description": "Returns the root DOM node to the caller." + }, + { + "name": "requestChildNodes", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to get children for." }, + { "name": "depth", "type": "integer", "optional": true, "description": "The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0." } + ], + "description": "Requests that children of the node with given id are returned to the caller in form of <code>setChildNodes</code> events where not only immediate children are retrieved, but all children down to the specified depth." + }, + { + "name": "querySelector", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to query upon." }, + { "name": "selector", "type": "string", "description": "Selector string." } + ], + "returns": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Query selector result." } + ], + "description": "Executes <code>querySelector</code> on a given node." + }, + { + "name": "querySelectorAll", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to query upon." }, + { "name": "selector", "type": "string", "description": "Selector string." } + ], + "returns": [ + { "name": "nodeIds", "type": "array", "items": { "$ref": "NodeId" }, "description": "Query selector result." } + ], + "description": "Executes <code>querySelectorAll</code> on a given node." + }, + { + "name": "setNodeName", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to set name for." }, + { "name": "name", "type": "string", "description": "New node's name." } + ], + "returns": [ + { "name": "nodeId", "$ref": "NodeId", "description": "New node's id." } + ], + "description": "Sets node name for a node with given id." + }, + { + "name": "setNodeValue", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to set value for." }, + { "name": "value", "type": "string", "description": "New node's value." } + ], + "description": "Sets node value for a node with given id." + }, + { + "name": "removeNode", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to remove." } + ], + "description": "Removes node with given id." + }, + { + "name": "setAttributeValue", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the element to set attribute for." }, + { "name": "name", "type": "string", "description": "Attribute name." }, + { "name": "value", "type": "string", "description": "Attribute value." } + ], + "description": "Sets attribute for an element with given id." + }, + { + "name": "setAttributesAsText", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the element to set attributes for." }, + { "name": "text", "type": "string", "description": "Text with a number of attributes. Will parse this text using HTML parser." }, + { "name": "name", "type": "string", "optional": true, "description": "Attribute name to replace with new attributes derived from text in case text parsed successfully." } + ], + "description": "Sets attributes on element with given id. This method is useful when user edits some existing attribute value and types in several attribute name/value pairs." + }, + { + "name": "removeAttribute", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the element to remove attribute from." }, + { "name": "name", "type": "string", "description": "Name of the attribute to remove." } + ], + "description": "Removes attribute with given name from an element with given id." + }, + { + "name": "getEventListenersForNode", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to get listeners for." }, + { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name for handler value. Handler value is not returned without this parameter specified." } + ], + "returns": [ + { "name": "listeners", "type": "array", "items": { "$ref": "EventListener"}, "description": "Array of relevant listeners." } + ], + "description": "Returns event listeners relevant to the node." + }, + { + "name": "getAccessibilityPropertiesForNode", + "description": "Returns a dictionary of accessibility properties for the node.", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node for which to get accessibility properties." } + ], + "returns": [ + { "name": "properties", "$ref": "AccessibilityProperties", "description": "Dictionary of relevant accessibility properties." } + ] + }, + { + "name": "getOuterHTML", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to get markup for." } + ], + "returns": [ + { "name": "outerHTML", "type": "string", "description": "Outer HTML markup." } + ], + "description": "Returns node's HTML markup." + }, + { + "name": "setOuterHTML", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to set markup for." }, + { "name": "outerHTML", "type": "string", "description": "Outer HTML markup to set." } + ], + "description": "Sets node HTML markup, returns new node id." + }, + { + "name": "performSearch", + "parameters": [ + { "name": "query", "type": "string", "description": "Plain text or query selector or XPath search query." }, + { "name": "nodeIds", "type": "array", "items": { "$ref": "NodeId" }, "optional": true, "description": "Ids of nodes to use as starting points for the search." } + ], + "returns": [ + { "name": "searchId", "type": "string", "description": "Unique search session identifier." }, + { "name": "resultCount", "type": "integer", "description": "Number of search results." } + ], + "description": "Searches for a given string in the DOM tree. Use <code>getSearchResults</code> to access search results or <code>cancelSearch</code> to end this search session." + }, + { + "name": "getSearchResults", + "parameters": [ + { "name": "searchId", "type": "string", "description": "Unique search session identifier." }, + { "name": "fromIndex", "type": "integer", "description": "Start index of the search result to be returned." }, + { "name": "toIndex", "type": "integer", "description": "End index of the search result to be returned." } + ], + "returns": [ + { "name": "nodeIds", "type": "array", "items": { "$ref": "NodeId" }, "description": "Ids of the search result nodes." } + ], + "description": "Returns search results from given <code>fromIndex</code> to given <code>toIndex</code> from the sarch with the given identifier." + }, + { + "name": "discardSearchResults", + "parameters": [ + { "name": "searchId", "type": "string", "description": "Unique search session identifier." } + ], + "description": "Discards search results from the session with the given id. <code>getSearchResults</code> should no longer be called for that search." + }, + { + "name": "requestNode", + "parameters": [ + { "name": "objectId", "$ref": "Runtime.RemoteObjectId", "description": "JavaScript object id to convert into node." } + ], + "returns": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Node id for given object." } + ], + "description": "Requests that the node is sent to the caller given the JavaScript node object reference. All nodes that form the path from the node to the root are also sent to the client as a series of <code>setChildNodes</code> notifications." + }, + { + "name": "setInspectModeEnabled", + "parameters": [ + { "name": "enabled", "type": "boolean", "description": "True to enable inspection mode, false to disable it." }, + { "name": "highlightConfig", "$ref": "HighlightConfig", "optional": true, "description": "A descriptor for the highlight appearance of hovered-over nodes. May be omitted if <code>enabled == false</code>." } + ], + "description": "Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. Backend then generates 'inspect' command upon element selection." + }, + { + "name": "highlightRect", + "parameters": [ + { "name": "x", "type": "integer", "description": "X coordinate" }, + { "name": "y", "type": "integer", "description": "Y coordinate" }, + { "name": "width", "type": "integer", "description": "Rectangle width" }, + { "name": "height", "type": "integer", "description": "Rectangle height" }, + { "name": "color", "$ref": "RGBAColor", "optional": true, "description": "The highlight fill color (default: transparent)." }, + { "name": "outlineColor", "$ref": "RGBAColor", "optional": true, "description": "The highlight outline color (default: transparent)." }, + { "name": "usePageCoordinates", "type": "boolean", "optional": true, "description": "Indicates whether the provided parameters are in page coordinates or in viewport coordinates (the default)." } + ], + "description": "Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport." + }, + { + "name": "highlightQuad", + "parameters": [ + { "name": "quad", "$ref": "Quad", "description": "Quad to highlight" }, + { "name": "color", "$ref": "RGBAColor", "optional": true, "description": "The highlight fill color (default: transparent)." }, + { "name": "outlineColor", "$ref": "RGBAColor", "optional": true, "description": "The highlight outline color (default: transparent)." }, + { "name": "usePageCoordinates", "type": "boolean", "optional": true, "description": "Indicates whether the provided parameters are in page coordinates or in viewport coordinates (the default)." } + ], + "description": "Highlights given quad. Coordinates are absolute with respect to the main frame viewport." + }, + { + "name": "highlightSelector", + "parameters": [ + { "name": "highlightConfig", "$ref": "HighlightConfig", "description": "A descriptor for the highlight appearance." }, + { "name": "selectorString", "type": "string", "description": "A CSS selector for finding matching nodes to highlight." }, + { "name": "frameId", "type": "string", "optional": true, "description": "Identifier of the frame which will be searched using the selector. If not provided, the main frame will be used." } + ], + "description": "Highlights all DOM nodes that match a given selector. A string containing a CSS selector must be specified." + }, + { + "name": "highlightNode", + "parameters": [ + { "name": "highlightConfig", "$ref": "HighlightConfig", "description": "A descriptor for the highlight appearance." }, + { "name": "nodeId", "$ref": "NodeId", "optional": true, "description": "Identifier of the node to highlight." }, + { "name": "objectId", "$ref": "Runtime.RemoteObjectId", "optional": true, "description": "JavaScript object id of the node to be highlighted." } + ], + "description": "Highlights DOM node with given id or with the given JavaScript object wrapper. Either nodeId or objectId must be specified." + }, + { + "name": "hideHighlight", + "description": "Hides DOM node highlight." + }, + { + "name": "highlightFrame", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Identifier of the frame to highlight." }, + { "name": "contentColor", "$ref": "RGBAColor", "optional": true, "description": "The content box highlight fill color (default: transparent)." }, + { "name": "contentOutlineColor", "$ref": "RGBAColor", "optional": true, "description": "The content box highlight outline color (default: transparent)." } + ], + "description": "Highlights owner element of the frame with given id." + }, + { + "name": "pushNodeByPathToFrontend", + "parameters": [ + { "name": "path", "type": "string", "description": "Path to node in the proprietary format." } + ], + "returns": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node for given path." } + ], + "description": "Requests that the node is sent to the caller given its path. // FIXME, use XPath" + }, + { + "name": "pushNodeByBackendIdToFrontend", + "parameters": [ + { "name": "backendNodeId", "$ref": "BackendNodeId", "description": "The backend node id of the node." } + ], + "returns": [ + { "name": "nodeId", "$ref": "NodeId", "description": "The pushed node's id." } + ], + "description": "Requests that the node is sent to the caller given its backend node id." + }, + { + "name": "releaseBackendNodeIds", + "parameters": [ + { "name": "nodeGroup", "type": "string", "description": "The backend node ids group name." } + ], + "description": "Requests that group of <code>BackendNodeIds</code> is released." + }, + { + "name": "resolveNode", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to resolve." }, + { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." } + ], + "returns": [ + { "name": "object", "$ref": "Runtime.RemoteObject", "description": "JavaScript object wrapper for given node." } + ], + "description": "Resolves JavaScript node object for given node id." + }, + { + "name": "getAttributes", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to retrieve attibutes for." } + ], + "returns": [ + { "name": "attributes", "type": "array", "items": { "type": "string" }, "description": "An interleaved array of node attribute names and values." } + ], + "description": "Returns attributes for the specified node." + }, + { + "name": "moveTo", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to drop." }, + { "name": "targetNodeId", "$ref": "NodeId", "description": "Id of the element to drop into." }, + { "name": "insertBeforeNodeId", "$ref": "NodeId", "optional": true, "description": "Drop node before given one." } + ], + "returns": [ + { "name": "nodeId", "$ref": "NodeId", "description": "New id of the moved node." } + ], + "description": "Moves node into the new container, places it before the given anchor." + }, + { + "name": "undo", + "description": "Undoes the last performed action." + }, + { + "name": "redo", + "description": "Re-does the last undone action." + }, + { + "name": "markUndoableState", + "description": "Marks last undoable state." + }, + { + "name": "focus", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node to focus." } + ], + "description": "Focuses the given element." + } + ], + "events": [ + { + "name": "documentUpdated", + "description": "Fired when <code>Document</code> has been totally updated. Node ids are no longer valid." + }, + { + "name": "setChildNodes", + "parameters": [ + { "name": "parentId", "$ref": "NodeId", "description": "Parent node id to populate with children." }, + { "name": "nodes", "type": "array", "items": { "$ref": "Node"}, "description": "Child nodes array." } + ], + "description": "Fired when backend wants to provide client with the missing DOM structure. This happens upon most of the calls requesting node ids." + }, + { + "name": "attributeModified", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node that has changed." }, + { "name": "name", "type": "string", "description": "Attribute name." }, + { "name": "value", "type": "string", "description": "Attribute value." } + ], + "description": "Fired when <code>Element</code>'s attribute is modified." + }, + { + "name": "attributeRemoved", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node that has changed." }, + { "name": "name", "type": "string", "description": "A ttribute name." } + ], + "description": "Fired when <code>Element</code>'s attribute is removed." + }, + { + "name": "inlineStyleInvalidated", + "parameters": [ + { "name": "nodeIds", "type": "array", "items": { "$ref": "NodeId" }, "description": "Ids of the nodes for which the inline styles have been invalidated." } + ], + "description": "Fired when <code>Element</code>'s inline style is modified via a CSS property modification." + }, + { + "name": "characterDataModified", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node that has changed." }, + { "name": "characterData", "type": "string", "description": "New text value." } + ], + "description": "Mirrors <code>DOMCharacterDataModified</code> event." + }, + { + "name": "childNodeCountUpdated", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node that has changed." }, + { "name": "childNodeCount", "type": "integer", "description": "New node count." } + ], + "description": "Fired when <code>Container</code>'s child node count has changed." + }, + { + "name": "childNodeInserted", + "parameters": [ + { "name": "parentNodeId", "$ref": "NodeId", "description": "Id of the node that has changed." }, + { "name": "previousNodeId", "$ref": "NodeId", "description": "If of the previous siblint." }, + { "name": "node", "$ref": "Node", "description": "Inserted node data." } + ], + "description": "Mirrors <code>DOMNodeInserted</code> event." + }, + { + "name": "childNodeRemoved", + "parameters": [ + { "name": "parentNodeId", "$ref": "NodeId", "description": "Parent id." }, + { "name": "nodeId", "$ref": "NodeId", "description": "Id of the node that has been removed." } + ], + "description": "Mirrors <code>DOMNodeRemoved</code> event." + }, + { + "name": "shadowRootPushed", + "parameters": [ + { "name": "hostId", "$ref": "NodeId", "description": "Host element id." }, + { "name": "root", "$ref": "Node", "description": "Shadow root." } + ], + "description": "Called when shadow root is pushed into the element." + }, + { + "name": "shadowRootPopped", + "parameters": [ + { "name": "hostId", "$ref": "NodeId", "description": "Host element id." }, + { "name": "rootId", "$ref": "NodeId", "description": "Shadow root id." } + ], + "description": "Called when shadow root is popped from the element." + }, + { + "name": "customElementStateChanged", + "parameters": [ + { "name": "nodeId", "$ref": "NodeId", "description": "Element id." }, + { "name": "customElementState", "$ref": "CustomElementState", "description": "Custom element state." } + ], + "description": "Called when the custom element state is changed." + }, + { + "name": "pseudoElementAdded", + "parameters": [ + { "name": "parentId", "$ref": "NodeId", "description": "Pseudo element's parent element id." }, + { "name": "pseudoElement", "$ref": "Node", "description": "The added pseudo element." } + ], + "description": "Called when a pseudo element is added to an element." + }, + { + "name": "pseudoElementRemoved", + "parameters": [ + { "name": "parentId", "$ref": "NodeId", "description": "Pseudo element's parent element id." }, + { "name": "pseudoElementId", "$ref": "NodeId", "description": "The removed pseudo element id." } + ], + "description": "Called when a pseudo element is removed from an element." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/DOMDebugger.json b/Source/JavaScriptCore/inspector/protocol/DOMDebugger.json new file mode 100644 index 000000000..bfab308b0 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/DOMDebugger.json @@ -0,0 +1,73 @@ +{ + "domain": "DOMDebugger", + "description": "DOM debugging allows setting breakpoints on particular DOM operations and events. JavaScript execution will stop on these operations as if there was a regular breakpoint set.", + "availability": "web", + "types": [ + { + "id": "DOMBreakpointType", + "type": "string", + "enum": ["subtree-modified", "attribute-modified", "node-removed"], + "description": "DOM breakpoint type." + } + ], + "commands": [ + { + "name": "setDOMBreakpoint", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "Identifier of the node to set breakpoint on." }, + { "name": "type", "$ref": "DOMBreakpointType", "description": "Type of the operation to stop upon." } + ], + "description": "Sets breakpoint on particular operation with DOM." + }, + { + "name": "removeDOMBreakpoint", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "Identifier of the node to remove breakpoint from." }, + { "name": "type", "$ref": "DOMBreakpointType", "description": "Type of the breakpoint to remove." } + ], + "description": "Removes DOM breakpoint that was set using <code>setDOMBreakpoint</code>." + }, + { + "name": "setEventListenerBreakpoint", + "parameters": [ + { "name": "eventName", "type": "string", "description": "DOM Event name to stop on (any DOM event will do)." } + ], + "description": "Sets breakpoint on particular DOM event." + }, + { + "name": "removeEventListenerBreakpoint", + "parameters": [ + { "name": "eventName", "type": "string", "description": "Event name." } + ], + "description": "Removes breakpoint on particular DOM event." + }, + { + "name": "setInstrumentationBreakpoint", + "parameters": [ + { "name": "eventName", "type": "string", "description": "Instrumentation name to stop on." } + ], + "description": "Sets breakpoint on particular native event." + }, + { + "name": "removeInstrumentationBreakpoint", + "parameters": [ + { "name": "eventName", "type": "string", "description": "Instrumentation name to stop on." } + ], + "description": "Sets breakpoint on particular native event." + }, + { + "name": "setXHRBreakpoint", + "parameters": [ + { "name": "url", "type": "string", "description": "Resource URL substring. All XHRs having this substring in the URL will get stopped upon." } + ], + "description": "Sets breakpoint on XMLHttpRequest." + }, + { + "name": "removeXHRBreakpoint", + "parameters": [ + { "name": "url", "type": "string", "description": "Resource URL substring." } + ], + "description": "Removes breakpoint from XMLHttpRequest." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/DOMStorage.json b/Source/JavaScriptCore/inspector/protocol/DOMStorage.json new file mode 100644 index 000000000..812e70d3f --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/DOMStorage.json @@ -0,0 +1,88 @@ +{ + "domain": "DOMStorage", + "description": "Query and modify DOM storage.", + "availability": "web", + "types": [ + { + "id": "StorageId", + "type": "object", + "description": "DOM Storage identifier.", + "properties": [ + { "name": "securityOrigin", "type": "string", "description": "Security origin for the storage." }, + { "name": "isLocalStorage", "type": "boolean", "description": "Whether the storage is local storage (not session storage)." } + ] + }, + { + "id": "Item", + "type": "array", + "description": "DOM Storage item.", + "items": { "type": "string" } + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables storage tracking, storage events will now be delivered to the client." + }, + { + "name": "disable", + "description": "Disables storage tracking, prevents storage events from being sent to the client." + }, + { + "name": "getDOMStorageItems", + "parameters": [ + { "name": "storageId", "$ref": "StorageId" } + ], + "returns": [ + { "name": "entries", "type": "array", "items": { "$ref": "Item" } } + ] + }, + { + "name": "setDOMStorageItem", + "parameters": [ + { "name": "storageId", "$ref": "StorageId" }, + { "name": "key", "type": "string" }, + { "name": "value", "type": "string" } + ] + }, + { + "name": "removeDOMStorageItem", + "parameters": [ + { "name": "storageId", "$ref": "StorageId" }, + { "name": "key", "type": "string" } + ] + } + ], + "events": [ + { + "name": "domStorageItemsCleared", + "parameters": [ + { "name": "storageId", "$ref": "StorageId" } + ] + }, + { + "name": "domStorageItemRemoved", + "parameters": [ + { "name": "storageId", "$ref": "StorageId" }, + { "name": "key", "type": "string" } + ] + }, + { + "name": "domStorageItemAdded", + "parameters": [ + { "name": "storageId", "$ref": "StorageId" }, + { "name": "key", "type": "string" }, + { "name": "newValue", "type": "string" } + ] + }, + { + "name": "domStorageItemUpdated", + "parameters": [ + { "name": "storageId", "$ref": "StorageId" }, + { "name": "key", "type": "string" }, + { "name": "oldValue", "type": "string" }, + { "name": "newValue", "type": "string" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Database.json b/Source/JavaScriptCore/inspector/protocol/Database.json new file mode 100644 index 000000000..b959e0f2d --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Database.json @@ -0,0 +1,71 @@ +{ + "domain": "Database", + "availability": "web", + "types": [ + { + "id": "DatabaseId", + "type": "string", + "description": "Unique identifier of Database object." + }, + { + "id": "Database", + "type": "object", + "description": "Database object.", + "properties": [ + { "name": "id", "$ref": "DatabaseId", "description": "Database ID." }, + { "name": "domain", "type": "string", "description": "Database domain." }, + { "name": "name", "type": "string", "description": "Database name." }, + { "name": "version", "type": "string", "description": "Database version." } + ] + }, + { + "id": "Error", + "type": "object", + "description": "Database error.", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables database tracking, database events will now be delivered to the client." + }, + { + "name": "disable", + "description": "Disables database tracking, prevents database events from being sent to the client." + }, + { + "name": "getDatabaseTableNames", + "parameters": [ + { "name": "databaseId", "$ref": "DatabaseId" } + ], + "returns": [ + { "name": "tableNames", "type": "array", "items": { "type": "string" } } + ] + }, + { + "name": "executeSQL", + "async": true, + "parameters": [ + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "query", "type": "string" } + ], + "returns": [ + { "name": "columnNames", "type": "array", "optional": true, "items": { "type": "string" } }, + { "name": "values", "type": "array", "optional": true, "items": { "type": "any" }}, + { "name": "sqlError", "$ref": "Error", "optional": true } + ] + } + ], + "events": [ + { + "name": "addDatabase", + "parameters": [ + { "name": "database", "$ref": "Database" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Debugger.json b/Source/JavaScriptCore/inspector/protocol/Debugger.json index d80edeb3b..7b63fea46 100644 --- a/Source/JavaScriptCore/inspector/protocol/Debugger.json +++ b/Source/JavaScriptCore/inspector/protocol/Debugger.json @@ -1,6 +1,7 @@ { "domain": "Debugger", "description": "Debugger domain exposes JavaScript debugging capabilities. It allows setting and removing breakpoints, stepping through execution, exploring stack traces, etc.", + "workerSupported": true, "types": [ { "id": "BreakpointId", @@ -37,7 +38,8 @@ "type": "object", "properties": [ { "name": "type", "type": "string", "enum": ["log", "evaluate", "sound", "probe"], "description": "Different kinds of breakpoint actions." }, - { "name": "data", "type": "string", "optional": true, "description": "Data associated with this breakpoint type (e.g. for type \"eval\" this is the JavaScript string to evalulate)." } + { "name": "data", "type": "string", "optional": true, "description": "Data associated with this breakpoint type (e.g. for type \"eval\" this is the JavaScript string to evalulate)." }, + { "name": "id", "$ref": "BreakpointActionIdentifier", "optional": true, "description": "A frontend-assigned identifier for this breakpoint action." } ], "description": "Action to perform when a breakpoint is triggered." }, @@ -47,7 +49,8 @@ "properties": [ { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true." }, { "name": "actions", "type": "array", "optional": true, "items": { "$ref": "BreakpointAction" }, "description": "Actions to perform automatically when the breakpoint is triggered." }, - { "name": "autoContinue", "type": "boolean", "optional": true, "description": "Automatically continue after hitting this breakpoint and running actions." } + { "name": "autoContinue", "type": "boolean", "optional": true, "description": "Automatically continue after hitting this breakpoint and running actions." }, + { "name": "ignoreCount", "type": "integer", "optional": true, "description": "Number of times to ignore this breakpoint, before stopping on the breakpoint and running actions." } ], "description": "Extra options that modify breakpoint behavior." }, @@ -58,7 +61,6 @@ { "name": "location", "$ref": "Location", "description": "Location of the function." }, { "name": "name", "type": "string", "optional": true, "description": "Name of the function. Not present for anonymous functions." }, { "name": "displayName", "type": "string", "optional": true, "description": "Display name of the function(specified in 'displayName' property on the function object)." }, - { "name": "inferredName", "type": "string", "optional": true, "description": "Name of the function inferred from its initial assignment." }, { "name": "scopeChain", "type": "array", "optional": true, "items": { "$ref": "Scope" }, "description": "Scope chain for this closure." } ], "description": "Information about the function." @@ -71,7 +73,8 @@ { "name": "functionName", "type": "string", "description": "Name of the JavaScript function called on this call frame." }, { "name": "location", "$ref": "Location", "description": "Location in the source code." }, { "name": "scopeChain", "type": "array", "items": { "$ref": "Scope" }, "description": "Scope chain for this call frame." }, - { "name": "this", "$ref": "Runtime.RemoteObject", "description": "<code>this</code> object for this call frame." } + { "name": "this", "$ref": "Runtime.RemoteObject", "description": "<code>this</code> object for this call frame." }, + { "name": "isTailDeleted", "type": "boolean", "description": "Is the current frame tail deleted from a tail call." } ], "description": "JavaScript call frame. Array of call frames form the call stack." }, @@ -79,8 +82,11 @@ "id": "Scope", "type": "object", "properties": [ - { "name": "type", "type": "string", "enum": ["global", "local", "with", "closure", "catch"], "description": "Scope type." }, - { "name": "object", "$ref": "Runtime.RemoteObject", "description": "Object representing the scope. For <code>global</code> and <code>with</code> scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties." } + { "name": "object", "$ref": "Runtime.RemoteObject", "description": "Object representing the scope. For <code>global</code> and <code>with</code> scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties." }, + { "name": "type", "type": "string", "enum": ["global", "with", "closure", "catch", "functionName", "globalLexicalEnvironment", "nestedLexical"], "description": "Scope type." }, + { "name": "name", "type": "string", "optional": true, "description": "Name associated with the scope." }, + { "name": "location", "$ref": "Location", "optional": true, "description": "Location if available of the scope definition." }, + { "name": "empty", "type": "boolean", "optional": true, "description": "Whether the scope has any variables." } ], "description": "Scope description." }, @@ -95,6 +101,30 @@ { "name": "timestamp", "type": "number", "description": "Timestamp of when the sample was taken." }, { "name": "payload", "$ref": "Runtime.RemoteObject", "description": "Contents of the sample." } ] + }, + { + "id": "AssertPauseReason", + "description": "The pause reason auxiliary data when paused because of an assertion.", + "type": "object", + "properties": [ + { "name": "message", "type": "string", "optional": true, "description": "The console.assert message string if provided." } + ] + }, + { + "id": "BreakpointPauseReason", + "description": "The pause reason auxiliary data when paused because of hitting a breakpoint.", + "type": "object", + "properties": [ + { "name": "breakpointId", "type": "string", "description": "The identifier of the breakpoint causing the pause." } + ] + }, + { + "id": "CSPViolationPauseReason", + "description": "The pause reason auxiliary data when paused because of a Content Security Policy directive.", + "type": "object", + "properties": [ + { "name": "directive", "type": "string", "description": "The CSP directive that blocked script execution." } + ] } ], "commands": [ @@ -107,6 +137,13 @@ "description": "Disables debugger for given page." }, { + "name": "setAsyncStackTraceDepth", + "description": "Set the async stack trace depth for the page. A value of zero disables recording of async stack traces.", + "parameters": [ + { "name": "depth", "type": "integer", "description": "Async stack trace depth." } + ] + }, + { "name": "setBreakpointsActive", "parameters": [ { "name": "active", "type": "boolean", "description": "New value for breakpoints active state." } @@ -124,8 +161,7 @@ ], "returns": [ { "name": "breakpointId", "$ref": "BreakpointId", "description": "Id of the created breakpoint for further reference." }, - { "name": "locations", "type": "array", "items": { "$ref": "Location"}, "description": "List of the locations this breakpoint resolved into upon addition." }, - { "name": "breakpointActionIdentifiers", "type": "array", "items": { "$ref": "BreakpointActionIdentifier" }, "description": "Assigned breakpoint action identifiers." } + { "name": "locations", "type": "array", "items": { "$ref": "Location"}, "description": "List of the locations this breakpoint resolved into upon addition." } ], "description": "Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in <code>locations</code> property. Further matching script parsing will result in subsequent <code>breakpointResolved</code> events issued. This logical breakpoint will survive page reloads." }, @@ -137,8 +173,7 @@ ], "returns": [ { "name": "breakpointId", "$ref": "BreakpointId", "description": "Id of the created breakpoint for further reference." }, - { "name": "actualLocation", "$ref": "Location", "description": "Location this breakpoint resolved into." }, - { "name": "breakpointActionIdentifiers", "type": "array", "items": { "$ref": "BreakpointActionIdentifier" }, "description": "Assigned breakpoint action identifiers." } + { "name": "actualLocation", "$ref": "Location", "description": "Location this breakpoint resolved into." } ], "description": "Sets JavaScript breakpoint at a given location." }, @@ -150,23 +185,27 @@ "description": "Removes JavaScript breakpoint." }, { + "name": "continueUntilNextRunLoop", + "description": "Continues execution until the current evaluation completes. This will trigger either a Debugger.paused or Debugger.resumed event." + }, + { "name": "continueToLocation", + "description": "Continues execution until specific location is reached. This will trigger either a Debugger.paused or Debugger.resumed event.", "parameters": [ { "name": "location", "$ref": "Location", "description": "Location to continue to." } - ], - "description": "Continues execution until specific location is reached." + ] }, { "name": "stepOver", - "description": "Steps over the statement." + "description": "Steps over the statement. This will trigger either a Debugger.paused or Debugger.resumed event." }, { "name": "stepInto", - "description": "Steps into the function call." + "description": "Steps into the function call. This will trigger either a Debugger.paused or Debugger.resumed event." }, { "name": "stepOut", - "description": "Steps out of the function call." + "description": "Steps out of the function call. This will trigger either a Debugger.paused or Debugger.resumed event." }, { "name": "pause", @@ -174,20 +213,20 @@ }, { "name": "resume", - "description": "Resumes JavaScript execution." + "description": "Resumes JavaScript execution. This will trigger a Debugger.resumed event." }, { "name": "searchInContent", + "description": "Searches for given string in script content.", "parameters": [ { "name": "scriptId", "$ref": "ScriptId", "description": "Id of the script to search in." }, - { "name": "query", "type": "string", "description": "String to search for." }, + { "name": "query", "type": "string", "description": "String to search for." }, { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive." }, { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex." } ], "returns": [ { "name": "result", "type": "array", "items": { "$ref": "GenericTypes.SearchMatch" }, "description": "List of search matches." } - ], - "description": "Searches for given string in script content." + ] }, { "name": "getScriptSource", @@ -207,14 +246,21 @@ "returns": [ { "name": "details", "$ref": "FunctionDetails", "description": "Information about the function." } ], - "description": "Returns detailed informtation on given function." + "description": "Returns detailed information on given function." }, { "name": "setPauseOnExceptions", + "description": "Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>.", "parameters": [ { "name": "state", "type": "string", "enum": ["none", "uncaught", "all"], "description": "Pause on exceptions mode." } - ], - "description": "Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>." + ] + }, + { + "name": "setPauseOnAssertions", + "description": "Set pause on assertions state. Assertions are console.assert assertions.", + "parameters": [ + { "name": "enabled", "type": "boolean" } + ] }, { "name": "evaluateOnCallFrame", @@ -225,11 +271,13 @@ { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Specifies whether command line API should be available to the evaluated expression, defaults to false." }, { "name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true, "description": "Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state." }, { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." } + { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." }, + { "name": "saveResult", "type": "boolean", "optional": true, "description": "Whether the resulting value should be considered for saving in the $n history." } ], "returns": [ { "name": "result", "$ref": "Runtime.RemoteObject", "description": "Object wrapper for the evaluation result." }, - { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation." } + { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation." }, + { "name": "savedResultIndex", "type": "integer", "optional": true, "description": "If the result was saved, this is the $n index that can be used to access the value." } ], "description": "Evaluates expression on a given call frame." }, @@ -250,14 +298,15 @@ "name": "scriptParsed", "parameters": [ { "name": "scriptId", "$ref": "ScriptId", "description": "Identifier of the script parsed." }, - { "name": "url", "type": "string", "description": "URL or name of the script parsed (if any)." }, + { "name": "url", "type": "string", "description": "URL of the script parsed (if any)." }, { "name": "startLine", "type": "integer", "description": "Line offset of the script within the resource with given URL (for script tags)." }, { "name": "startColumn", "type": "integer", "description": "Column offset of the script within the resource with given URL." }, { "name": "endLine", "type": "integer", "description": "Last line of the script." }, { "name": "endColumn", "type": "integer", "description": "Length of the last line of the script." }, { "name": "isContentScript", "type": "boolean", "optional": true, "description": "Determines whether this script is a user extension script." }, + { "name": "sourceURL", "type": "string", "optional": true, "description": "sourceURL name of the script (if any)." }, { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with script (if any)." }, - { "name": "hasSourceURL", "type": "boolean", "optional": true, "description": "True, if this script has sourceURL." } + { "name": "module", "type": "boolean", "optional": true, "description": "True if this script was parsed as a module." } ], "description": "Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger." }, @@ -284,8 +333,9 @@ "name": "paused", "parameters": [ { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" }, "description": "Call stack the virtual machine stopped on." }, - { "name": "reason", "type": "string", "enum": [ "XHR", "DOM", "EventListener", "exception", "assert", "CSPViolation", "other" ], "description": "Pause reason." }, - { "name": "data", "type": "object", "optional": true, "description": "Object containing break-specific auxiliary properties." } + { "name": "reason", "type": "string", "enum": ["XHR", "DOM", "EventListener", "exception", "assert", "CSPViolation", "DebuggerStatement", "Breakpoint", "PauseOnNextStatement", "other"], "description": "Pause reason." }, + { "name": "data", "type": "object", "optional": true, "description": "Object containing break-specific auxiliary properties." }, + { "name": "asyncStackTrace", "$ref": "Console.StackTrace", "optional": true, "description": "Linked list of asynchronous StackTraces." } ], "description": "Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria." }, @@ -295,10 +345,17 @@ }, { "name": "didSampleProbe", - "description": "Fires when a new proben sample is collected.", + "description": "Fires when a new probe sample is collected.", "parameters": [ { "name": "sample", "$ref": "ProbeSample", "description": "A collected probe sample." } ] + }, + { + "name": "playBreakpointActionSound", + "description": "Fired when a \"sound\" breakpoint action is triggered on a breakpoint.", + "parameters": [ + { "name": "breakpointActionId", "$ref": "BreakpointActionIdentifier", "description": "Breakpoint action identifier." } + ] } ] } diff --git a/Source/JavaScriptCore/inspector/protocol/Heap.json b/Source/JavaScriptCore/inspector/protocol/Heap.json new file mode 100644 index 000000000..450ade8ab --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Heap.json @@ -0,0 +1,100 @@ +{ + "domain": "Heap", + "description": "Heap domain exposes JavaScript heap attributes and capabilities.", + "workerSupported": true, + "types": [ + { + "id": "GarbageCollection", + "description": "Information about a garbage collection.", + "type": "object", + "properties": [ + { "name": "type", "type": "string", "enum": ["full", "partial"], "description": "The type of garbage collection." }, + { "name": "startTime", "type": "number" }, + { "name": "endTime", "type": "number" } + ] + }, + { + "id": "HeapSnapshotData", + "description": "JavaScriptCore HeapSnapshot JSON data.", + "type": "string" + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables Heap domain events." + }, + { + "name": "disable", + "description": "Disables Heap domain events." + }, + { + "name": "gc", + "description": "Trigger a full garbage collection." + }, + { + "name": "snapshot", + "description": "Take a heap snapshot.", + "returns": [ + { "name": "timestamp", "type": "number" }, + { "name": "snapshotData", "$ref": "HeapSnapshotData" } + ] + }, + { + "name": "startTracking", + "description": "Start tracking heap changes. This will produce a `trackingStart` event." + }, + { + "name": "stopTracking", + "description": "Stop tracking heap changes. This will produce a `trackingComplete` event." + }, + { + "name": "getPreview", + "description": "Returns a preview (string, Debugger.FunctionDetails, or Runtime.ObjectPreview) for a Heap.HeapObjectId.", + "parameters": [ + { "name": "heapObjectId", "type": "integer", "description": "Identifier of the heap object within the snapshot." } + ], + "returns": [ + { "name": "string", "type": "string", "optional": true, "description": "String value." }, + { "name": "functionDetails", "$ref": "Debugger.FunctionDetails", "optional": true, "description": "Function details." }, + { "name": "preview", "$ref": "Runtime.ObjectPreview", "optional": true, "description": "Object preview." } + ] + }, + { + "name": "getRemoteObject", + "description": "Returns the strongly referenced Runtime.RemoteObject for a Heap.HeapObjectId.", + "parameters": [ + { "name": "heapObjectId", "type": "integer", "description": "Identifier of the heap object within the snapshot." }, + { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." } + ], + "returns": [ + { "name": "result", "$ref": "Runtime.RemoteObject", "description": "Resulting object." } + ] + } + ], + "events": [ + { + "name": "garbageCollected", + "description": "Information about the garbage collection.", + "parameters": [ + { "name": "collection", "$ref": "GarbageCollection" } + ] + }, + { + "name": "trackingStart", + "description": "Tracking started.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { "name": "snapshotData", "$ref": "HeapSnapshotData", "description": "Snapshot at the start of tracking." } + ] + }, + { + "name": "trackingComplete", + "description": "Tracking stopped.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { "name": "snapshotData", "$ref": "HeapSnapshotData", "description": "Snapshot at the end of tracking." } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/IndexedDB.json b/Source/JavaScriptCore/inspector/protocol/IndexedDB.json new file mode 100644 index 000000000..bc35008d9 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/IndexedDB.json @@ -0,0 +1,143 @@ +{ + "domain": "IndexedDB", + "featureGuard": "ENABLE(INDEXED_DATABASE)", + "availability": "web", + "types": [ + { + "id": "DatabaseWithObjectStores", + "type": "object", + "description": "Database with an array of object stores.", + "properties": [ + { "name": "name", "type": "string", "description": "Database name." }, + { "name": "version", "type": "number", "description": "Database version." }, + { "name": "objectStores", "type": "array", "items": { "$ref": "ObjectStore" }, "description": "Object stores in this database." } + ] + }, + { + "id": "ObjectStore", + "type": "object", + "description": "Object store.", + "properties": [ + { "name": "name", "type": "string", "description": "Object store name." }, + { "name": "keyPath", "$ref": "KeyPath", "description": "Object store key path." }, + { "name": "autoIncrement", "type": "boolean", "description": "If true, object store has auto increment flag set." }, + { "name": "indexes", "type": "array", "items": { "$ref": "ObjectStoreIndex" }, "description": "Indexes in this object store." } + ] + }, + { + "id": "ObjectStoreIndex", + "type": "object", + "description": "Object store index.", + "properties": [ + { "name": "name", "type": "string", "description": "Index name." }, + { "name": "keyPath", "$ref": "KeyPath", "description": "Index key path." }, + { "name": "unique", "type": "boolean", "description": "If true, index is unique." }, + { "name": "multiEntry", "type": "boolean", "description": "If true, index allows multiple entries for a key." } + ] + }, + { + "id": "Key", + "type": "object", + "description": "Key.", + "properties": [ + { "name": "type", "type": "string", "enum": ["number", "string", "date", "array"], "description": "Key type." }, + { "name": "number", "type": "number", "optional": true, "description": "Number value." }, + { "name": "string", "type": "string", "optional": true, "description": "String value." }, + { "name": "date", "type": "number", "optional": true, "description": "Date value." }, + { "name": "array", "type": "array", "optional": true, "items": { "$ref": "Key" }, "description": "Array value." } + ] + }, + { + "id": "KeyRange", + "type": "object", + "description": "Key range.", + "properties": [ + { "name": "lower", "$ref": "Key", "optional": true, "description": "Lower bound." }, + { "name": "upper", "$ref": "Key", "optional": true, "description": "Upper bound." }, + { "name": "lowerOpen", "type": "boolean", "description": "If true lower bound is open." }, + { "name": "upperOpen", "type": "boolean", "description": "If true upper bound is open." } + ] + }, + { + "id": "DataEntry", + "type": "object", + "description": "Data entry.", + "properties": [ + { "name": "key", "$ref": "Runtime.RemoteObject", "description": "Key." }, + { "name": "primaryKey", "$ref": "Runtime.RemoteObject", "description": "Primary key." }, + { "name": "value", "$ref": "Runtime.RemoteObject", "description": "Value." } + ] + }, + { + "id": "KeyPath", + "type": "object", + "description": "Key path.", + "properties": [ + { "name": "type", "type": "string", "enum": ["null", "string", "array"], "description": "Key path type." }, + { "name": "string", "type": "string", "optional": true, "description": "String value." }, + { "name": "array", "type": "array", "optional": true, "items": { "type": "string" }, "description": "Array value." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables events from backend." + }, + { + "name": "disable", + "description": "Disables events from backend." + }, + { + "name": "requestDatabaseNames", + "description": "Requests database names for given security origin.", + "async": true, + "parameters": [ + { "name": "securityOrigin", "type": "string", "description": "Security origin." } + ], + "returns": [ + { "name": "databaseNames", "type": "array", "items": { "type": "string" }, "description": "Database names for origin." } + ] + }, + { + "name": "requestDatabase", + "description": "Requests database with given name in given frame.", + "async": true, + "parameters": [ + { "name": "securityOrigin", "type": "string", "description": "Security origin." }, + { "name": "databaseName", "type": "string", "description": "Database name." } + ], + "returns": [ + { "name": "databaseWithObjectStores", "$ref": "DatabaseWithObjectStores", "description": "Database with an array of object stores." } + ] + }, + { + "name": "requestData", + "description": "Requests data from object store or index.", + "async": true, + "parameters": [ + { "name": "securityOrigin", "type": "string", "description": "Security origin." }, + { "name": "databaseName", "type": "string", "description": "Database name." }, + { "name": "objectStoreName", "type": "string", "description": "Object store name." }, + { "name": "indexName", "type": "string", "description": "Index name, empty string for object store data requests." }, + { "name": "skipCount", "type": "integer", "description": "Number of records to skip." }, + { "name": "pageSize", "type": "integer", "description": "Number of records to fetch." }, + { "name": "keyRange", "$ref": "KeyRange", "optional": true, "description": "Key range." } + ], + "returns": [ + { "name": "objectStoreDataEntries", "type": "array", "items": { "$ref": "DataEntry" }, "description": "Array of object store data entries." }, + { "name": "hasMore", "type": "boolean", "description": "If true, there are more entries to fetch in the given range." } + ] + }, + { + "name": "clearObjectStore", + "description": "Clears all entries from an object store.", + "async": true, + "parameters": [ + { "name": "securityOrigin", "type": "string", "description": "Security origin." }, + { "name": "databaseName", "type": "string", "description": "Database name." }, + { "name": "objectStoreName", "type": "string", "description": "Object store name." } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/InspectorDomain.json b/Source/JavaScriptCore/inspector/protocol/Inspector.json index 83a213021..0420ebda0 100644 --- a/Source/JavaScriptCore/inspector/protocol/InspectorDomain.json +++ b/Source/JavaScriptCore/inspector/protocol/Inspector.json @@ -9,13 +9,16 @@ { "name": "disable", "description": "Disables inspector domain notifications." + }, + { + "name": "initialized", + "description": "Sent by the frontend after all initialization messages have been sent." } ], "events": [ { "name": "evaluateForTestInFrontend", "parameters": [ - { "name": "testCallId", "type": "integer" }, { "name": "script", "type": "string" } ] }, @@ -34,6 +37,13 @@ ] }, { + "name": "activateExtraDomains", + "description": "Fired when the backend has alternate domains that need to be activated.", + "parameters": [ + { "name": "domains", "type": "array", "items": { "type": "string" }, "description": "Domain names that need activation" } + ] + }, + { "name": "targetCrashed", "description": "Fired when debugging target has crashed" } diff --git a/Source/JavaScriptCore/inspector/protocol/LayerTree.json b/Source/JavaScriptCore/inspector/protocol/LayerTree.json new file mode 100644 index 000000000..4115cd4ab --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/LayerTree.json @@ -0,0 +1,114 @@ +{ + "domain": "LayerTree", + "availability": "web", + "types": [ + { + "id": "LayerId", + "type": "string", + "description": "Unique RenderLayer identifier." + }, + { + "id": "PseudoElementId", + "type": "string", + "description": "Unique PseudoElement identifier." + }, + { + "id": "IntRect", + "type": "object", + "description": "A rectangle.", + "properties": [ + { "name": "x", "type": "integer", "description": "The x position." }, + { "name": "y", "type": "integer", "description": "The y position." }, + { "name": "width", "type": "integer", "description": "The width metric." }, + { "name": "height", "type": "integer", "description": "The height metric." } + ] + }, + { + "id": "Layer", + "type": "object", + "description": "Information about a compositing layer.", + "properties": [ + { "name": "layerId", "$ref": "LayerId", "description": "The unique id for this layer." }, + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "The id for the node associated with this layer." }, + { "name": "bounds", "$ref": "IntRect", "description": "Bounds of the layer in absolute page coordinates." }, + { "name": "paintCount", "type": "integer", "description": "Indicates how many time this layer has painted." }, + { "name": "memory", "type": "integer", "description": "Estimated memory used by this layer." }, + { "name": "compositedBounds", "$ref": "IntRect", "description": "The bounds of the composited layer." }, + { "name": "isInShadowTree", "type": "boolean", "optional": true, "description": "Indicates whether this layer is associated with an element hosted in a shadow tree." }, + { "name": "isReflection", "type": "boolean", "optional": true, "description": "Indicates whether this layer was used to provide a reflection for the element." }, + { "name": "isGeneratedContent", "type": "boolean", "optional": true, "description": "Indicates whether the layer is attached to a pseudo element that is CSS generated content." }, + { "name": "isAnonymous", "type": "boolean", "optional": true, "description": "Indicates whether the layer was created for a CSS anonymous block or box." }, + { "name": "pseudoElementId", "$ref": "PseudoElementId", "optional": true, "description": "The id for the pseudo element associated with this layer." }, + { "name": "pseudoElement", "type": "string", "optional": true, "description": "The name of the CSS pseudo-element that prompted the layer to be generated." } + ] + }, + { + "id": "CompositingReasons", + "type": "object", + "description": "An object containing the reasons why the layer was composited as properties.", + "properties": [ + { "name": "transform3D", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a CSS 3D transform." }, + { "name": "video", "type": "boolean", "optional": true, "description": "Composition due to association with a <video> element." }, + { "name": "canvas", "type": "boolean", "optional": true, "description": "Composition due to the element being a <canvas> element." }, + { "name": "plugin", "type": "boolean", "optional": true, "description": "Composition due to association with a plugin." }, + { "name": "iFrame", "type": "boolean", "optional": true, "description": "Composition due to association with an <iframe> element." }, + { "name": "backfaceVisibilityHidden", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a \"backface-visibility: hidden\" style." }, + { "name": "clipsCompositingDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with an element clipping compositing descendants." }, + { "name": "animation", "type": "boolean", "optional": true, "description": "Composition due to association with an animated element." }, + { "name": "filters", "type": "boolean", "optional": true, "description": "Composition due to association with an element with CSS filters applied." }, + { "name": "positionFixed", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a \"position: fixed\" style." }, + { "name": "positionSticky", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a \"position: sticky\" style." }, + { "name": "overflowScrollingTouch", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a \"overflow-scrolling: touch\" style." }, + { "name": "stacking", "type": "boolean", "optional": true, "description": "Composition due to association with an element establishing a stacking context." }, + { "name": "overlap", "type": "boolean", "optional": true, "description": "Composition due to association with an element overlapping other composited elements." }, + { "name": "negativeZIndexChildren", "type": "boolean", "optional": true, "description": "Composition due to association with an element with descendants that have a negative z-index." }, + { "name": "transformWithCompositedDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with an element with composited descendants." }, + { "name": "opacityWithCompositedDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with an element with opacity applied and composited descendants." }, + { "name": "maskWithCompositedDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with a masked element and composited descendants." }, + { "name": "reflectionWithCompositedDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a reflection and composited descendants." }, + { "name": "filterWithCompositedDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with an element with CSS filters applied and composited descendants." }, + { "name": "blendingWithCompositedDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with an element with CSS blending applied and composited descendants." }, + { "name": "isolatesCompositedBlendingDescendants", "type": "boolean", "optional": true, "description": "Composition due to association with an element isolating compositing descendants having CSS blending applied." }, + { "name": "perspective", "type": "boolean", "optional": true, "description": "Composition due to association with an element with perspective applied." }, + { "name": "preserve3D", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a \"transform-style: preserve-3d\" style." }, + { "name": "willChange", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a \"will-change\" style." }, + { "name": "root", "type": "boolean", "optional": true, "description": "Composition due to association with the root element." }, + { "name": "blending", "type": "boolean", "optional": true, "description": "Composition due to association with an element with a \"blend-mode\" style." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables compositing tree inspection." + }, + { + "name": "disable", + "description": "Disables compositing tree inspection." + }, + { + "name": "layersForNode", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "Root of the subtree for which we want to gather layers." } ], + "description": "Returns the layer tree structure of the current page.", + "returns": [ + { "name": "layers", "type": "array", "items": { "$ref": "Layer" }, "description": "Child layers." } + ] + }, + { + "name": "reasonsForCompositingLayer", + "parameters": [ + { "name": "layerId", "$ref": "LayerId", "description": "The id of the layer for which we want to get the reasons it was composited." } + ], + "description": "Provides the reasons why the given layer was composited.", + "returns": [ + { "name": "compositingReasons", "$ref": "CompositingReasons", "description": "An object containing the reasons why the layer was composited as properties." } + ] + } + ], + "events": [ + { + "name": "layerTreeDidChange" + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Memory.json b/Source/JavaScriptCore/inspector/protocol/Memory.json new file mode 100644 index 000000000..7dcfe59ae --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Memory.json @@ -0,0 +1,70 @@ +{ + "domain": "Memory", + "description": "Memory domain exposes page memory tracking.", + "featureGuard": "ENABLE(RESOURCE_USAGE)", + "availability": "web", + "types": [ + { + "id": "Event", + "type": "object", + "properties": [ + { "name": "timestamp", "type": "number" }, + { "name": "categories", "type": "array", "items": { "$ref": "CategoryData" }, "description": "Breakdown of memory in categories." } + ] + }, + { + "id": "CategoryData", + "type": "object", + "properties": [ + { "name": "type", "type": "string", "enum": ["javascript", "jit", "images", "layers", "page", "other"], "description": "Category type." }, + { "name": "size", "type": "number", "description": "Category size in bytes." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables Memory domain events." + }, + { + "name": "disable", + "description": "Disables Memory domain events." + }, + { + "name": "startTracking", + "description": "Start tracking memory. This will produce a `trackingStart` event." + }, + { + "name": "stopTracking", + "description": "Stop tracking memory. This will produce a `trackingComplete` event." + } + ], + "events": [ + { + "name": "memoryPressure", + "description": "Memory pressure was encountered.", + "parameters": [ + { "name": "timestamp", "type": "number" }, + { "name": "severity", "type": "string", "enum": ["critical", "non-critical"], "description": "The severity of the memory pressure event." } + ] + }, + { + "name": "trackingStart", + "description": "Tracking started.", + "parameters": [ + { "name": "timestamp", "type": "number" } + ] + }, + { + "name": "trackingUpdate", + "description": "Periodic tracking updates with event data.", + "parameters": [ + { "name": "event", "$ref": "Event" } + ] + }, + { + "name": "trackingComplete", + "description": "Tracking stopped." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Network.json b/Source/JavaScriptCore/inspector/protocol/Network.json new file mode 100644 index 000000000..5b159ab16 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Network.json @@ -0,0 +1,315 @@ +{ + "domain": "Network", + "description": "Network domain allows tracking network activities of the page. It exposes information about http, file, data and other requests and responses, their headers, bodies, timing, etc.", + "availability": "web", + "types": [ + { + "id": "LoaderId", + "type": "string", + "description": "Unique loader identifier." + }, + { + "id": "FrameId", + "type": "string", + "description": "Unique frame identifier." + }, + { + "id": "RequestId", + "type": "string", + "description": "Unique request identifier." + }, + { + "id": "Timestamp", + "type": "number", + "description": "Number of seconds since epoch." + }, + { + "id": "Headers", + "type": "object", + "description": "Request / response headers as keys / values of JSON object." + }, + { + "id": "ResourceTiming", + "type": "object", + "description": "Timing information for the request.", + "properties": [ + { "name": "startTime", "type": "number", "description": "Timing's startTime is a baseline in seconds, while the other numbers are ticks in milliseconds relatively to this." }, + { "name": "domainLookupStart", "type": "number", "description": "Started DNS address resolve." }, + { "name": "domainLookupEnd", "type": "number", "description": "Finished DNS address resolve." }, + { "name": "connectStart", "type": "number", "description": "Started connecting to the remote host." }, + { "name": "connectEnd", "type": "number", "description": "Connected to the remote host." }, + { "name": "secureConnectionStart", "type": "number", "description": "Started SSL handshake." }, + { "name": "requestStart", "type": "number", "description": "Started sending request." }, + { "name": "responseStart", "type": "number", "description": "Started receiving response headers." } + ] + }, + { + "id": "Request", + "type": "object", + "description": "HTTP request data.", + "properties": [ + { "name": "url", "type": "string", "description": "Request URL." }, + { "name": "method", "type": "string", "description": "HTTP request method." }, + { "name": "headers", "$ref": "Headers", "description": "HTTP request headers." }, + { "name": "postData", "type": "string", "optional": true, "description": "HTTP POST request data." } + ] + }, + { + "id": "Response", + "type": "object", + "description": "HTTP response data.", + "properties": [ + { "name": "url", "type": "string", "description": "Response URL. This URL can be different from CachedResource.url in case of redirect." }, + { "name": "status", "type": "number", "description": "HTTP response status code." }, + { "name": "statusText", "type": "string", "description": "HTTP response status text." }, + { "name": "headers", "$ref": "Headers", "description": "HTTP response headers." }, + { "name": "headersText", "type": "string", "optional": true, "description": "HTTP response headers text." }, + { "name": "mimeType", "type": "string", "description": "Resource mimeType as determined by the browser." }, + { "name": "requestHeaders", "$ref": "Headers", "optional": true, "description": "Refined HTTP request headers that were actually transmitted over the network." }, + { "name": "requestHeadersText", "type": "string", "optional": true, "description": "HTTP request headers text." }, + { "name": "fromDiskCache", "type": "boolean", "optional": true, "description": "Specifies that the request was served from the disk cache." }, + { "name": "timing", "$ref": "ResourceTiming", "optional": true, "description": "Timing information for the given request." } + ] + }, + { + "id": "WebSocketRequest", + "type": "object", + "description": "WebSocket request data.", + "properties": [ + { "name": "headers", "$ref": "Headers", "description": "HTTP response headers." } + ] + }, + { + "id": "WebSocketResponse", + "type": "object", + "description": "WebSocket response data.", + "properties": [ + { "name": "status", "type": "number", "description": "HTTP response status code." }, + { "name": "statusText", "type": "string", "description": "HTTP response status text." }, + { "name": "headers", "$ref": "Headers", "description": "HTTP response headers." } + ] + }, + { + "id": "WebSocketFrame", + "type": "object", + "description": "WebSocket frame data.", + "properties": [ + { "name": "opcode", "type": "number", "description": "WebSocket frame opcode." }, + { "name": "mask", "type": "boolean", "description": "WebSocket frame mask." }, + { "name": "payloadData", "type": "string", "description": "WebSocket frame payload data." } + ] + }, + { + "id": "CachedResource", + "type": "object", + "description": "Information about the cached resource.", + "properties": [ + { "name": "url", "type": "string", "description": "Resource URL. This is the url of the original network request." }, + { "name": "type", "$ref": "Page.ResourceType", "description": "Type of this resource." }, + { "name": "response", "$ref": "Response", "optional": true, "description": "Cached response data." }, + { "name": "bodySize", "type": "number", "description": "Cached response body size." }, + { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with this resource (if any)." } + ] + }, + { + "id": "Initiator", + "type": "object", + "description": "Information about the request initiator.", + "properties": [ + { "name": "type", "type": "string", "enum": ["parser", "script", "other"], "description": "Type of this initiator." }, + { "name": "stackTrace", "type": "array", "items": { "$ref": "Console.CallFrame" }, "optional": true, "description": "Initiator JavaScript stack trace, set for Script only." }, + { "name": "url", "type": "string", "optional": true, "description": "Initiator URL, set for Parser type only." }, + { "name": "lineNumber", "type": "number", "optional": true, "description": "Initiator line number, set for Parser type only." } + ] + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables network tracking, network events will now be delivered to the client." + }, + { + "name": "disable", + "description": "Disables network tracking, prevents network events from being sent to the client." + }, + { + "name": "setExtraHTTPHeaders", + "description": "Specifies whether to always send extra HTTP headers with the requests from this page.", + "parameters": [ + { "name": "headers", "$ref": "Headers", "description": "Map with extra HTTP headers." } + ] + }, + { + "name": "getResponseBody", + "description": "Returns content served for the given request.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Identifier of the network request to get content for." } + ], + "returns": [ + { "name": "body", "type": "string", "description": "Response body." }, + { "name": "base64Encoded", "type": "boolean", "description": "True, if content was sent as base64." } + ] + }, + { + "name": "setCacheDisabled", + "parameters": [ + { "name": "cacheDisabled", "type": "boolean", "description": "Cache disabled state." } + ], + "description": "Toggles ignoring cache for each request. If <code>true</code>, cache will not be used." + }, + { + "name": "loadResource", + "async": true, + "parameters": [ + { "name": "frameId", "$ref": "FrameId", "description": "Frame to load the resource from." }, + { "name": "url", "type": "string", "description": "URL of the resource to load." } + ], + "returns": [ + { "name": "content", "type": "string", "description": "Resource content." }, + { "name": "mimeType", "type": "string", "description": "Resource mimeType." }, + { "name": "status", "type": "number", "description": "HTTP response status code." } + ], + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + } + ], + "events": [ + { + "name": "requestWillBeSent", + "description": "Fired when page is about to send HTTP request.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "frameId", "$ref": "FrameId", "description": "Frame identifier." }, + { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier." }, + { "name": "documentURL", "type": "string", "description": "URL of the document this request is loaded for." }, + { "name": "request", "$ref": "Request", "description": "Request data." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "initiator", "$ref": "Initiator", "description": "Request initiator." }, + { "name": "redirectResponse", "optional": true, "$ref": "Response", "description": "Redirect response data." }, + { "name": "type", "$ref": "Page.ResourceType", "optional": true, "description": "Resource type." }, + { "name": "targetId", "type": "string", "optional": true, "description": "Identifier for the context of where the load originated. In general this is the target identifier. For Workers this will be the workerId." } + ] + }, + { + "name": "requestServedFromCache", + "description": "Fired if request ended up loading from cache.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." } + ] + }, + { + "name": "responseReceived", + "description": "Fired when HTTP response is available.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "frameId", "$ref": "FrameId", "description": "Frame identifier." }, + { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "type", "$ref": "Page.ResourceType", "description": "Resource type." }, + { "name": "response", "$ref": "Response", "description": "Response data." } + ] + }, + { + "name": "dataReceived", + "description": "Fired when data chunk was received over the network.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "dataLength", "type": "integer", "description": "Data chunk length." }, + { "name": "encodedDataLength", "type": "integer", "description": "Actual bytes received (might be less than dataLength for compressed encodings)." } + ] + }, + { + "name": "loadingFinished", + "description": "Fired when HTTP request has finished loading.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with this resource (if any)." } + ] + }, + { + "name": "loadingFailed", + "description": "Fired when HTTP request has failed to load.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "errorText", "type": "string", "description": "User friendly error message." }, + { "name": "canceled", "type": "boolean", "optional": true, "description": "True if loading was canceled." } + ] + }, + { + "name": "requestServedFromMemoryCache", + "description": "Fired when HTTP request has been served from memory cache.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "frameId", "$ref": "FrameId", "description": "Frame identifier." }, + { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier." }, + { "name": "documentURL", "type": "string", "description": "URL of the document this request is loaded for." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "initiator", "$ref": "Initiator", "description": "Request initiator." }, + { "name": "resource", "$ref": "CachedResource", "description": "Cached resource data." } + ] + }, + { + "name": "webSocketWillSendHandshakeRequest", + "description": "Fired when WebSocket is about to initiate handshake.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "request", "$ref": "WebSocketRequest", "description": "WebSocket request data." } + ] + }, + { + "name": "webSocketHandshakeResponseReceived", + "description": "Fired when WebSocket handshake response becomes available.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "response", "$ref": "WebSocketResponse", "description": "WebSocket response data." } + ] + }, + { + "name": "webSocketCreated", + "description": "Fired upon WebSocket creation.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "url", "type": "string", "description": "WebSocket request URL." } + ] + }, + { + "name": "webSocketClosed", + "description": "Fired when WebSocket is closed.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." } + ] + }, + { + "name": "webSocketFrameReceived", + "description": "Fired when WebSocket frame is received.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "response", "$ref": "WebSocketFrame", "description": "WebSocket response data." } + ] + }, + { + "name": "webSocketFrameError", + "description": "Fired when WebSocket frame error occurs.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "errorMessage", "type": "string", "description": "WebSocket frame error message." } + ] + }, + { + "name": "webSocketFrameSent", + "description": "Fired when WebSocket frame is sent.", + "parameters": [ + { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, + { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "response", "$ref": "WebSocketFrame", "description": "WebSocket response data." } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/OverlayTypes.json b/Source/JavaScriptCore/inspector/protocol/OverlayTypes.json new file mode 100644 index 000000000..3a4b01507 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/OverlayTypes.json @@ -0,0 +1,130 @@ +{ + "domain": "OverlayTypes", + "description": "Exposes types to be used by the inspector overlay.", + "types": [ + { + "id": "Point", + "type": "object", + "properties": [ + { "name": "x", "type": "number" }, + { "name": "y", "type": "number" } + ] + }, + { + "id": "Size", + "type": "object", + "properties": [ + { "name": "width", "type": "integer" }, + { "name": "height", "type": "integer" } + ] + }, + { + "id": "Quad", + "description": "A quad is a collection of 4 points. When initialized from a rect, the points are in clockwise order from top left.", + "type": "array", + "items": { "$ref": "Point" } + }, + { + "id": "Rect", + "description": "A rectangle specified by a reference coordinate and width/height offsets.", + "type": "object", + "properties": [ + { "name": "x", "type": "number" }, + { "name": "y", "type": "number" }, + { "name": "width", "type": "number" }, + { "name": "height", "type": "number" } + ] + }, + { + "id": "Region", + "description": "A single region in a flow thread.", + "type": "object", + "properties": [ + { "name": "borderQuad", "$ref": "Quad" }, + { "name": "incomingQuad", "$ref": "Quad" }, + { "name": "outgoingQuad", "$ref": "Quad" }, + { "name": "isHighlighted", "type": "boolean", "optional": true } + ] + }, + { + "id": "DisplayPath", + "description": "A vector path described using SVG path syntax.", + "type": "array", + "items": { "type": "any" } + }, + { + "id": "RegionFlowData", + "type": "object", + "properties": [ + { "name": "regions", "type": "array", "items": { "$ref": "Region"} }, + { "name": "name", "type": "string" } + ] + }, + { + "id": "ContentFlowData", + "type": "object", + "properties": [ + { "name": "name", "type": "string" } + ] + }, + { + "id": "ShapeOutsideData", + "type": "object", + "properties": [ + { "name": "bounds", "$ref": "Quad", "description": "Bounds for the shape-outside paths." }, + { "name": "shape", "$ref": "DisplayPath", "description": "Path for the element's shape.", "optional": true }, + { "name": "marginShape", "$ref": "DisplayPath", "description": "Path for the element's margin shape.", "optional": true } + ] + }, + { + "id": "ElementData", + "description": "Data that describes an element to be highlighted.", + "type": "object", + "properties": [ + { "name": "tagName", "type": "string" }, + { "name": "idValue", "type": "string", "description": "The value of the element's 'id' attribute." }, + { "name": "classes", "type": "array", "items": { "type": "string" }, "optional": true }, + { "name": "size", "$ref": "Size", "optional": true }, + { "name": "role", "type": "string", "description": "Computed accessibility role for the element.", "optional": true }, + { "name": "pseudoElement", "type": "string", "optional": true }, + { "name": "regionFlowData", "$ref": "RegionFlowData", "optional": true }, + { "name": "contentFlowData", "$ref": "ContentFlowData", "optional": true }, + { "name": "shapeOutsideData", "$ref": "ShapeOutsideData", "optional": true } + ] + }, + { + "id": "FragmentHighlightData", + "description": "Data required to highlight multiple quads.", + "type": "object", + "properties": [ + { "name": "quads", "type": "array", "items": { "$ref": "Quad" }, "description": "Quads for which the highlight should be applied."}, + { "name": "contentColor", "type": "string" }, + { "name": "contentOutlineColor", "type": "string" }, + { "name": "paddingColor", "type": "string" }, + { "name": "borderColor", "type": "string" }, + { "name": "marginColor", "type": "string" }, + { "name": "regionClippingArea", "$ref": "Quad", "optional": true } + ] + }, + { + "id": "NodeHighlightData", + "description": "Data required to highlight a DOM node.", + "type": "object", + "properties": [ + { "name": "scrollOffset", "$ref": "Point", "description": "Scroll offset for the MainFrame's FrameView that is shared across all quads." }, + { "name": "fragments", "type": "array", "items": { "$ref": "FragmentHighlightData" } }, + { "name": "elementData", "$ref": "ElementData", "optional": true } + ] + }, + { + "id": "OverlayConfiguration", + "description": "Data required to configure the overlay's size and scaling behavior.", + "type": "object", + "properties": [ + { "name": "deviceScaleFactor", "type": "number" }, + { "name": "viewportSize", "$ref": "Size" }, + { "name": "frameViewFullSize", "$ref": "Size" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Page.json b/Source/JavaScriptCore/inspector/protocol/Page.json new file mode 100644 index 000000000..8df0dbb66 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Page.json @@ -0,0 +1,305 @@ +{ + "domain": "Page", + "description": "Actions and events related to the inspected page belong to the page domain.", + "availability": "web", + "types": [ + { + "id": "ResourceType", + "type": "string", + "enum": ["Document", "Stylesheet", "Image", "Font", "Script", "XHR", "Fetch", "WebSocket", "Other"], + "description": "Resource type as it was perceived by the rendering engine." + }, + { + "id": "CoordinateSystem", + "type": "string", + "enum": ["Viewport", "Page"], + "description": "Coordinate system used by supplied coordinates." + }, + { + "id": "Frame", + "type": "object", + "description": "Information about the Frame on the page.", + "properties": [ + { "name": "id", "type": "string", "description": "Frame unique identifier." }, + { "name": "parentId", "type": "string", "optional": true, "description": "Parent frame identifier." }, + { "name": "loaderId", "$ref": "Network.LoaderId", "description": "Identifier of the loader associated with this frame." }, + { "name": "name", "type": "string", "optional": true, "description": "Frame's name as specified in the tag." }, + { "name": "url", "type": "string", "description": "Frame document's URL." }, + { "name": "securityOrigin", "type": "string", "description": "Frame document's security origin." }, + { "name": "mimeType", "type": "string", "description": "Frame document's mimeType as determined by the browser." } + ] + }, + { + "id": "FrameResource", + "type": "object", + "properties": [ + { "name": "url", "type": "string", "description": "Resource URL." }, + { "name": "type", "$ref": "ResourceType", "description": "Type of this resource." }, + { "name": "mimeType", "type": "string", "description": "Resource mimeType as determined by the browser." }, + { "name": "failed", "type": "boolean", "optional": true, "description": "True if the resource failed to load." }, + { "name": "canceled", "type": "boolean", "optional": true, "description": "True if the resource was canceled during loading." }, + { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with this resource (if any)." }, + { "name": "targetId", "type": "string", "optional": true, "description": "Identifier for the context of where the load originated. In general this is the target identifier. For Workers this will be the workerId." } + ] + }, + { + "id": "FrameResourceTree", + "type": "object", + "description": "Information about the Frame hierarchy along with their cached resources.", + "properties": [ + { "name": "frame", "$ref": "Frame", "description": "Frame information for this tree item." }, + { "name": "childFrames", "type": "array", "optional": true, "items": { "$ref": "FrameResourceTree" }, "description": "Child frames." }, + { "name": "resources", "type": "array", "items": { "$ref": "FrameResource" }, "description": "Information about frame resources." } + ] + }, + { + "id": "SearchResult", + "type": "object", + "description": "Search result for resource.", + "properties": [ + { "name": "url", "type": "string", "description": "Resource URL." }, + { "name": "frameId", "$ref": "Network.FrameId", "description": "Resource frame id." }, + { "name": "matchesCount", "type": "number", "description": "Number of matches in the resource content." }, + { "name": "requestId", "$ref": "Network.RequestId", "optional": true, "description": "Network request id." } + ] + }, + { + "id": "Cookie", + "type": "object", + "description": "Cookie object", + "properties": [ + { "name": "name", "type": "string", "description": "Cookie name." }, + { "name": "value", "type": "string", "description": "Cookie value." }, + { "name": "domain", "type": "string", "description": "Cookie domain." }, + { "name": "path", "type": "string", "description": "Cookie path." }, + { "name": "expires", "type": "number", "description": "Cookie expires." }, + { "name": "size", "type": "integer", "description": "Cookie size." }, + { "name": "httpOnly", "type": "boolean", "description": "True if cookie is http-only." }, + { "name": "secure", "type": "boolean", "description": "True if cookie is secure." }, + { "name": "session", "type": "boolean", "description": "True in case of session cookie." } + ] + }, + { + "id": "ScriptIdentifier", + "type": "string", + "description": "Unique script identifier." + } + ], + "commands": [ + { + "name": "enable", + "description": "Enables page domain notifications." + }, + { + "name": "disable", + "description": "Disables page domain notifications." + }, + { + "name": "addScriptToEvaluateOnLoad", + "parameters": [ + { "name": "scriptSource", "type": "string" } + ], + "returns": [ + { "name": "identifier", "$ref": "ScriptIdentifier", "description": "Identifier of the added script." } + ] + }, + { + "name": "removeScriptToEvaluateOnLoad", + "parameters": [ + { "name": "identifier", "$ref": "ScriptIdentifier" } + ] + }, + { + "name": "reload", + "parameters": [ + { "name": "ignoreCache", "type": "boolean", "optional": true, "description": "If true, browser cache is ignored (as if the user pressed Shift+refresh)." }, + { "name": "scriptToEvaluateOnLoad", "type": "string", "optional": true, "description": "If set, the script will be injected into all frames of the inspected page after reload." } + ], + "description": "Reloads given page optionally ignoring the cache." + }, + { + "name": "navigate", + "parameters": [ + { "name": "url", "type": "string", "description": "URL to navigate the page to." } + ], + "description": "Navigates current page to the given URL." + }, + { + "name": "getCookies", + "returns": [ + { "name": "cookies", "type": "array", "items": { "$ref": "Cookie"}, "description": "Array of cookie objects." } + ], + "description": "Returns all browser cookies. Depending on the backend support, will return detailed cookie information in the <code>cookies</code> field." + }, + { + "name": "deleteCookie", + "parameters": [ + { "name": "cookieName", "type": "string", "description": "Name of the cookie to remove." }, + { "name": "url", "type": "string", "description": "URL to match cooke domain and path." } + ], + "description": "Deletes browser cookie with given name, domain and path." + }, + { + "name": "getResourceTree", + "description": "Returns present frame / resource tree structure.", + "returns": [ + { "name": "frameTree", "$ref": "FrameResourceTree", "description": "Present frame / resource tree structure." } + ] + }, + { + "name": "getResourceContent", + "description": "Returns content of the given resource.", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Frame id to get resource for." }, + { "name": "url", "type": "string", "description": "URL of the resource to get content for." } + ], + "returns": [ + { "name": "content", "type": "string", "description": "Resource content." }, + { "name": "base64Encoded", "type": "boolean", "description": "True, if content was served as base64." } + ] + }, + { + "name": "searchInResource", + "description": "Searches for given string in resource content.", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Frame id for resource to search in." }, + { "name": "url", "type": "string", "description": "URL of the resource to search in." }, + { "name": "query", "type": "string", "description": "String to search for." }, + { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive." }, + { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex." }, + { "name": "requestId", "$ref": "Network.RequestId", "optional": true, "description": "Request id for resource to search in." } + ], + "returns": [ + { "name": "result", "type": "array", "items": { "$ref": "GenericTypes.SearchMatch" }, "description": "List of search matches." } + ] + }, + { + "name": "searchInResources", + "description": "Searches for given string in frame / resource tree structure.", + "parameters": [ + { "name": "text", "type": "string", "description": "String to search for." }, + { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive." }, + { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex." } + ], + "returns": [ + { "name": "result", "type": "array", "items": { "$ref": "SearchResult" }, "description": "List of search results." } + ] + }, + { + "name": "setShowPaintRects", + "description": "Requests that backend shows paint rectangles", + "parameters": [ + { "name": "result", "type": "boolean", "description": "True for showing paint rectangles" } + ] + }, + { + "name": "setEmulatedMedia", + "description": "Emulates the given media for CSS media queries.", + "parameters": [ + { "name": "media", "type": "string", "description": "Media type to emulate. Empty string disables the override." } + ] + }, + { + "name": "getCompositingBordersVisible", + "description": "Indicates the visibility of compositing borders.", + "returns": [ + { "name": "result", "type": "boolean", "description": "If true, compositing borders are visible." } + ] + }, + { + "name": "setCompositingBordersVisible", + "description": "Controls the visibility of compositing borders.", + "parameters": [ + { "name": "visible", "type": "boolean", "description": "True for showing compositing borders." } + ] + }, + { + "name": "snapshotNode", + "description": "Capture a snapshot of the specified node that does not include unrelated layers.", + "parameters": [ + { "name": "nodeId", "$ref": "DOM.NodeId", "description": "Id of the node to snapshot." } + ], + "returns": [ + { "name": "dataURL", "type": "string", "description": "Base64-encoded image data (PNG)." } + ] + }, + { + "name": "snapshotRect", + "description": "Capture a snapshot of the page within the specified rectangle and coordinate system.", + "parameters": [ + { "name": "x", "type": "integer", "description": "X coordinate" }, + { "name": "y", "type": "integer", "description": "Y coordinate" }, + { "name": "width", "type": "integer", "description": "Rectangle width" }, + { "name": "height", "type": "integer", "description": "Rectangle height" }, + { "name": "coordinateSystem", "$ref": "CoordinateSystem", "description": "Indicates the coordinate system of the supplied rectangle." } + ], + "returns": [ + { "name": "dataURL", "type": "string", "description": "Base64-encoded image data (PNG)." } + ] + }, + { + "name": "archive", + "description": "Grab an archive of the page.", + "returns": [ + { "name": "data", "type": "string", "description": "Base64-encoded web archive." } + ] + } + ], + "events": [ + { + "name": "domContentEventFired", + "parameters": [ + { "name": "timestamp", "type": "number" } + ] + }, + { + "name": "loadEventFired", + "parameters": [ + { "name": "timestamp", "type": "number" } + ] + }, + { + "name": "frameNavigated", + "description": "Fired once navigation of the frame has completed. Frame is now associated with the new loader.", + "parameters": [ + { "name": "frame", "$ref": "Frame", "description": "Frame object." } + ] + }, + { + "name": "frameDetached", + "description": "Fired when frame has been detached from its parent.", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Id of the frame that has been detached." } + ] + }, + { + "name": "frameStartedLoading", + "description": "Fired when frame has started loading.", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Id of the frame that has started loading." } + ] + }, + { + "name": "frameStoppedLoading", + "description": "Fired when frame has stopped loading.", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Id of the frame that has stopped loading." } + ] + }, + { + "name": "frameScheduledNavigation", + "description": "Fired when frame schedules a potential navigation.", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Id of the frame that has scheduled a navigation." }, + { "name": "delay", "type": "number", "description": "Delay (in seconds) until the navigation is scheduled to begin. The navigation is not guaranteed to start." } + ] + }, + { + "name": "frameClearedScheduledNavigation", + "description": "Fired when frame no longer has a scheduled navigation.", + "parameters": [ + { "name": "frameId", "$ref": "Network.FrameId", "description": "Id of the frame that has cleared its scheduled navigation." } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Replay.json b/Source/JavaScriptCore/inspector/protocol/Replay.json new file mode 100644 index 000000000..7bc26bda7 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Replay.json @@ -0,0 +1,264 @@ +{ + "domain": "Replay", + "description": "Controls web replay, and manages recording sessions and segments.", + "featureGuard": "ENABLE(WEB_REPLAY)", + "availability": "web", + "types": [ + { + "id": "SessionIdentifier", "description": "Unique replay session identifier.", + "type": "integer" + }, + { + "id": "SegmentIdentifier", "description": "Unique session segment identifier.", + "type": "integer" + }, + { + "id": "SessionState", "description": "State machine's state for the session.", + "type": "string", + "enum": ["Capturing", "Inactive", "Replaying"] + }, + { + "id": "SegmentState", "description": "State machine's state for the session segment.", + "type": "string", + "enum": ["Appending", "Unloaded", "Loaded", "Dispatching"] + }, + { + "id": "ReplayPosition", + "type": "object", + "properties": [ + { "name": "segmentOffset", "type": "integer", "description": "Offset for a segment within the currently-loaded replay session." }, + { "name": "inputOffset", "type": "integer", "description": "Offset for an event loop input within the specified session segment." } + ] + }, + { + "id": "ReplayInput", + "type": "object", + "properties": [ + { "name": "type", "type": "string", "description": "Input type." }, + { "name": "offset", "type": "integer", "description": "Offset of this input in its respective queue."}, + { "name": "data", "type": "object", "description": "Per-input payload." } + ] + }, + { + "id": "ReplayInputQueue", + "type": "object", + "properties": [ + { "name": "type", "type": "string", "description": "Queue type" }, + { "name": "inputs", "type": "array", "items": { "$ref": "ReplayInput"}, "description": "Inputs belonging to this queue." } + ] + }, + { + "id": "SessionSegment", "description": "A standalone segment of a replay session that corresponds to a single main frame navigation and execution.", + "type": "object", + "properties": [ + { "name": "id", "$ref": "SegmentIdentifier", "description": "Unique session segment identifier." }, + { "name": "timestamp", "type": "number", "description": "Start time of the segment, in milliseconds since the epoch." }, + { "name": "queues", "type": "array", "items": { "$ref": "ReplayInputQueue"} } + ] + }, + { + "id": "ReplaySession", "description": "An ordered collection of replay session segments.", + "type": "object", + "properties": [ + { "name": "id", "$ref": "SessionIdentifier", "description": "Unique replay session identifier." }, + { "name": "timestamp", "type": "number", "description": "Creation time of session, in milliseconds since the epoch." }, + { "name": "segments", "type": "array", "items": { "$ref": "SegmentIdentifier" }, "description": "An ordered list identifiers for the segments that comprise this replay session." } + ] + } + ], + "commands": [ + { + "name": "startCapturing", + "description": "Starts capture of a new replay session." + }, + { + "name": "stopCapturing", + "description": "Stops capture of the currently recording replay session." + }, + { + "name": "replayToPosition", + "description": "Seek execution to a specific position within the replay session.", + "parameters": [ + { "name": "position", "$ref": "ReplayPosition" }, + { "name": "shouldFastForward", "type": "boolean" } + ] + }, + { + "name": "replayToCompletion", + "description": "Replay all session segments completely.", + "parameters": [ + { "name": "shouldFastForward", "type": "boolean" } + ] + }, + { + "name": "pausePlayback", + "description": "Pauses playback in the current segment. Can be resumed by using a replay command." + }, + { + "name": "cancelPlayback", + "description": "Cancels playback of the current segment. Further replaying will start from the beginning of the current segment." + }, + { + "name": "switchSession", + "description": "Unloads the current replay session and loads the specified session", + "parameters": [ + { "name": "sessionIdentifier", "$ref": "SessionIdentifier" } + ] + }, + { + "name": "insertSessionSegment", + "description": "Splices the specified session segment into the session at the specified index.", + "parameters": [ + { "name": "sessionIdentifier", "$ref": "SessionIdentifier" }, + { "name": "segmentIdentifier", "$ref": "SegmentIdentifier" }, + { "name": "segmentIndex", "type": "integer" } + ] + }, + { + "name": "removeSessionSegment", + "description": "Removes the session segment at the specified position from the session.", + "parameters": [ + { "name": "sessionIdentifier", "$ref": "SessionIdentifier" }, + { "name": "segmentIndex", "type": "integer" } + ] + }, + { + "name": "currentReplayState", + "description": "Returns the identifier, position, session state and segment state of the currently loaded session. This is necessary because the inspector may be closed and reopened in the middle of replay.", + "returns": [ + { "name": "sessionIdentifier", "$ref": "SessionIdentifier" }, + { "name": "segmentIdentifier", "$ref": "SegmentIdentifier", "optional": true, "description": "If no segment is currently loaded, then there is no valid segment identifier." }, + { "name": "sessionState", "$ref": "SessionState" }, + { "name": "segmentState", "$ref": "SegmentState" }, + { "name": "replayPosition", "$ref": "ReplayPosition" } + ] + }, + { + "name": "getAvailableSessions", + "description": "Returns identifiers of all available sessions.", + "returns": [ + { "name": "ids", "type": "array", "items": { "$ref": "SessionIdentifier" } } + ] + }, + { + "name": "getSessionData", + "description": "Returns an object for the specified session.", + "parameters": [ + { "name": "sessionIdentifier", "$ref": "SessionIdentifier" } + ], + "returns": [ + { "name": "session", "$ref": "ReplaySession", "optional": true, "description": "The requested serialized replay session." } + ] + }, + { + "name": "getSegmentData", + "description": "Returns an object for the specified session segment.", + "parameters": [ + { "name": "id", "$ref": "SegmentIdentifier" } + ], + "returns": [ + { "name": "segment", "$ref": "SessionSegment", "optional": true, "description": "The requested serialized session segment." } + ] + } + ], + "events": [ + { + "name": "captureStarted", + "description": "Fired when capture has started." + }, + { + "name": "captureStopped", + "description": "Fired when capture has stopped." + }, + { + "name": "playbackHitPosition", + "description": "Playback within the session has progressed up to this position, and is about to replay the input at the specified offset.", + "parameters": [ + { "name": "position", "$ref": "ReplayPosition", "description": "The playback position that was hit." }, + { "name": "timestamp", "type": "number", "description": "A timestamp for the event." } + ] + }, + { + "name": "playbackStarted", + "description": "Fired when session playback has started." + }, + { + "name": "playbackPaused", + "description": "Fired when session playback has paused, but not finished.", + "parameters": [ + { "name": "position", "$ref": "ReplayPosition", "description": "The playback position immediately prior to where playback is paused." } + ] + }, + { + "name": "playbackFinished", + "description": "Fired when session playback has stopped." + }, + { + "name": "inputSuppressionChanged", + "description": "Fired when the replay controller starts or stops suppressing user inputs.", + "parameters": [ + { "name": "willSuppress", "type": "boolean", "description": "Whether user inputs will be suppressed during playback." } + ] + }, + { + "name": "sessionCreated", + "description": "Fired when a new replay session is created", + "parameters": [ + { "name": "id", "$ref": "SessionIdentifier", "description": "Identifier for the created session." } + ] + }, + { + "name": "sessionModified", + "description": "Fired when a session's segments have changed.", + "parameters": [ + { "name": "id", "$ref": "SessionIdentifier", "description": "Identifier for the session the segment was added to." } + ] + }, + { + "name": "sessionRemoved", + "description": "Fired when a replay session is removed and can no longer be loaded.", + "parameters": [ + { "name": "id", "$ref": "SessionIdentifier", "description": "Identifier for the removed session." } + ] + }, + { + "name": "sessionLoaded", + "description": "Fired when a replay session is loaded.", + "parameters": [ + { "name": "id", "$ref": "SessionIdentifier", "description": "Identifier for the loaded session." } + ] + }, + { + "name": "segmentCreated", + "description": "Fired when a new session segment is created.", + "parameters": [ + { "name": "id", "$ref": "SegmentIdentifier", "description": "Identifier for the created session segment." } + ] + }, + { + "name": "segmentRemoved", + "description": "Fired when a session segment is removed and can no longer be replayed as part of a session.", + "parameters": [ + { "name": "id", "$ref": "SegmentIdentifier", "description": "Identifier for the removed session segment." } + ] + }, + { + "name": "segmentCompleted", + "description": "Fired when a session segment is completed and can no longer have inputs added to it.", + "parameters": [ + { "name": "id", "$ref": "SegmentIdentifier", "description": "Identifier for the completed session segment." } + ] + }, + { + "name": "segmentLoaded", + "description": "Fired when a segment is loaded.", + "parameters": [ + { "name": "segmentIdentifier", "$ref": "SegmentIdentifier", "description": "Id for the loaded segment." } + ] + }, + { + "name": "segmentUnloaded", + "description": "Fired when a segment is unloaded." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Runtime.json b/Source/JavaScriptCore/inspector/protocol/Runtime.json index f7bf133b4..c41693c79 100644 --- a/Source/JavaScriptCore/inspector/protocol/Runtime.json +++ b/Source/JavaScriptCore/inspector/protocol/Runtime.json @@ -1,6 +1,7 @@ { "domain": "Runtime", "description": "Runtime domain exposes JavaScript runtime by means of remote evaluation and mirror objects. Evaluation results are returned as mirror object that expose object type, string representation and unique identifier that can be used for further object reference. Original objects are maintained in memory unless they are either explicitly released or are released along with the other objects in their object group.", + "workerSupported": true, "types": [ { "id": "RemoteObjectId", @@ -12,13 +13,15 @@ "type": "object", "description": "Mirror object referencing original JavaScript object.", "properties": [ - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean"], "description": "Object type." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date"], "description": "Object subtype hint. Specified for <code>object</code> type values only." }, + { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol"], "description": "Object type." }, + { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "error", "map", "set", "weakmap", "weakset", "iterator", "class", "proxy"], "description": "Object subtype hint. Specified for <code>object</code> <code>function</code> (for class) type values only." }, { "name": "className", "type": "string", "optional": true, "description": "Object class (constructor) name. Specified for <code>object</code> type values only." }, { "name": "value", "type": "any", "optional": true, "description": "Remote object value (in case of primitive values or JSON values if it was requested)." }, { "name": "description", "type": "string", "optional": true, "description": "String representation of the object." }, { "name": "objectId", "$ref": "RemoteObjectId", "optional": true, "description": "Unique object identifier (for non-primitive values)." }, - { "name": "preview", "$ref": "ObjectPreview", "optional": true, "description": "Preview containsing abbreviated property values." } + { "name": "size", "type": "integer", "optional": true, "description": "Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only." }, + { "name": "classPrototype", "$ref": "RemoteObject", "optional": true, "description": "Remote object for the class prototype. Specified for class object type values only." }, + { "name": "preview", "$ref": "ObjectPreview", "optional": true, "description": "Preview containing abbreviated property values. Specified for <code>object</code> type values only." } ] }, { @@ -26,9 +29,14 @@ "type": "object", "description": "Object containing abbreviated remote object value.", "properties": [ + { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol"], "description": "Object type." }, + { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "error", "map", "set", "weakmap", "weakset", "iterator", "class", "proxy"], "description": "Object subtype hint. Specified for <code>object</code> type values only." }, + { "name": "description", "type": "string", "optional": true, "description": "String representation of the object." }, { "name": "lossless", "type": "boolean", "description": "Determines whether preview is lossless (contains all information of the original object)." }, - { "name": "overflow", "type": "boolean", "description": "True iff some of the properties of the original did not fit." }, - { "name": "properties", "type": "array", "items": { "$ref": "PropertyPreview" }, "description": "List of the properties." } + { "name": "overflow", "type": "boolean", "optional": true, "description": "True iff some of the properties of the original did not fit." }, + { "name": "properties", "type": "array", "items": { "$ref": "PropertyPreview" }, "optional": true, "description": "List of the properties." }, + { "name": "entries", "type": "array", "items": { "$ref": "EntryPreview" }, "optional": true, "description": "List of the entries. Specified for <code>map</code> and <code>set</code> subtype values only." }, + { "name": "size", "type": "integer", "optional": true, "description": "Size of the array/collection. Specified for array/map/set/weakmap/weakset object type values only." } ] }, { @@ -36,10 +44,27 @@ "type": "object", "properties": [ { "name": "name", "type": "string", "description": "Property name." }, - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean"], "description": "Object type." }, + { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol", "accessor"], "description": "Object type." }, + { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "error", "map", "set", "weakmap", "weakset", "iterator", "class", "proxy"], "description": "Object subtype hint. Specified for <code>object</code> type values only." }, { "name": "value", "type": "string", "optional": true, "description": "User-friendly property value string." }, { "name": "valuePreview", "$ref": "ObjectPreview", "optional": true, "description": "Nested value preview." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date"], "description": "Object subtype hint. Specified for <code>object</code> type values only." } + { "name": "internal", "type": "boolean", "optional": true, "description": "True if this is an internal property." } + ] + }, + { + "id": "EntryPreview", + "type": "object", + "properties": [ + { "name": "key", "$ref": "ObjectPreview", "optional": true, "description": "Entry key. Specified for map-like collection entries." }, + { "name": "value", "$ref": "ObjectPreview", "description": "Entry value." } + ] + }, + { + "id": "CollectionEntry", + "type": "object", + "properties": [ + { "name": "key", "$ref": "Runtime.RemoteObject", "optional": true, "description": "Entry key of a map-like collection, otherwise not provided." }, + { "name": "value", "$ref": "Runtime.RemoteObject", "description": "Entry value." } ] }, { @@ -47,7 +72,7 @@ "type": "object", "description": "Object property descriptor.", "properties": [ - { "name": "name", "type": "string", "description": "Property name." }, + { "name": "name", "type": "string", "description": "Property name or symbol description." }, { "name": "value", "$ref": "RemoteObject", "optional": true, "description": "The value associated with the property." }, { "name": "writable", "type": "boolean", "optional": true, "description": "True if the value associated with the property may be changed (data descriptors only)." }, { "name": "get", "$ref": "RemoteObject", "optional": true, "description": "A function which serves as a getter for the property, or <code>undefined</code> if there is no getter (accessor descriptors only)." }, @@ -55,7 +80,9 @@ { "name": "configurable", "type": "boolean", "description": "True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object." }, { "name": "enumerable", "type": "boolean", "description": "True if this property shows up during enumeration of the properties on the corresponding object." }, { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation." }, - { "name": "isOwn", "optional": true, "type": "boolean", "description": "True if the property is owned for the object." } + { "name": "isOwn", "optional": true, "type": "boolean", "description": "True if the property is owned for the object." }, + { "name": "symbol", "optional": true, "$ref": "Runtime.RemoteObject", "description": "Property symbol object, if the property is a symbol." }, + { "name": "nativeGetter", "optional": true, "type": "boolean", "description": "True if the property value came from a native getter." } ] }, { @@ -82,11 +109,6 @@ "description": "Id of an execution context." }, { - "id": "RuntimeFrameId", - "type": "string", - "description": "Unique frame identifier. FIXME: Duplicate of Network.FrameId <https://webkit.org/b/125664> Web Inspector: FIX Type Dependency Issues" - }, - { "id": "ExecutionContextDescription", "type": "object", "description": "Description of an isolated world.", @@ -94,7 +116,7 @@ { "name": "id", "$ref": "ExecutionContextId", "description": "Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed." }, { "name": "isPageContext", "type": "boolean", "description": "True if this is a context where inpspected web page scripts run. False if it is a content script isolated context." }, { "name": "name", "type": "string", "description": "Human readable name describing given context."}, - { "name": "frameId", "$ref": "RuntimeFrameId", "description": "Id of the owning frame." } + { "name": "frameId", "$ref": "Network.FrameId", "description": "Id of the owning frame." } ] }, { @@ -111,6 +133,65 @@ { "name": "startOffset", "type": "integer", "description": "Start offset of range (inclusive)." }, { "name": "endOffset", "type": "integer", "description": "End offset of range (exclusive)." } ] + }, + { + "id": "StructureDescription", + "type": "object", + "properties": [ + { "name": "fields", "type": "array", "items": { "type": "string" }, "optional": true, "description": "Array of strings, where the strings represent object properties." }, + { "name": "optionalFields", "type": "array", "items": { "type": "string" }, "optional": true, "description": "Array of strings, where the strings represent optional object properties." }, + { "name": "constructorName", "type": "string", "optional": true, "description": "Name of the constructor." }, + { "name": "prototypeStructure", "$ref": "StructureDescription", "optional": true, "description": "Pointer to the StructureRepresentation of the protoype if one exists." }, + { "name": "isImprecise", "type": "boolean", "optional": true, "description": "If true, it indicates that the fields in this StructureDescription may be inaccurate. I.e, there might have been fields that have been deleted before it was profiled or it has fields we haven't profiled." } + ] + }, + { + "id": "TypeSet", + "type": "object", + "properties": [ + { "name": "isFunction", "type": "boolean", "description": "Indicates if this type description has been type Function." }, + { "name": "isUndefined", "type": "boolean", "description": "Indicates if this type description has been type Undefined." }, + { "name": "isNull", "type": "boolean", "description": "Indicates if this type description has been type Null." }, + { "name": "isBoolean", "type": "boolean", "description": "Indicates if this type description has been type Boolean." }, + { "name": "isInteger", "type": "boolean", "description": "Indicates if this type description has been type Integer." }, + { "name": "isNumber", "type": "boolean", "description": "Indicates if this type description has been type Number." }, + { "name": "isString", "type": "boolean", "description": "Indicates if this type description has been type String." }, + { "name": "isObject", "type": "boolean", "description": "Indicates if this type description has been type Object." }, + { "name": "isSymbol", "type": "boolean", "description": "Indicates if this type description has been type Symbol." } + ] + }, + { + "id": "TypeDescription", + "type": "object", + "description": "Container for type information that has been gathered.", + "properties": [ + { "name": "isValid", "type": "boolean", "description": "If true, we were able to correlate the offset successfuly with a program location. If false, the offset may be bogus or the offset may be from a CodeBlock that hasn't executed." }, + { "name": "leastCommonAncestor", "type": "string", "optional": true, "description": "Least common ancestor of all Constructors if the TypeDescription has seen any structures. This string is the display name of the shared constructor function." }, + { "name": "typeSet", "$ref": "TypeSet", "optional": true, "description": "Set of booleans for determining the aggregate type of this type description." }, + { "name": "structures", "type": "array", "items": { "$ref": "StructureDescription" }, "optional": true, "description": "Array of descriptions for all structures seen for this variable." }, + { "name": "isTruncated", "type": "boolean", "optional": true, "description": "If true, this indicates that no more structures are being profiled because some maximum threshold has been reached and profiling has stopped because of memory pressure." } + ] + }, + { + "id": "TypeLocation", + "type": "object", + "description": "Describes the location of an expression we want type information for.", + "properties": [ + { "name": "typeInformationDescriptor", "type": "integer", "description": "What kind of type information do we want (normal, function return values, 'this' statement)." }, + { "name": "sourceID", "type": "string", "description": "sourceID uniquely identifying a script" }, + { "name": "divot", "type": "integer", "description": "character offset for assignment range" } + ] + }, + { + "id": "BasicBlock", + "type": "object", + "description": "From Wikipedia: a basic block is a portion of the code within a program with only one entry point and only one exit point. This type gives the location of a basic block and if that basic block has executed.", + "properties": [ + { "name": "startOffset", "type": "integer", "description": "Start offset of the basic block." }, + { "name": "endOffset", "type": "integer", "description": "End offset of the basic block." }, + { "name": "hasExecuted", "type": "boolean", "description": "Indicates if the basic block has executed before." }, + { "name": "executionCount", "type": "integer", "description": "Indicates how many times the basic block has executed." } + ] } ], "commands": [ @@ -135,11 +216,13 @@ { "name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true, "description": "Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state." }, { "name": "contextId", "$ref": "Runtime.ExecutionContextId", "optional": true, "description": "Specifies in which isolated context to perform evaluation. Each content script lives in an isolated context and this parameter may be used to specify one of those contexts. If the parameter is omitted or 0 the evaluation will be performed in the context of the inspected page." }, { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." } + { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." }, + { "name": "saveResult", "type": "boolean", "optional": true, "description": "Whether the resulting value should be considered for saving in the $n history." } ], "returns": [ { "name": "result", "$ref": "RemoteObject", "description": "Evaluation result." }, - { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation." } + { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation." }, + { "name": "savedResultIndex", "type": "integer", "optional": true, "description": "If the result was saved, this is the $n index that can be used to access the value." } ], "description": "Evaluates expression on global object." }, @@ -163,7 +246,8 @@ "name": "getProperties", "parameters": [ { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to return properties for." }, - { "name": "ownProperties", "optional": true, "type": "boolean", "description": "If true, returns properties belonging only to the element itself, not to its prototype chain." } + { "name": "ownProperties", "optional": true, "type": "boolean", "description": "If true, returns properties belonging only to the object itself, not to its prototype chain." }, + { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for property values." } ], "returns": [ { "name": "result", "type": "array", "items": { "$ref": "PropertyDescriptor"}, "description": "Object properties." }, @@ -172,6 +256,42 @@ "description": "Returns properties of a given object. Object group of the result is inherited from the target object." }, { + "name": "getDisplayableProperties", + "parameters": [ + { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to return properties for." }, + { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for property values." } + ], + "returns": [ + { "name": "properties", "type": "array", "items": { "$ref": "PropertyDescriptor"}, "description": "Object properties." }, + { "name": "internalProperties", "optional": true, "type": "array", "items": { "$ref": "InternalPropertyDescriptor"}, "description": "Internal object properties." } + ], + "description": "Returns displayable properties of a given object. Object group of the result is inherited from the target object. Displayable properties are own properties, internal properties, and native getters in the prototype chain (assumed to be bindings and treated like own properties for the frontend)." + }, + { + "name": "getCollectionEntries", + "description": "Returns entries of given Map / Set collection.", + "parameters": [ + { "name": "objectId", "$ref": "Runtime.RemoteObjectId", "description": "Id of the collection to get entries for." }, + { "name": "objectGroup", "optional": true, "type": "string", "description": "Symbolic group name that can be used to release multiple. If not provided, it will be the same objectGroup as the RemoteObject determined from <code>objectId</code>. This is useful for WeakMap to release the collection entries." }, + { "name": "startIndex", "optional": true, "type": "integer", "description": "If provided skip to this index before collecting values. Otherwise, 0." }, + { "name": "numberToFetch", "optional": true, "type": "integer", "description": "If provided only return <code>numberToFetch</code> values. Otherwise, return values all the way to the end." } + ], + "returns": [ + { "name": "entries", "type": "array", "items": { "$ref": "CollectionEntry" }, "description": "Array of collection entries." } + ] + }, + { + "name": "saveResult", + "parameters": [ + { "name": "value", "$ref": "CallArgument", "description": "Id or value of the object to save." }, + { "name": "contextId", "optional": true, "$ref": "ExecutionContextId", "description": "Unique id of the execution context. To specify in which execution context script evaluation should be performed. If not provided, determine from the CallArgument's objectId." } + ], + "returns": [ + { "name": "savedResultIndex", "type": "integer", "optional": true, "description": "If the value was saved, this is the $n index that can be used to access the value." } + ], + "description": "Assign a saved result index to this value." + }, + { "name": "releaseObject", "parameters": [ { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to release." } @@ -186,16 +306,48 @@ "description": "Releases all remote objects that belong to a given group." }, { - "name": "run", - "description": "Tells inspected instance(worker or page) that it can run in case it was started paused." - }, - { "name": "enable", "description": "Enables reporting of execution contexts creation by means of <code>executionContextCreated</code> event. When the reporting gets enabled the event will be sent immediately for each existing execution context." }, { "name": "disable", "description": "Disables reporting of execution contexts creation." + }, + { + "name": "getRuntimeTypesForVariablesAtOffsets", + "parameters": [ + { "name": "locations", "type": "array", "items": { "$ref": "TypeLocation" }, "description": "An array of type locations we're requesting information for. Results are expected in the same order they're sent in."} + ], + "returns": [ + { "name": "types", "type": "array", "items": { "$ref": "TypeDescription", "description": "Types for requested variable." } } + ], + "description": "Returns detailed informtation on given function." + }, + { + "name": "enableTypeProfiler", + "description": "Enables type profiling on the VM." + }, + { + "name": "disableTypeProfiler", + "description": "Disables type profiling on the VM." + }, + { + "name": "enableControlFlowProfiler", + "description": "Enables control flow profiling on the VM." + }, + { + "name": "disableControlFlowProfiler", + "description": "Disables control flow profiling on the VM." + }, + { + "name": "getBasicBlocks", + "parameters": [ + { "name": "sourceID", "type": "string", "description": "Indicates which sourceID information is requested for." } + ], + "returns": [ + { "name": "basicBlocks", "type": "array", "items": { "$ref": "BasicBlock", "description": "Array of basic blocks." } } + ], + "description": "Returns a list of basic blocks for the given sourceID with information about their text ranges and whether or not they have executed." } ], "events": [ diff --git a/Source/JavaScriptCore/inspector/protocol/ScriptProfiler.json b/Source/JavaScriptCore/inspector/protocol/ScriptProfiler.json new file mode 100644 index 000000000..d01258dd5 --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/ScriptProfiler.json @@ -0,0 +1,99 @@ +{ + "domain": "ScriptProfiler", + "description": "Profiler domain exposes JavaScript evaluation timing and profiling.", + "types": [ + { + "id": "EventType", + "type": "string", + "enum": ["API", "Microtask", "Other"] + }, + { + "id": "Event", + "type": "object", + "properties": [ + { "name": "startTime", "type": "number" }, + { "name": "endTime", "type": "number" }, + { "name": "type", "$ref": "EventType" } + ] + }, + { + "id": "ExpressionLocation", + "type": "object", + "properties": [ + { "name": "line", "type": "integer", "description": "1-based." }, + { "name": "column", "type": "integer", "description": "1-based." } + ] + }, + { + "id": "StackFrame", + "type": "object", + "properties": [ + { "name": "sourceID", "$ref": "Debugger.ScriptId", "description": "Unique script identifier." }, + { "name": "name", "type": "string", "description": "A displayable name for the stack frame. i.e function name, (program), etc." }, + { "name": "line", "type": "integer", "description": "-1 if unavailable. 1-based if available." }, + { "name": "column", "type": "integer", "description": "-1 if unavailable. 1-based if available." }, + { "name": "url", "type": "string" }, + { "name": "expressionLocation", "$ref": "ExpressionLocation", "optional": true } + ] + }, + { + "id": "StackTrace", + "type": "object", + "properties": [ + { "name": "timestamp", "type": "number" }, + { "name": "stackFrames", "type": "array", "items": { "$ref": "StackFrame" }, "description": "First array item is the bottom of the call stack and last array item is the top of the call stack." } + ] + }, + { + "id": "Samples", + "type": "object", + "properties": [ + { "name": "stackTraces", "type": "array", "items": { "$ref": "StackTrace" } } + ] + } + ], + "commands": [ + { + "name": "startTracking", + "description": "Start tracking script evaluations.", + "parameters": [ + { "name": "includeSamples", "type": "boolean", "optional": true, "description": "Start the sampling profiler, defaults to false." } + ] + }, + { + "name": "stopTracking", + "description": "Stop tracking script evaluations. This will produce a `trackingComplete` event." + } + ], + "events": [ + { + "name": "trackingStart", + "description": "Tracking started.", + "parameters": [ + { "name": "timestamp", "type": "number" } + ] + }, + { + "name": "trackingUpdate", + "description": "Periodic tracking updates with event data.", + "parameters": [ + { "name": "event", "$ref": "Event" } + ] + }, + { + "name": "trackingComplete", + "description": "Tracking stopped. Includes any buffered data during tracking, such as profiling information.", + "parameters": [ + { "name": "samples", "$ref": "Samples", "optional": true, "description": "Stack traces." } + ] + }, + { + "name": "programmaticCaptureStarted", + "description": "Fired when programmatic capture starts (console.profile). JSContext inspection only." + }, + { + "name": "programmaticCaptureStopped", + "description": "Fired when programmatic capture stops (console.profileEnd). JSContext inspection only." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Timeline.json b/Source/JavaScriptCore/inspector/protocol/Timeline.json new file mode 100644 index 000000000..77396756d --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Timeline.json @@ -0,0 +1,118 @@ +{ + "domain": "Timeline", + "description": "Timeline provides its clients with instrumentation records that are generated during the page runtime. Timeline instrumentation can be started and stopped using corresponding commands. While timeline is started, it is generating timeline event records.", + "availability": "web", + "types": [ + { + "id": "EventType", + "type": "string", + "description": "Timeline record type.", + "enum": [ + "EventDispatch", + "ScheduleStyleRecalculation", + "RecalculateStyles", + "InvalidateLayout", + "Layout", + "Paint", + "Composite", + "RenderingFrame", + "TimerInstall", + "TimerRemove", + "TimerFire", + "EvaluateScript", + "TimeStamp", + "Time", + "TimeEnd", + "FunctionCall", + "ProbeSample", + "ConsoleProfile", + "RequestAnimationFrame", + "CancelAnimationFrame", + "FireAnimationFrame" + ] + }, + { + "id": "Instrument", + "type": "string", + "description": "Instrument types.", + "enum": [ + "ScriptProfiler", + "Timeline", + "Memory", + "Heap" + ] + }, + { + "id": "TimelineEvent", + "type": "object", + "description": "Timeline record contains information about the recorded activity.", + "properties": [ + { "name": "type", "$ref": "EventType", "description": "Event type." }, + { "name": "data", "type": "object", "description": "Event data." }, + { "name": "children", "type": "array", "optional": true, "items": { "$ref": "TimelineEvent" }, "description": "Nested records." } + ] + } + ], + "commands": [ + { + "name": "start", + "description": "Starts capturing instrumentation events.", + "parameters": [ + { "name": "maxCallStackDepth", "optional": true, "type": "integer", "description": "Samples JavaScript stack traces up to <code>maxCallStackDepth</code>, defaults to 5." } + ] + }, + { + "name": "stop", + "description": "Stops capturing instrumentation events." + }, + { + "name": "setAutoCaptureEnabled", + "description": "Toggle auto capture state. If <code>true</code> the backend will disable breakpoints and start capturing on navigation. The backend will fire the <code>autoCaptureStarted</code> event when an auto capture starts. The frontend should stop the auto capture when appropriate and re-enable breakpoints.", + "parameters": [ + { "name": "enabled", "type": "boolean", "description": "New auto capture state." } + ] + }, + { + "name": "setInstruments", + "description": "Instruments to enable when capture starts on the backend (e.g. auto capture or programmatic capture).", + "parameters": [ + { "name": "instruments", "type": "array", "items": { "$ref": "Instrument" }, "description": "Instruments to enable." } + ] + } + ], + "events": [ + { + "name": "eventRecorded", + "description": "Fired for every instrumentation event while timeline is started.", + "parameters": [ + { "name": "record", "$ref": "TimelineEvent", "description": "Timeline event record data." } + ] + }, + { + "name": "recordingStarted", + "description": "Fired when recording has started.", + "parameters": [ + { "name": "startTime", "type": "number", "description": "Start time of this new recording." } + ] + }, + { + "name": "recordingStopped", + "description": "Fired when recording has stopped.", + "parameters": [ + { "name": "endTime", "type": "number", "description": "End time of this recording." } + ] + }, + { + "name": "autoCaptureStarted", + "description": "Fired when auto capture started." + }, + { + "name": "programmaticCaptureStarted", + "description": "Fired when programmatic capture starts (console.profile)." + }, + { + "name": "programmaticCaptureStopped", + "description": "Fired when programmatic capture stops (console.profileEnd)." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/protocol/Worker.json b/Source/JavaScriptCore/inspector/protocol/Worker.json new file mode 100644 index 000000000..a57fac08f --- /dev/null +++ b/Source/JavaScriptCore/inspector/protocol/Worker.json @@ -0,0 +1,52 @@ +{ + "domain": "Worker", + "availability": "web", + "types": [], + "commands": [ + { + "name": "enable", + "description": "Enable Worker domain events." + }, + { + "name": "disable", + "description": "Disable Worker domain events." + }, + { + "name": "initialized", + "description": "Sent after the frontend has sent all initialization messages and can resume this worker. This command is required to allow execution in the worker.", + "parameters": [ + { "name": "workerId", "type": "string" } + ] + }, + { + "name": "sendMessageToWorker", + "description": "Send an Inspector Protocol message to be dispatched to a Worker's agents.", + "parameters": [ + { "name": "workerId", "type": "string" }, + { "name": "message", "type": "string", "description": "JSON Inspector Protocol message (command) to be dispatched on the backend." } + ] + } + ], + "events": [ + { + "name": "workerCreated", + "parameters": [ + { "name": "workerId", "type": "string" }, + { "name": "url", "type": "string" } + ] + }, + { + "name": "workerTerminated", + "parameters": [ + { "name": "workerId", "type": "string" } + ] + }, + { + "name": "dispatchMessageFromWorker", + "parameters": [ + { "name": "workerId", "type": "string" }, + { "name": "message", "type": "string", "description": "JSON Inspector Protocol message (response or event) to be dispatched on the frontend." } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/remote/RemoteAutomationTarget.cpp b/Source/JavaScriptCore/inspector/remote/RemoteAutomationTarget.cpp new file mode 100644 index 000000000..565218c69 --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteAutomationTarget.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2015, 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "RemoteAutomationTarget.h" + +#if ENABLE(REMOTE_INSPECTOR) + +#include "RemoteInspector.h" + +namespace Inspector { + +void RemoteAutomationTarget::setIsPaired(bool paired) +{ + if (m_paired == paired) + return; + + m_paired = paired; + + update(); +} + +} // namespace Inspector + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteAutomationTarget.h b/Source/JavaScriptCore/inspector/remote/RemoteAutomationTarget.h new file mode 100644 index 000000000..0b174fd75 --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteAutomationTarget.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2015, 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(REMOTE_INSPECTOR) + +#include "RemoteControllableTarget.h" +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendChannel; + +class JS_EXPORT_PRIVATE RemoteAutomationTarget : public RemoteControllableTarget { +public: + virtual ~RemoteAutomationTarget() { } + + bool isPaired() const { return m_paired; } + void setIsPaired(bool); + + virtual String name() const = 0; + RemoteControllableTarget::Type type() const override { return RemoteControllableTarget::Type::Automation; } + bool remoteControlAllowed() const override { return !m_paired; }; + +private: + bool m_paired { false }; +}; + +} // namespace Inspector + +SPECIALIZE_TYPE_TRAITS_CONTROLLABLE_TARGET(Inspector::RemoteAutomationTarget, Automation) + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteConnectionToTarget.h b/Source/JavaScriptCore/inspector/remote/RemoteConnectionToTarget.h new file mode 100644 index 000000000..99596e5c8 --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteConnectionToTarget.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(REMOTE_INSPECTOR) + +#include "InspectorFrontendChannel.h" +#include <wtf/Lock.h> +#include <wtf/ThreadSafeRefCounted.h> + +#if PLATFORM(COCOA) +#include <wtf/BlockPtr.h> +#include <wtf/RetainPtr.h> + +OBJC_CLASS NSString; +#endif + +namespace Inspector { + +class RemoteControllableTarget; + +#if PLATFORM(COCOA) +typedef Vector<BlockPtr<void ()>> RemoteTargetQueue; +#endif + +class RemoteConnectionToTarget final : public ThreadSafeRefCounted<RemoteConnectionToTarget>, public FrontendChannel { +public: +#if PLATFORM(COCOA) + RemoteConnectionToTarget(RemoteControllableTarget*, NSString* connectionIdentifier, NSString* destination); +#endif + virtual ~RemoteConnectionToTarget(); + + // Main API. + bool setup(bool isAutomaticInspection = false, bool automaticallyPause = false); +#if PLATFORM(COCOA) + void sendMessageToTarget(NSString *); +#else + void sendMessageToTarget(const String&); +#endif + void close(); + void targetClosed(); + + std::optional<unsigned> targetIdentifier() const; +#if PLATFORM(COCOA) + NSString *connectionIdentifier() const; + NSString *destination() const; + + Lock& queueMutex() { return m_queueMutex; } + const RemoteTargetQueue& queue() const { return m_queue; } + void clearQueue() { m_queue.clear(); } +#endif + + // FrontendChannel overrides. + ConnectionType connectionType() const override { return ConnectionType::Remote; } + void sendMessageToFrontend(const String&) override; + +private: +#if PLATFORM(COCOA) + void dispatchAsyncOnTarget(void (^block)()); + + void setupRunLoop(); + void teardownRunLoop(); + void queueTaskOnPrivateRunLoop(void (^block)()); +#endif + + // This connection from the RemoteInspector singleton to the InspectionTarget + // can be used on multiple threads. So any access to the target + // itself must take this mutex to ensure m_target is valid. + Lock m_targetMutex; + +#if PLATFORM(COCOA) + // If a target has a specific run loop it wants to evaluate on + // we setup our run loop sources on that specific run loop. + RetainPtr<CFRunLoopRef> m_runLoop; + RetainPtr<CFRunLoopSourceRef> m_runLoopSource; + RemoteTargetQueue m_queue; + Lock m_queueMutex; +#endif + + RemoteControllableTarget* m_target { nullptr }; + bool m_connected { false }; + +#if PLATFORM(COCOA) + RetainPtr<NSString> m_connectionIdentifier; + RetainPtr<NSString> m_destination; +#endif +}; + +} // namespace Inspector + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteControllableTarget.cpp b/Source/JavaScriptCore/inspector/remote/RemoteControllableTarget.cpp new file mode 100644 index 000000000..f52852b15 --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteControllableTarget.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "RemoteControllableTarget.h" + +#if ENABLE(REMOTE_INSPECTOR) + +#include "RemoteInspector.h" + +namespace Inspector { + +RemoteControllableTarget::~RemoteControllableTarget() +{ + RemoteInspector::singleton().unregisterTarget(this); +} + +void RemoteControllableTarget::init() +{ + RemoteInspector::singleton().registerTarget(this); +} + +void RemoteControllableTarget::update() +{ + RemoteInspector::singleton().updateTarget(this); +} + +} // namespace Inspector + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteControllableTarget.h b/Source/JavaScriptCore/inspector/remote/RemoteControllableTarget.h new file mode 100644 index 000000000..afae369ae --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteControllableTarget.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(REMOTE_INSPECTOR) + +#include <wtf/TypeCasts.h> +#include <wtf/text/WTFString.h> + +#if USE(CF) +#include <CoreFoundation/CFRunLoop.h> +#endif + +namespace Inspector { + +class FrontendChannel; + +class JS_EXPORT_PRIVATE RemoteControllableTarget { +public: + virtual ~RemoteControllableTarget(); + + void init(); + void update(); + + virtual void connect(FrontendChannel*, bool isAutomaticConnection = false) = 0; + virtual void disconnect(FrontendChannel*) = 0; + + unsigned targetIdentifier() const { return m_identifier; } + void setTargetIdentifier(unsigned identifier) { m_identifier = identifier; } + + enum class Type { JavaScript, Web, Automation }; + virtual Type type() const = 0; + virtual bool remoteControlAllowed() const = 0; + virtual void dispatchMessageFromRemote(const String& message) = 0; + +#if USE(CF) + // The dispatch block will be scheduled on a global run loop if null is returned. + virtual CFRunLoopRef targetRunLoop() { return nullptr; } +#endif +private: + unsigned m_identifier {0}; +}; + +} // namespace Inspector + +#define SPECIALIZE_TYPE_TRAITS_CONTROLLABLE_TARGET(ToClassName, ToClassType) \ +SPECIALIZE_TYPE_TRAITS_BEGIN(ToClassName) \ + static bool isType(const Inspector::RemoteControllableTarget& target) { return target.type() == Inspector::RemoteControllableTarget::Type::ToClassType; } \ +SPECIALIZE_TYPE_TRAITS_END() + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteInspectionTarget.cpp b/Source/JavaScriptCore/inspector/remote/RemoteInspectionTarget.cpp new file mode 100644 index 000000000..5d5f3ebc7 --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteInspectionTarget.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "RemoteInspectionTarget.h" + +#if ENABLE(REMOTE_INSPECTOR) + +#include "EventLoop.h" +#include "RemoteInspector.h" + +namespace Inspector { + +bool RemoteInspectionTarget::remoteControlAllowed() const +{ + return remoteDebuggingAllowed() || hasLocalDebugger(); +} + +void RemoteInspectionTarget::setRemoteDebuggingAllowed(bool allowed) +{ + if (m_allowed == allowed) + return; + + m_allowed = allowed; + + if (m_allowed && automaticInspectionAllowed()) + RemoteInspector::singleton().updateAutomaticInspectionCandidate(this); + else + RemoteInspector::singleton().updateTarget(this); +} + +void RemoteInspectionTarget::pauseWaitingForAutomaticInspection() +{ + ASSERT(targetIdentifier()); + ASSERT(m_allowed); + ASSERT(automaticInspectionAllowed()); + + EventLoop loop; + while (RemoteInspector::singleton().waitingForAutomaticInspection(targetIdentifier()) && !loop.ended()) + loop.cycle(); +} + +void RemoteInspectionTarget::unpauseForInitializedInspector() +{ + RemoteInspector::singleton().setupCompleted(targetIdentifier()); +} + +} // namespace Inspector + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteInspectionTarget.h b/Source/JavaScriptCore/inspector/remote/RemoteInspectionTarget.h new file mode 100644 index 000000000..45329f6d6 --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteInspectionTarget.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2013, 2015 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(REMOTE_INSPECTOR) + +#include "RemoteControllableTarget.h" +#include <wtf/RetainPtr.h> +#include <wtf/TypeCasts.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendChannel; + +class JS_EXPORT_PRIVATE RemoteInspectionTarget : public RemoteControllableTarget { +public: + bool remoteDebuggingAllowed() const { return m_allowed; } + void setRemoteDebuggingAllowed(bool); + +#if USE(CF) + CFRunLoopRef targetRunLoop() override { return m_runLoop.get(); } + void setTargetRunLoop(CFRunLoopRef runLoop) { m_runLoop = runLoop; } +#endif + + virtual String name() const { return String(); } // JavaScript and Web + virtual String url() const { return String(); } // Web + virtual bool hasLocalDebugger() const = 0; + + virtual void setIndicating(bool) { } // Default is to do nothing. + virtual void pause() { }; + + virtual bool automaticInspectionAllowed() const { return false; } + virtual void pauseWaitingForAutomaticInspection(); + virtual void unpauseForInitializedInspector(); + + // RemoteControllableTarget overrides. + bool remoteControlAllowed() const override; +private: + bool m_allowed {false}; +#if USE(CF) + RetainPtr<CFRunLoopRef> m_runLoop; +#endif +}; + +} // namespace Inspector + +SPECIALIZE_TYPE_TRAITS_BEGIN(Inspector::RemoteInspectionTarget) \ + static bool isType(const Inspector::RemoteControllableTarget& target) \ + { \ + return target.type() == Inspector::RemoteControllableTarget::Type::JavaScript \ + || target.type() == Inspector::RemoteControllableTarget::Type::Web; \ + } +SPECIALIZE_TYPE_TRAITS_END() + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteInspector.cpp b/Source/JavaScriptCore/inspector/remote/RemoteInspector.cpp new file mode 100644 index 000000000..af88dc13e --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteInspector.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2013-2016 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "RemoteInspector.h" + +#if ENABLE(REMOTE_INSPECTOR) + +#include "RemoteAutomationTarget.h" +#include "RemoteConnectionToTarget.h" +#include "RemoteInspectionTarget.h" +#include "RemoteInspectorConstants.h" +#include <wtf/MainThread.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +bool RemoteInspector::startEnabled = true; + +void RemoteInspector::startDisabled() +{ + RemoteInspector::startEnabled = false; +} + +unsigned RemoteInspector::nextAvailableTargetIdentifier() +{ + unsigned nextValidTargetIdentifier; + do { + nextValidTargetIdentifier = m_nextAvailableTargetIdentifier++; + } while (!nextValidTargetIdentifier || nextValidTargetIdentifier == std::numeric_limits<unsigned>::max() || m_targetMap.contains(nextValidTargetIdentifier)); + return nextValidTargetIdentifier; +} + +void RemoteInspector::registerTarget(RemoteControllableTarget* target) +{ + ASSERT_ARG(target, target); + + std::lock_guard<Lock> lock(m_mutex); + + unsigned targetIdentifier = nextAvailableTargetIdentifier(); + target->setTargetIdentifier(targetIdentifier); + + { + auto result = m_targetMap.set(targetIdentifier, target); + ASSERT_UNUSED(result, result.isNewEntry); + } + + // If remote control is not allowed, a null listing is returned. + if (auto targetListing = listingForTarget(*target)) { + auto result = m_targetListingMap.set(targetIdentifier, targetListing); + ASSERT_UNUSED(result, result.isNewEntry); + } + + pushListingsSoon(); +} + +void RemoteInspector::unregisterTarget(RemoteControllableTarget* target) +{ + ASSERT_ARG(target, target); + + std::lock_guard<Lock> lock(m_mutex); + + unsigned targetIdentifier = target->targetIdentifier(); + if (!targetIdentifier) + return; + + bool wasRemoved = m_targetMap.remove(targetIdentifier); + ASSERT_UNUSED(wasRemoved, wasRemoved); + + // The listing may never have been added if remote control isn't allowed. + m_targetListingMap.remove(targetIdentifier); + + if (auto connectionToTarget = m_targetConnectionMap.take(targetIdentifier)) + connectionToTarget->targetClosed(); + + pushListingsSoon(); +} + +void RemoteInspector::updateTarget(RemoteControllableTarget* target) +{ + ASSERT_ARG(target, target); + + std::lock_guard<Lock> lock(m_mutex); + + unsigned targetIdentifier = target->targetIdentifier(); + if (!targetIdentifier) + return; + + { + auto result = m_targetMap.set(targetIdentifier, target); + ASSERT_UNUSED(result, !result.isNewEntry); + } + + // If the target has just allowed remote control, then the listing won't exist yet. + // If the target has no identifier remove the old listing. + if (auto targetListing = listingForTarget(*target)) + m_targetListingMap.set(targetIdentifier, targetListing); + else + m_targetListingMap.remove(targetIdentifier); + + pushListingsSoon(); +} + +void RemoteInspector::updateClientCapabilities() +{ + ASSERT(isMainThread()); + + std::lock_guard<Lock> lock(m_mutex); + + if (!m_client) + m_clientCapabilities = std::nullopt; + else { + RemoteInspector::Client::Capabilities updatedCapabilities = { + m_client->remoteAutomationAllowed() // remoteAutomationAllowed + }; + + m_clientCapabilities = updatedCapabilities; + } +} + +void RemoteInspector::setRemoteInspectorClient(RemoteInspector::Client* client) +{ + ASSERT_ARG(client, client); + ASSERT(!m_client); + + { + std::lock_guard<Lock> lock(m_mutex); + m_client = client; + } + + // Send an updated listing that includes whether the client allows remote automation. + updateClientCapabilities(); + pushListingsSoon(); +} + +void RemoteInspector::setupFailed(unsigned targetIdentifier) +{ + std::lock_guard<Lock> lock(m_mutex); + + m_targetConnectionMap.remove(targetIdentifier); + + if (targetIdentifier == m_automaticInspectionCandidateTargetIdentifier) + m_automaticInspectionPaused = false; + + updateHasActiveDebugSession(); + updateTargetListing(targetIdentifier); + pushListingsSoon(); +} + +void RemoteInspector::setupCompleted(unsigned targetIdentifier) +{ + std::lock_guard<Lock> lock(m_mutex); + + if (targetIdentifier == m_automaticInspectionCandidateTargetIdentifier) + m_automaticInspectionPaused = false; +} + +bool RemoteInspector::waitingForAutomaticInspection(unsigned) +{ + // We don't take the lock to check this because we assume it will be checked repeatedly. + return m_automaticInspectionPaused; +} + +void RemoteInspector::clientCapabilitiesDidChange() +{ + updateClientCapabilities(); + pushListingsSoon(); +} + +void RemoteInspector::stop() +{ + std::lock_guard<Lock> lock(m_mutex); + + stopInternal(StopSource::API); +} + +TargetListing RemoteInspector::listingForTarget(const RemoteControllableTarget& target) const +{ + if (is<RemoteInspectionTarget>(target)) + return listingForInspectionTarget(downcast<RemoteInspectionTarget>(target)); + if (is<RemoteAutomationTarget>(target)) + return listingForAutomationTarget(downcast<RemoteAutomationTarget>(target)); + + ASSERT_NOT_REACHED(); + return nullptr; +} + +void RemoteInspector::updateHasActiveDebugSession() +{ + bool hasActiveDebuggerSession = !m_targetConnectionMap.isEmpty(); + if (hasActiveDebuggerSession == m_hasActiveDebugSession) + return; + + m_hasActiveDebugSession = hasActiveDebuggerSession; + + // FIXME: Expose some way to access this state in an embedder. + // Legacy iOS WebKit 1 had a notification. This will need to be smarter with WebKit2. +} + +} // namespace Inspector + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteInspector.h b/Source/JavaScriptCore/inspector/remote/RemoteInspector.h new file mode 100644 index 000000000..b7ca1ea1e --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteInspector.h @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2013, 2015, 2016 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if ENABLE(REMOTE_INSPECTOR) + +#include <wtf/Forward.h> +#include <wtf/HashMap.h> +#include <wtf/Lock.h> + +#if PLATFORM(COCOA) +#include "RemoteInspectorXPCConnection.h" +#include <wtf/RetainPtr.h> + +OBJC_CLASS NSDictionary; +OBJC_CLASS NSString; +typedef RetainPtr<NSDictionary> TargetListing; +#endif + +namespace Inspector { + +class RemoteAutomationTarget; +class RemoteConnectionToTarget; +class RemoteControllableTarget; +class RemoteInspectionTarget; +class RemoteInspectorClient; + +class JS_EXPORT_PRIVATE RemoteInspector final +#if PLATFORM(COCOA) + : public RemoteInspectorXPCConnection::Client +#endif +{ +public: + class Client { + public: + struct Capabilities { + bool remoteAutomationAllowed : 1; + }; + + virtual ~Client() { } + virtual bool remoteAutomationAllowed() const = 0; + virtual void requestAutomationSession(const String& sessionIdentifier) = 0; + }; + + static void startDisabled(); + static RemoteInspector& singleton(); + friend class NeverDestroyed<RemoteInspector>; + + void registerTarget(RemoteControllableTarget*); + void unregisterTarget(RemoteControllableTarget*); + void updateTarget(RemoteControllableTarget*); + void sendMessageToRemote(unsigned targetIdentifier, const String& message); + + void setRemoteInspectorClient(RemoteInspector::Client*); + void clientCapabilitiesDidChange(); + + void setupFailed(unsigned targetIdentifier); + void setupCompleted(unsigned targetIdentifier); + bool waitingForAutomaticInspection(unsigned targetIdentifier); + void updateAutomaticInspectionCandidate(RemoteInspectionTarget*); + + bool enabled() const { return m_enabled; } + bool hasActiveDebugSession() const { return m_hasActiveDebugSession; } + + void start(); + void stop(); + +#if PLATFORM(COCOA) + bool hasParentProcessInformation() const { return m_parentProcessIdentifier != 0; } + pid_t parentProcessIdentifier() const { return m_parentProcessIdentifier; } + RetainPtr<CFDataRef> parentProcessAuditData() const { return m_parentProcessAuditData; } + void setParentProcessInformation(pid_t, RetainPtr<CFDataRef> auditData); + void setParentProcessInfomationIsDelayed(); +#endif + +private: + RemoteInspector(); + + unsigned nextAvailableTargetIdentifier(); + + enum class StopSource { API, XPCMessage }; + void stopInternal(StopSource); + +#if PLATFORM(COCOA) + void setupXPCConnectionIfNeeded(); +#endif + + TargetListing listingForTarget(const RemoteControllableTarget&) const; + TargetListing listingForInspectionTarget(const RemoteInspectionTarget&) const; + TargetListing listingForAutomationTarget(const RemoteAutomationTarget&) const; + + void pushListingsNow(); + void pushListingsSoon(); + + void updateTargetListing(unsigned targetIdentifier); + void updateTargetListing(const RemoteControllableTarget&); + + void updateHasActiveDebugSession(); + void updateClientCapabilities(); + + void sendAutomaticInspectionCandidateMessage(); + +#if PLATFORM(COCOA) + void xpcConnectionReceivedMessage(RemoteInspectorXPCConnection*, NSString *messageName, NSDictionary *userInfo) override; + void xpcConnectionFailed(RemoteInspectorXPCConnection*) override; + void xpcConnectionUnhandledMessage(RemoteInspectorXPCConnection*, xpc_object_t) override; + + void receivedSetupMessage(NSDictionary *userInfo); + void receivedDataMessage(NSDictionary *userInfo); + void receivedDidCloseMessage(NSDictionary *userInfo); + void receivedGetListingMessage(NSDictionary *userInfo); + void receivedIndicateMessage(NSDictionary *userInfo); + void receivedProxyApplicationSetupMessage(NSDictionary *userInfo); + void receivedConnectionDiedMessage(NSDictionary *userInfo); + void receivedAutomaticInspectionConfigurationMessage(NSDictionary *userInfo); + void receivedAutomaticInspectionRejectMessage(NSDictionary *userInfo); + void receivedAutomationSessionRequestMessage(NSDictionary *userInfo); +#endif + + static bool startEnabled; + + // Targets can be registered from any thread at any time. + // Any target can send messages over the XPC connection. + // So lock access to all maps and state as they can change + // from any thread. + Lock m_mutex; + + HashMap<unsigned, RemoteControllableTarget*> m_targetMap; + HashMap<unsigned, RefPtr<RemoteConnectionToTarget>> m_targetConnectionMap; + HashMap<unsigned, TargetListing> m_targetListingMap; + +#if PLATFORM(COCOA) + RefPtr<RemoteInspectorXPCConnection> m_relayConnection; +#endif + + RemoteInspector::Client* m_client { nullptr }; + std::optional<RemoteInspector::Client::Capabilities> m_clientCapabilities; + +#if PLATFORM(COCOA) + dispatch_queue_t m_xpcQueue; +#endif + unsigned m_nextAvailableTargetIdentifier { 1 }; + int m_notifyToken { 0 }; + bool m_enabled { false }; + bool m_hasActiveDebugSession { false }; + bool m_pushScheduled { false }; + + pid_t m_parentProcessIdentifier { 0 }; +#if PLATFORM(COCOA) + RetainPtr<CFDataRef> m_parentProcessAuditData; +#endif + bool m_shouldSendParentProcessInformation { false }; + bool m_automaticInspectionEnabled { false }; + bool m_automaticInspectionPaused { false }; + unsigned m_automaticInspectionCandidateTargetIdentifier { 0 }; +}; + +} // namespace Inspector + +#endif // ENABLE(REMOTE_INSPECTOR) diff --git a/Source/JavaScriptCore/inspector/remote/RemoteInspectorConstants.h b/Source/JavaScriptCore/inspector/remote/RemoteInspectorConstants.h new file mode 100644 index 000000000..700657be0 --- /dev/null +++ b/Source/JavaScriptCore/inspector/remote/RemoteInspectorConstants.h @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2011, 2016 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +// WIRConstants are "Web Inspector Relay" constants shared between +// the WebInspector framework on the OS X side, webinspectord, and +// iOS WebKit on the device side. + +#define WIRSimulatorTCPPortNumber 27753 +#define WIRXPCMachPortName "com.apple.webinspector" +#define WIRXPCDebuggerServiceName "com.apple.webinspector.debugger" +#define WIRServiceAvailableNotification "com.apple.webinspectord.available" +#define WIRServiceAvailabilityCheckNotification "com.apple.webinspectord.availability_check" +#define WIRServiceEnabledNotification "com.apple.webinspectord.enabled" +#define WIRServiceDisabledNotification "com.apple.webinspectord.disabled" +#define WIRAutomaticInspectionEnabledState "com.apple.webinspectord.automatic_inspection_enabled" + + +#define WIRApplicationIdentifierKey @"WIRApplicationIdentifierKey" +#define WIRApplicationBundleIdentifierKey @"WIRApplicationBundleIdentifierKey" +#define WIRApplicationNameKey @"WIRApplicationNameKey" +#define WIRIsApplicationProxyKey @"WIRIsApplicationProxyKey" +#define WIRIsApplicationActiveKey @"WIRIsApplicationActiveKey" +#define WIRHostApplicationIdentifierKey @"WIRHostApplicationIdentifierKey" +#define WIRHostApplicationNameKey @"WIRHostApplicationNameKey" +#define WIRConnectionIdentifierKey @"WIRConnectionIdentifierKey" +// COMPATABILITY(iOS 9): The key string is intentionally mismatched to support old relays. +#define WIRTargetIdentifierKey @"WIRPageIdentifierKey" +#define WIRHasLocalDebuggerKey @"WIRHasLocalDebuggerKey" +#define WIRTitleKey @"WIRTitleKey" +#define WIRURLKey @"WIRURLKey" +#define WIRUserInfoKey @"WIRUserInfoKey" +#define WIRApplicationDictionaryKey @"WIRApplicationDictionaryKey" +#define WIRMessageDataKey @"WIRMessageDataKey" +#define WIRApplicationGetListingMessage @"WIRApplicationGetListingMessage" +#define WIRIndicateMessage @"WIRIndicateMessage" +#define WIRIndicateEnabledKey @"WIRIndicateEnabledKey" +#define WIRSenderKey @"WIRSenderKey" +#define WIRSocketDataKey @"WIRSocketDataKey" +#define WIRSocketDataMessage @"WIRSocketDataMessage" +#define WIRSocketSetupMessage @"WIRSocketSetupMessage" +#define WIRWebPageCloseMessage @"WIRWebPageCloseMessage" +#define WIRRawDataMessage @"WIRRawDataMessage" +#define WIRRawDataKey @"WIRRawDataKey" +#define WIRListingMessage @"WIRListingMessage" +#define WIRListingKey @"WIRListingKey" +#define WIRRemoteAutomationEnabledKey @"WIRRemoteAutomationEnabledKey" +#define WIRDestinationKey @"WIRDestinationKey" +#define WIRConnectionDiedMessage @"WIRConnectionDiedMessage" +#define WIRTypeKey @"WIRTypeKey" +#define WIRTypeJavaScript @"WIRTypeJavaScript" +#define WIRTypeWeb @"WIRTypeWeb" +#define WIRTypeAutomation @"WIRTypeAutomation" +#define WIRAutomaticallyPause @"WIRAutomaticallyPause" + +#define WIRAutomaticInspectionEnabledKey @"WIRAutomaticInspectionEnabledKey" +#define WIRAutomaticInspectionSessionIdentifierKey @"WIRAutomaticInspectionSessionIdentifierKey" +#define WIRAutomaticInspectionConfigurationMessage @"WIRAutomaticInspectionConfigurationMessage" +#define WIRAutomaticInspectionRejectMessage @"WIRAutomaticInspectionRejectMessage" +#define WIRAutomaticInspectionCandidateMessage @"WIRAutomaticInspectionCandidateMessage" + +#define WIRAutomationTargetIsPairedKey @"WIRAutomationTargetIsPairedKey" +#define WIRSessionIdentifierKey @"WIRSessionIdentifierKey" +#define WIRAutomationSessionRequestMessage @"WIRAutomationSessionRequestMessage" + +// These definitions are shared with a Simulator webinspectord and +// OS X process communicating with it. + +#define WIRSimulatorBuildKey @"WIRSimulatorBuildKey" +#define WIRSimulatorProductVersionKey @"WIRSimulatorProductVersionKey" +#define WIRSimulatorNameKey @"WIRSimulatorNameKey" + +// These definitions are shared between webinspectord and WebKit. + +#define WIRPermissionDenied @"WIRPermissionDenied" +#define WIRProxyApplicationParentPIDKey @"WIRProxyApplicationParentPID" +#define WIRProxyApplicationParentAuditDataKey @"WIRProxyApplicationParentAuditData" +#define WIRProxyApplicationSetupMessage @"WIRProxyApplicationSetupMessage" +#define WIRProxyApplicationSetupResponseMessage @"WIRProxyApplicationSetupResponseMessage" diff --git a/Source/JavaScriptCore/inspector/scripts/CodeGeneratorInspector.py b/Source/JavaScriptCore/inspector/scripts/CodeGeneratorInspector.py deleted file mode 100755 index 9c6195ff4..000000000 --- a/Source/JavaScriptCore/inspector/scripts/CodeGeneratorInspector.py +++ /dev/null @@ -1,2613 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2011 Google Inc. All rights reserved. -# Copyright (c) 2012 Intel Corporation. All rights reserved. -# Copyright (c) 2013 Apple Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import os.path -import sys -import string -import optparse -import re -try: - import json -except ImportError: - import simplejson as json - -import CodeGeneratorInspectorStrings - - -DOMAIN_DEFINE_NAME_MAP = { - "Database": "SQL_DATABASE", - "IndexedDB": "INDEXED_DATABASE", -} - - -# Manually-filled map of type name replacements. -TYPE_NAME_FIX_MAP = { - "RGBA": "Rgba", # RGBA is reported to be conflicting with a define name in Windows CE. - "": "Empty", -} - - -TYPES_WITH_RUNTIME_CAST_SET = frozenset(["Runtime.RemoteObject", "Runtime.PropertyDescriptor", "Runtime.InternalPropertyDescriptor", - "Debugger.FunctionDetails", "Debugger.CallFrame", - "Canvas.TraceLog", "Canvas.ResourceInfo", "Canvas.ResourceState", - # This should be a temporary hack. TimelineEvent should be created via generated C++ API. - "Timeline.TimelineEvent"]) - -TYPES_WITH_OPEN_FIELD_LIST_SET = frozenset(["Timeline.TimelineEvent", - # InspectorStyleSheet not only creates this property but wants to read it and modify it. - "CSS.CSSProperty", - # InspectorResourceAgent needs to update mime-type. - "Network.Response"]) - -EXACTLY_INT_SUPPORTED = False - -INSPECTOR_TYPES_GENERATOR_CONFIG_MAP = { - "JavaScript": { - "prefix": "JS", - "typebuilder_dependency": "", - "export_macro": "JS_EXPORT_PRIVATE", - }, - "Web": { - "prefix": "Web", - "typebuilder_dependency": "#include <inspector/InspectorJSTypeBuilders.h>", - "export_macro": "", - }, -} - -cmdline_parser = optparse.OptionParser(usage="usage: %prog [options] <Inspector.json>") -cmdline_parser.add_option("--output_h_dir") -cmdline_parser.add_option("--output_cpp_dir") -cmdline_parser.add_option("--output_js_dir") -cmdline_parser.add_option("--output_type") # JavaScript, Web -cmdline_parser.add_option("--write_always", action="store_true") -cmdline_parser.add_option("--no_verification", action="store_true") - -try: - arg_options, arg_values = cmdline_parser.parse_args() - if (len(arg_values) < 1): - raise Exception("At least one plain argument expected") - - input_json_filename = arg_values[0] - dependency_json_filenames = arg_values[1:] - - output_header_dirname = arg_options.output_h_dir - output_cpp_dirname = arg_options.output_cpp_dir - output_js_dirname = arg_options.output_js_dir - output_type = arg_options.output_type - - write_always = arg_options.write_always - verification = not arg_options.no_verification - if not output_header_dirname: - raise Exception("Output .h directory must be specified") - if not output_cpp_dirname: - raise Exception("Output .cpp directory must be specified") - if not output_js_dirname: - raise Exception("Output .js directory must be specified") - if output_type not in INSPECTOR_TYPES_GENERATOR_CONFIG_MAP.keys(): - raise Exception("Unknown output type. Allowed types are: %s" % INSPECTOR_TYPES_GENERATOR_CONFIG_MAP.keys()) -except Exception: - # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html - exc = sys.exc_info()[1] - sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc) - sys.stderr.write("Usage: <script> Inspector.json --output_h_dir <output_header_dir> --output_cpp_dir <output_cpp_dir> --output_js_dir <output_js_dir> [--write_always] [--no_verification]\n") - exit(1) - - -def dash_to_camelcase(word): - return ''.join(x.capitalize() or '-' for x in word.split('-')) - - -def fix_camel_case(name): - refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name) - refined = to_title_case(refined) - return re.sub(r'(?i)HTML|XML|WML|API|GC|XHR|DOM|CSS', lambda pat: pat.group(0).upper(), refined) - - -def to_title_case(name): - return name[:1].upper() + name[1:] - - -class Capitalizer: - @staticmethod - def lower_camel_case_to_upper(str): - if len(str) > 0 and str[0].islower(): - str = str[0].upper() + str[1:] - return str - - @staticmethod - def upper_camel_case_to_lower(str): - pos = 0 - while pos < len(str) and str[pos].isupper(): - pos += 1 - if pos == 0: - return str - if pos == 1: - return str[0].lower() + str[1:] - if pos < len(str): - pos -= 1 - possible_abbreviation = str[0:pos] - if possible_abbreviation not in Capitalizer.ABBREVIATION: - raise Exception("Unknown abbreviation %s" % possible_abbreviation) - str = possible_abbreviation.lower() + str[pos:] - return str - - @staticmethod - def camel_case_to_capitalized_with_underscores(str): - if len(str) == 0: - return str - output = Capitalizer.split_camel_case_(str) - return "_".join(output).upper() - - @staticmethod - def split_camel_case_(str): - output = [] - pos_being = 0 - pos = 1 - has_oneletter = False - while pos < len(str): - if str[pos].isupper(): - output.append(str[pos_being:pos].upper()) - if pos - pos_being == 1: - has_oneletter = True - pos_being = pos - pos += 1 - output.append(str[pos_being:]) - if has_oneletter: - array_pos = 0 - while array_pos < len(output) - 1: - if len(output[array_pos]) == 1: - array_pos_end = array_pos + 1 - while array_pos_end < len(output) and len(output[array_pos_end]) == 1: - array_pos_end += 1 - if array_pos_end - array_pos > 1: - possible_abbreviation = "".join(output[array_pos:array_pos_end]) - if possible_abbreviation.upper() in Capitalizer.ABBREVIATION: - output[array_pos:array_pos_end] = [possible_abbreviation] - else: - array_pos = array_pos_end - 1 - array_pos += 1 - return output - - ABBREVIATION = frozenset(["XHR", "DOM", "CSS"]) - -VALIDATOR_IFDEF_NAME = "!ASSERT_DISABLED" - - -class DomainNameFixes: - @classmethod - def get_fixed_data(cls, domain_name): - field_name_res = Capitalizer.upper_camel_case_to_lower(domain_name) + "Agent" - - class Res(object): - skip_js_bind = domain_name in cls.skip_js_bind_domains - - @staticmethod - def get_guard(): - if domain_name in DOMAIN_DEFINE_NAME_MAP: - define_name = DOMAIN_DEFINE_NAME_MAP[domain_name] - - class Guard: - @staticmethod - def generate_open(output): - output.append("#if ENABLE(%s)\n" % define_name) - - @staticmethod - def generate_close(output): - output.append("#endif // ENABLE(%s)\n" % define_name) - - return Guard - - return Res - - skip_js_bind_domains = set(["DOMDebugger"]) - - -class RawTypes(object): - @staticmethod - def get(json_type): - if json_type == "boolean": - return RawTypes.Bool - elif json_type == "string": - return RawTypes.String - elif json_type == "array": - return RawTypes.Array - elif json_type == "object": - return RawTypes.Object - elif json_type == "integer": - return RawTypes.Int - elif json_type == "number": - return RawTypes.Number - elif json_type == "any": - return RawTypes.Any - else: - raise Exception("Unknown type: %s" % json_type) - - # For output parameter all values are passed by pointer except RefPtr-based types. - class OutputPassModel: - class ByPointer: - @staticmethod - def get_argument_prefix(): - return "&" - - @staticmethod - def get_parameter_type_suffix(): - return "*" - - class ByReference: - @staticmethod - def get_argument_prefix(): - return "" - - @staticmethod - def get_parameter_type_suffix(): - return "&" - - class BaseType(object): - need_internal_runtime_cast_ = False - - @classmethod - def request_raw_internal_runtime_cast(cls): - if not cls.need_internal_runtime_cast_: - cls.need_internal_runtime_cast_ = True - - @classmethod - def get_raw_validator_call_text(cls): - return "RuntimeCastHelper::assertType<Inspector::InspectorValue::Type%s>" % cls.get_validate_method_params().template_type - - class String(BaseType): - @staticmethod - def get_getter_name(): - return "String" - - get_setter_name = get_getter_name - - @staticmethod - def get_c_initializer(): - return "\"\"" - - @staticmethod - def get_js_bind_type(): - return "string" - - @staticmethod - def get_validate_method_params(): - class ValidateMethodParams: - template_type = "String" - return ValidateMethodParams - - @staticmethod - def get_output_pass_model(): - return RawTypes.OutputPassModel.ByPointer - - @staticmethod - def is_heavy_value(): - return True - - @staticmethod - def get_array_item_raw_c_type_text(): - return "String" - - @staticmethod - def get_raw_type_model(): - return TypeModel.String - - class Int(BaseType): - @staticmethod - def get_getter_name(): - return "Int" - - @staticmethod - def get_setter_name(): - return "Number" - - @staticmethod - def get_c_initializer(): - return "0" - - @staticmethod - def get_js_bind_type(): - return "number" - - @classmethod - def get_raw_validator_call_text(cls): - return "RuntimeCastHelper::assertInt" - - @staticmethod - def get_output_pass_model(): - return RawTypes.OutputPassModel.ByPointer - - @staticmethod - def is_heavy_value(): - return False - - @staticmethod - def get_array_item_raw_c_type_text(): - return "int" - - @staticmethod - def get_raw_type_model(): - return TypeModel.Int - - class Number(BaseType): - @staticmethod - def get_getter_name(): - return "Double" - - @staticmethod - def get_setter_name(): - return "Number" - - @staticmethod - def get_c_initializer(): - return "0" - - @staticmethod - def get_js_bind_type(): - return "number" - - @staticmethod - def get_validate_method_params(): - class ValidateMethodParams: - template_type = "Number" - return ValidateMethodParams - - @staticmethod - def get_output_pass_model(): - return RawTypes.OutputPassModel.ByPointer - - @staticmethod - def is_heavy_value(): - return False - - @staticmethod - def get_array_item_raw_c_type_text(): - return "double" - - @staticmethod - def get_raw_type_model(): - return TypeModel.Number - - class Bool(BaseType): - @staticmethod - def get_getter_name(): - return "Boolean" - - get_setter_name = get_getter_name - - @staticmethod - def get_c_initializer(): - return "false" - - @staticmethod - def get_js_bind_type(): - return "boolean" - - @staticmethod - def get_validate_method_params(): - class ValidateMethodParams: - template_type = "Boolean" - return ValidateMethodParams - - @staticmethod - def get_output_pass_model(): - return RawTypes.OutputPassModel.ByPointer - - @staticmethod - def is_heavy_value(): - return False - - @staticmethod - def get_array_item_raw_c_type_text(): - return "bool" - - @staticmethod - def get_raw_type_model(): - return TypeModel.Bool - - class Object(BaseType): - @staticmethod - def get_getter_name(): - return "Object" - - @staticmethod - def get_setter_name(): - return "Value" - - @staticmethod - def get_c_initializer(): - return "InspectorObject::create()" - - @staticmethod - def get_js_bind_type(): - return "object" - - @staticmethod - def get_output_argument_prefix(): - return "" - - @staticmethod - def get_validate_method_params(): - class ValidateMethodParams: - template_type = "Object" - return ValidateMethodParams - - @staticmethod - def get_output_pass_model(): - return RawTypes.OutputPassModel.ByReference - - @staticmethod - def is_heavy_value(): - return True - - @staticmethod - def get_array_item_raw_c_type_text(): - return "Inspector::InspectorObject" - - @staticmethod - def get_raw_type_model(): - return TypeModel.Object - - class Any(BaseType): - @staticmethod - def get_getter_name(): - return "Value" - - get_setter_name = get_getter_name - - @staticmethod - def get_c_initializer(): - raise Exception("Unsupported") - - @staticmethod - def get_js_bind_type(): - raise Exception("Unsupported") - - @staticmethod - def get_raw_validator_call_text(): - return "RuntimeCastHelper::assertAny" - - @staticmethod - def get_output_pass_model(): - return RawTypes.OutputPassModel.ByReference - - @staticmethod - def is_heavy_value(): - return True - - @staticmethod - def get_array_item_raw_c_type_text(): - return "Inspector::InspectorValue" - - @staticmethod - def get_raw_type_model(): - return TypeModel.Any - - class Array(BaseType): - @staticmethod - def get_getter_name(): - return "Array" - - @staticmethod - def get_setter_name(): - return "Value" - - @staticmethod - def get_c_initializer(): - return "InspectorArray::create()" - - @staticmethod - def get_js_bind_type(): - return "object" - - @staticmethod - def get_output_argument_prefix(): - return "" - - @staticmethod - def get_validate_method_params(): - class ValidateMethodParams: - template_type = "Array" - return ValidateMethodParams - - @staticmethod - def get_output_pass_model(): - return RawTypes.OutputPassModel.ByReference - - @staticmethod - def is_heavy_value(): - return True - - @staticmethod - def get_array_item_raw_c_type_text(): - return "Inspector::InspectorArray" - - @staticmethod - def get_raw_type_model(): - return TypeModel.Array - - -def replace_right_shift(input_str): - return input_str.replace(">>", "> >") - - -class CommandReturnPassModel: - class ByReference: - def __init__(self, var_type, set_condition): - self.var_type = var_type - self.set_condition = set_condition - - def get_return_var_type(self): - return self.var_type - - @staticmethod - def get_output_argument_prefix(): - return "" - - @staticmethod - def get_output_to_raw_expression(): - return "%s" - - def get_output_parameter_type(self): - return self.var_type + "&" - - def get_set_return_condition(self): - return self.set_condition - - class ByPointer: - def __init__(self, var_type): - self.var_type = var_type - - def get_return_var_type(self): - return self.var_type - - @staticmethod - def get_output_argument_prefix(): - return "&" - - @staticmethod - def get_output_to_raw_expression(): - return "%s" - - def get_output_parameter_type(self): - return self.var_type + "*" - - @staticmethod - def get_set_return_condition(): - return None - - class OptOutput: - def __init__(self, var_type): - self.var_type = var_type - - def get_return_var_type(self): - return "Inspector::TypeBuilder::OptOutput<%s>" % self.var_type - - @staticmethod - def get_output_argument_prefix(): - return "&" - - @staticmethod - def get_output_to_raw_expression(): - return "%s.getValue()" - - def get_output_parameter_type(self): - return "Inspector::TypeBuilder::OptOutput<%s>*" % self.var_type - - @staticmethod - def get_set_return_condition(): - return "%s.isAssigned()" - - -class TypeModel: - class RefPtrBased(object): - def __init__(self, class_name): - self.class_name = class_name - self.optional = False - - def get_optional(self): - result = TypeModel.RefPtrBased(self.class_name) - result.optional = True - return result - - def get_command_return_pass_model(self): - if self.optional: - set_condition = "%s" - else: - set_condition = None - return CommandReturnPassModel.ByReference(replace_right_shift("RefPtr<%s>" % self.class_name), set_condition) - - def get_input_param_type_text(self): - return replace_right_shift("PassRefPtr<%s>" % self.class_name) - - @staticmethod - def get_event_setter_expression_pattern(): - return "%s" - - class Enum(object): - def __init__(self, base_type_name): - self.type_name = base_type_name + "::Enum" - - def get_optional(base_self): - class EnumOptional: - @classmethod - def get_optional(cls): - return cls - - @staticmethod - def get_command_return_pass_model(): - return CommandReturnPassModel.OptOutput(base_self.type_name) - - @staticmethod - def get_input_param_type_text(): - return base_self.type_name + "*" - - @staticmethod - def get_event_setter_expression_pattern(): - raise Exception("TODO") - return EnumOptional - - def get_command_return_pass_model(self): - return CommandReturnPassModel.ByPointer(self.type_name) - - def get_input_param_type_text(self): - return self.type_name - - @staticmethod - def get_event_setter_expression_pattern(): - return "%s" - - class ValueType(object): - def __init__(self, type_name, is_heavy): - self.type_name = type_name - self.is_heavy = is_heavy - - def get_optional(self): - return self.ValueOptional(self) - - def get_command_return_pass_model(self): - return CommandReturnPassModel.ByPointer(self.type_name) - - def get_input_param_type_text(self): - if self.is_heavy: - return "const %s&" % self.type_name - else: - return self.type_name - - def get_opt_output_type_(self): - return self.type_name - - @staticmethod - def get_event_setter_expression_pattern(): - return "%s" - - class ValueOptional: - def __init__(self, base): - self.base = base - - def get_optional(self): - return self - - def get_command_return_pass_model(self): - return CommandReturnPassModel.OptOutput(self.base.get_opt_output_type_()) - - def get_input_param_type_text(self): - return "const %s* const" % self.base.type_name - - @staticmethod - def get_event_setter_expression_pattern(): - return "*%s" - - class ExactlyInt(ValueType): - def __init__(self): - TypeModel.ValueType.__init__(self, "int", False) - - def get_input_param_type_text(self): - return "Inspector::TypeBuilder::ExactlyInt" - - def get_opt_output_type_(self): - return "Inspector::TypeBuilder::ExactlyInt" - - @classmethod - def init_class(cls): - cls.Bool = cls.ValueType("bool", False) - if EXACTLY_INT_SUPPORTED: - cls.Int = cls.ExactlyInt() - else: - cls.Int = cls.ValueType("int", False) - cls.Number = cls.ValueType("double", False) - cls.String = cls.ValueType("String", True,) - cls.Object = cls.RefPtrBased("Inspector::InspectorObject") - cls.Array = cls.RefPtrBased("Inspector::InspectorArray") - cls.Any = cls.RefPtrBased("Inspector::InspectorValue") - -TypeModel.init_class() - - -# Collection of InspectorObject class methods that are likely to be overloaded in generated class. -# We must explicitly import all overloaded methods or they won't be available to user. -INSPECTOR_OBJECT_SETTER_NAMES = frozenset(["setValue", "setBoolean", "setNumber", "setString", "setValue", "setObject", "setArray"]) - - -def fix_type_name(json_name): - if json_name in TYPE_NAME_FIX_MAP: - fixed = TYPE_NAME_FIX_MAP[json_name] - - class Result(object): - class_name = fixed - - @staticmethod - def output_comment(writer): - writer.newline("// Type originally was named '%s'.\n" % json_name) - else: - - class Result(object): - class_name = json_name - - @staticmethod - def output_comment(writer): - pass - - return Result - - -class Writer: - def __init__(self, output, indent): - self.output = output - self.indent = indent - - def newline(self, str): - if (self.indent): - self.output.append(self.indent) - self.output.append(str) - - def append(self, str): - self.output.append(str) - - def newline_multiline(self, str): - parts = str.split('\n') - self.newline(parts[0]) - for p in parts[1:]: - self.output.append('\n') - if p: - self.newline(p) - - def append_multiline(self, str): - parts = str.split('\n') - self.append(parts[0]) - for p in parts[1:]: - self.output.append('\n') - if p: - self.newline(p) - - def get_indent(self): - return self.indent - - def get_indented(self, additional_indent): - return Writer(self.output, self.indent + additional_indent) - - def insert_writer(self, additional_indent): - new_output = [] - self.output.append(new_output) - return Writer(new_output, self.indent + additional_indent) - - -class EnumConstants: - map_ = {} - constants_ = [] - - @classmethod - def add_constant(cls, value): - if value in cls.map_: - return cls.map_[value] - else: - pos = len(cls.map_) - cls.map_[value] = pos - cls.constants_.append(value) - return pos - - @classmethod - def get_enum_constant_code(cls): - output = [] - for item in cls.constants_: - output.append(" \"" + item + "\"") - return ",\n".join(output) + "\n" - - -# Typebuilder code is generated in several passes: first typedefs, then other classes. -# Manual pass management is needed because we cannot have forward declarations for typedefs. -class TypeBuilderPass: - TYPEDEF = "typedef" - MAIN = "main" - - -class TypeBindings: - @staticmethod - def create_named_type_declaration(json_typable, context_domain_name, type_data): - json_type = type_data.get_json_type() - - class Helper: - is_ad_hoc = False - full_name_prefix_for_use = "Inspector::TypeBuilder::" + context_domain_name + "::" - full_name_prefix_for_impl = "Inspector::TypeBuilder::" + context_domain_name + "::" - - @staticmethod - def write_doc(writer): - if "description" in json_type: - writer.newline("/* ") - writer.append(json_type["description"]) - writer.append(" */\n") - - @staticmethod - def add_to_forward_listener(forward_listener): - forward_listener.add_type_data(type_data) - - - fixed_type_name = fix_type_name(json_type["id"]) - return TypeBindings.create_type_declaration_(json_typable, context_domain_name, fixed_type_name, Helper) - - @staticmethod - def create_ad_hoc_type_declaration(json_typable, context_domain_name, ad_hoc_type_context): - class Helper: - is_ad_hoc = True - full_name_prefix_for_use = ad_hoc_type_context.container_relative_name_prefix - full_name_prefix_for_impl = ad_hoc_type_context.container_full_name_prefix - - @staticmethod - def write_doc(writer): - pass - - @staticmethod - def add_to_forward_listener(forward_listener): - pass - fixed_type_name = ad_hoc_type_context.get_type_name_fix() - return TypeBindings.create_type_declaration_(json_typable, context_domain_name, fixed_type_name, Helper) - - @staticmethod - def create_type_declaration_(json_typable, context_domain_name, fixed_type_name, helper): - if json_typable["type"] == "string": - if "enum" in json_typable: - - class EnumBinding: - need_user_runtime_cast_ = False - need_internal_runtime_cast_ = False - - @classmethod - def resolve_inner(cls, resolve_context): - pass - - @classmethod - def request_user_runtime_cast(cls, request): - if request: - cls.need_user_runtime_cast_ = True - request.acknowledge() - - @classmethod - def request_internal_runtime_cast(cls): - cls.need_internal_runtime_cast_ = True - - @classmethod - def get_code_generator(enum_binding_cls): - #FIXME: generate ad-hoc enums too once we figure out how to better implement them in C++. - comment_out = helper.is_ad_hoc - - class CodeGenerator: - @staticmethod - def generate_type_builder(writer, generate_context): - enum = json_typable["enum"] - helper.write_doc(writer) - enum_name = fixed_type_name.class_name - fixed_type_name.output_comment(writer) - writer.newline("struct ") - writer.append(enum_name) - writer.append(" {\n") - writer.newline(" enum Enum {\n") - for enum_item in enum: - enum_pos = EnumConstants.add_constant(enum_item) - - item_c_name = fix_camel_case(enum_item) - if item_c_name in TYPE_NAME_FIX_MAP: - item_c_name = TYPE_NAME_FIX_MAP[item_c_name] - writer.newline(" ") - writer.append(item_c_name) - writer.append(" = ") - writer.append("%s" % enum_pos) - writer.append(",\n") - writer.newline(" };\n") - if enum_binding_cls.need_user_runtime_cast_: - raise Exception("Not yet implemented") - - if enum_binding_cls.need_internal_runtime_cast_: - writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME) - writer.newline(" static void assertCorrectValue(Inspector::InspectorValue* value);\n") - writer.append("#endif // %s\n" % VALIDATOR_IFDEF_NAME) - - validator_writer = generate_context.validator_writer - - domain_fixes = DomainNameFixes.get_fixed_data(context_domain_name) - domain_guard = domain_fixes.get_guard() - if domain_guard: - domain_guard.generate_open(validator_writer) - - validator_writer.newline("void %s%s::assertCorrectValue(Inspector::InspectorValue* value)\n" % (helper.full_name_prefix_for_impl, enum_name)) - validator_writer.newline("{\n") - validator_writer.newline(" WTF::String s;\n") - validator_writer.newline(" bool cast_res = value->asString(&s);\n") - validator_writer.newline(" ASSERT(cast_res);\n") - if len(enum) > 0: - condition_list = [] - for enum_item in enum: - enum_pos = EnumConstants.add_constant(enum_item) - condition_list.append("s == \"%s\"" % enum_item) - validator_writer.newline(" ASSERT(%s);\n" % " || ".join(condition_list)) - validator_writer.newline("}\n") - - if domain_guard: - domain_guard.generate_close(validator_writer) - - validator_writer.newline("\n\n") - - writer.newline("}; // struct ") - writer.append(enum_name) - writer.append("\n") - - @staticmethod - def register_use(forward_listener): - pass - - @staticmethod - def get_generate_pass_id(): - return TypeBuilderPass.MAIN - - return CodeGenerator - - @classmethod - def get_validator_call_text(cls): - return helper.full_name_prefix_for_use + fixed_type_name.class_name + "::assertCorrectValue" - - @classmethod - def get_array_item_c_type_text(cls): - return helper.full_name_prefix_for_use + fixed_type_name.class_name + "::Enum" - - @staticmethod - def get_setter_value_expression_pattern(): - return "Inspector::TypeBuilder::get%sEnumConstantValue(%s)" - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.String - - @staticmethod - def get_type_model(): - return TypeModel.Enum(helper.full_name_prefix_for_use + fixed_type_name.class_name) - - return EnumBinding - else: - if helper.is_ad_hoc: - - class PlainString: - @classmethod - def resolve_inner(cls, resolve_context): - pass - - @staticmethod - def request_user_runtime_cast(request): - raise Exception("Unsupported") - - @staticmethod - def request_internal_runtime_cast(): - pass - - @staticmethod - def get_code_generator(): - return None - - @classmethod - def get_validator_call_text(cls): - return RawTypes.String.get_raw_validator_call_text() - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.String - - @staticmethod - def get_type_model(): - return TypeModel.String - - @staticmethod - def get_setter_value_expression_pattern(): - return None - - @classmethod - def get_array_item_c_type_text(cls): - return cls.reduce_to_raw_type().get_array_item_raw_c_type_text() - - return PlainString - - else: - - class TypedefString: - @classmethod - def resolve_inner(cls, resolve_context): - pass - - @staticmethod - def request_user_runtime_cast(request): - raise Exception("Unsupported") - - @staticmethod - def request_internal_runtime_cast(): - RawTypes.String.request_raw_internal_runtime_cast() - - @staticmethod - def get_code_generator(): - class CodeGenerator: - @staticmethod - def generate_type_builder(writer, generate_context): - helper.write_doc(writer) - fixed_type_name.output_comment(writer) - writer.newline("typedef String ") - writer.append(fixed_type_name.class_name) - writer.append(";\n\n") - - @staticmethod - def register_use(forward_listener): - pass - - @staticmethod - def get_generate_pass_id(): - return TypeBuilderPass.TYPEDEF - - return CodeGenerator - - @classmethod - def get_validator_call_text(cls): - return RawTypes.String.get_raw_validator_call_text() - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.String - - @staticmethod - def get_type_model(): - return TypeModel.ValueType("%s%s" % (helper.full_name_prefix_for_use, fixed_type_name.class_name), True) - - @staticmethod - def get_setter_value_expression_pattern(): - return None - - @classmethod - def get_array_item_c_type_text(cls): - return "const %s%s&" % (helper.full_name_prefix_for_use, fixed_type_name.class_name) - - return TypedefString - - elif json_typable["type"] == "integer": - if helper.is_ad_hoc: - - class PlainInteger: - @classmethod - def resolve_inner(cls, resolve_context): - pass - - @staticmethod - def request_user_runtime_cast(request): - raise Exception("Unsupported") - - @staticmethod - def request_internal_runtime_cast(): - pass - - @staticmethod - def get_code_generator(): - return None - - @classmethod - def get_validator_call_text(cls): - return RawTypes.Int.get_raw_validator_call_text() - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.Int - - @staticmethod - def get_type_model(): - return TypeModel.Int - - @staticmethod - def get_setter_value_expression_pattern(): - return None - - @classmethod - def get_array_item_c_type_text(cls): - return cls.reduce_to_raw_type().get_array_item_raw_c_type_text() - - return PlainInteger - - else: - - class TypedefInteger: - @classmethod - def resolve_inner(cls, resolve_context): - pass - - @staticmethod - def request_user_runtime_cast(request): - raise Exception("Unsupported") - - @staticmethod - def request_internal_runtime_cast(): - RawTypes.Int.request_raw_internal_runtime_cast() - - @staticmethod - def get_code_generator(): - class CodeGenerator: - @staticmethod - def generate_type_builder(writer, generate_context): - helper.write_doc(writer) - fixed_type_name.output_comment(writer) - writer.newline("typedef int ") - writer.append(fixed_type_name.class_name) - writer.append(";\n\n") - - @staticmethod - def register_use(forward_listener): - pass - - @staticmethod - def get_generate_pass_id(): - return TypeBuilderPass.TYPEDEF - - return CodeGenerator - - @classmethod - def get_validator_call_text(cls): - return RawTypes.Int.get_raw_validator_call_text() - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.Int - - @staticmethod - def get_type_model(): - return TypeModel.Int - - @staticmethod - def get_setter_value_expression_pattern(): - return None - - @classmethod - def get_array_item_c_type_text(cls): - return helper.full_name_prefix_for_use + fixed_type_name.class_name - - return TypedefInteger - - elif json_typable["type"] == "object": - if "properties" in json_typable: - - class ClassBinding: - resolve_data_ = None - need_user_runtime_cast_ = False - need_internal_runtime_cast_ = False - - @classmethod - def resolve_inner(cls, resolve_context): - if cls.resolve_data_: - return - - properties = json_typable["properties"] - main = [] - optional = [] - - ad_hoc_type_list = [] - - for prop in properties: - prop_name = prop["name"] - ad_hoc_type_context = cls.AdHocTypeContextImpl(prop_name, fixed_type_name.class_name, resolve_context, ad_hoc_type_list, helper.full_name_prefix_for_impl) - binding = resolve_param_type(prop, context_domain_name, ad_hoc_type_context) - - code_generator = binding.get_code_generator() - if code_generator: - code_generator.register_use(resolve_context.forward_listener) - - class PropertyData: - param_type_binding = binding - p = prop - - if prop.get("optional"): - optional.append(PropertyData) - else: - main.append(PropertyData) - - class ResolveData: - main_properties = main - optional_properties = optional - ad_hoc_types = ad_hoc_type_list - - cls.resolve_data_ = ResolveData - - for ad_hoc in ad_hoc_type_list: - ad_hoc.resolve_inner(resolve_context) - - @classmethod - def request_user_runtime_cast(cls, request): - if not request: - return - cls.need_user_runtime_cast_ = True - request.acknowledge() - cls.request_internal_runtime_cast() - - @classmethod - def request_internal_runtime_cast(cls): - if cls.need_internal_runtime_cast_: - return - cls.need_internal_runtime_cast_ = True - for p in cls.resolve_data_.main_properties: - p.param_type_binding.request_internal_runtime_cast() - for p in cls.resolve_data_.optional_properties: - p.param_type_binding.request_internal_runtime_cast() - - @classmethod - def get_code_generator(class_binding_cls): - class CodeGenerator: - @classmethod - def generate_type_builder(cls, writer, generate_context): - resolve_data = class_binding_cls.resolve_data_ - helper.write_doc(writer) - class_name = fixed_type_name.class_name - - is_open_type = (context_domain_name + "." + class_name) in TYPES_WITH_OPEN_FIELD_LIST_SET - - fixed_type_name.output_comment(writer) - writer.newline("class ") - writer.append(class_name) - writer.append(" : public ") - if is_open_type: - writer.append("Inspector::InspectorObject") - else: - writer.append("Inspector::InspectorObjectBase") - writer.append(" {\n") - writer.newline("public:\n") - ad_hoc_type_writer = writer.insert_writer(" ") - - for ad_hoc_type in resolve_data.ad_hoc_types: - code_generator = ad_hoc_type.get_code_generator() - if code_generator: - code_generator.generate_type_builder(ad_hoc_type_writer, generate_context) - - writer.newline_multiline( -""" enum { - NoFieldsSet = 0, -""") - - state_enum_items = [] - if len(resolve_data.main_properties) > 0: - pos = 0 - for prop_data in resolve_data.main_properties: - item_name = Capitalizer.lower_camel_case_to_upper(prop_data.p["name"]) + "Set" - state_enum_items.append(item_name) - writer.newline(" %s = 1 << %s,\n" % (item_name, pos)) - pos += 1 - all_fields_set_value = "(" + (" | ".join(state_enum_items)) + ")" - else: - all_fields_set_value = "0" - - writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_1 - % (all_fields_set_value, class_name, class_name)) - - pos = 0 - for prop_data in resolve_data.main_properties: - prop_name = prop_data.p["name"] - - param_type_binding = prop_data.param_type_binding - param_raw_type = param_type_binding.reduce_to_raw_type() - - writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_2 - % (state_enum_items[pos], - Capitalizer.lower_camel_case_to_upper(prop_name), - param_type_binding.get_type_model().get_input_param_type_text(), - state_enum_items[pos], prop_name, - param_raw_type.get_setter_name(), prop_name, - format_setter_value_expression(param_type_binding, "value"), - state_enum_items[pos])) - - pos += 1 - - writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_3 - % (class_name, class_name, class_name, class_name, class_name)) - - writer.newline(" /*\n") - writer.newline(" * Synthetic constructor:\n") - writer.newline(" * RefPtr<%s> result = %s::create()" % (class_name, class_name)) - for prop_data in resolve_data.main_properties: - writer.append_multiline("\n * .set%s(...)" % Capitalizer.lower_camel_case_to_upper(prop_data.p["name"])) - writer.append_multiline(";\n */\n") - - writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_4) - - writer.newline(" typedef Inspector::TypeBuilder::StructItemTraits ItemTraits;\n") - - for prop_data in resolve_data.optional_properties: - prop_name = prop_data.p["name"] - param_type_binding = prop_data.param_type_binding - setter_name = "set%s" % Capitalizer.lower_camel_case_to_upper(prop_name) - - writer.append_multiline("\n void %s" % setter_name) - writer.append("(%s value)\n" % param_type_binding.get_type_model().get_input_param_type_text()) - writer.newline(" {\n") - writer.newline(" this->set%s(ASCIILiteral(\"%s\"), %s);\n" - % (param_type_binding.reduce_to_raw_type().get_setter_name(), prop_data.p["name"], - format_setter_value_expression(param_type_binding, "value"))) - writer.newline(" }\n") - - - if setter_name in INSPECTOR_OBJECT_SETTER_NAMES: - writer.newline(" using Inspector::InspectorObjectBase::%s;\n\n" % setter_name) - - if class_binding_cls.need_user_runtime_cast_: - writer.newline(" static PassRefPtr<%s> runtimeCast(PassRefPtr<Inspector::InspectorValue> value)\n" % class_name) - writer.newline(" {\n") - writer.newline(" RefPtr<Inspector::InspectorObject> object;\n") - writer.newline(" bool castRes = value->asObject(&object);\n") - writer.newline(" ASSERT_UNUSED(castRes, castRes);\n") - writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME) - writer.newline(" assertCorrectValue(object.get());\n") - writer.append("#endif // %s\n" % VALIDATOR_IFDEF_NAME) - writer.newline(" COMPILE_ASSERT(sizeof(%s) == sizeof(Inspector::InspectorObjectBase), type_cast_problem);\n" % class_name) - writer.newline(" return static_cast<%s*>(static_cast<Inspector::InspectorObjectBase*>(object.get()));\n" % class_name) - writer.newline(" }\n") - writer.append("\n") - - if class_binding_cls.need_internal_runtime_cast_: - writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME) - writer.newline(" static %s void assertCorrectValue(Inspector::InspectorValue* value);\n" % INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["export_macro"]) - writer.append("#endif // %s\n" % VALIDATOR_IFDEF_NAME) - - closed_field_set = (context_domain_name + "." + class_name) not in TYPES_WITH_OPEN_FIELD_LIST_SET - - validator_writer = generate_context.validator_writer - - domain_fixes = DomainNameFixes.get_fixed_data(context_domain_name) - domain_guard = domain_fixes.get_guard() - if domain_guard: - domain_guard.generate_open(validator_writer) - - validator_writer.newline("void %s%s::assertCorrectValue(Inspector::InspectorValue* value)\n" % (helper.full_name_prefix_for_impl, class_name)) - validator_writer.newline("{\n") - validator_writer.newline(" RefPtr<InspectorObject> object;\n") - validator_writer.newline(" bool castRes = value->asObject(&object);\n") - validator_writer.newline(" ASSERT_UNUSED(castRes, castRes);\n") - for prop_data in resolve_data.main_properties: - validator_writer.newline(" {\n") - it_name = "%sPos" % prop_data.p["name"] - validator_writer.newline(" InspectorObject::iterator %s;\n" % it_name) - validator_writer.newline(" %s = object->find(\"%s\");\n" % (it_name, prop_data.p["name"])) - validator_writer.newline(" ASSERT(%s != object->end());\n" % it_name) - validator_writer.newline(" %s(%s->value.get());\n" % (prop_data.param_type_binding.get_validator_call_text(), it_name)) - validator_writer.newline(" }\n") - - if closed_field_set: - validator_writer.newline(" int foundPropertiesCount = %s;\n" % len(resolve_data.main_properties)) - - for prop_data in resolve_data.optional_properties: - validator_writer.newline(" {\n") - it_name = "%sPos" % prop_data.p["name"] - validator_writer.newline(" InspectorObject::iterator %s;\n" % it_name) - validator_writer.newline(" %s = object->find(\"%s\");\n" % (it_name, prop_data.p["name"])) - validator_writer.newline(" if (%s != object->end()) {\n" % it_name) - validator_writer.newline(" %s(%s->value.get());\n" % (prop_data.param_type_binding.get_validator_call_text(), it_name)) - if closed_field_set: - validator_writer.newline(" ++foundPropertiesCount;\n") - validator_writer.newline(" }\n") - validator_writer.newline(" }\n") - - if closed_field_set: - validator_writer.newline(" if (foundPropertiesCount != object->size())\n") - validator_writer.newline(" FATAL(\"Unexpected properties in object: %s\\n\", object->toJSONString().ascii().data());\n") - validator_writer.newline("}\n") - - if domain_guard: - domain_guard.generate_close(validator_writer) - - validator_writer.newline("\n\n") - - if is_open_type: - cpp_writer = generate_context.cpp_writer - writer.append("\n") - writer.newline(" // Property names for type generated as open.\n") - for prop_data in resolve_data.main_properties + resolve_data.optional_properties: - prop_name = prop_data.p["name"] - prop_field_name = Capitalizer.lower_camel_case_to_upper(prop_name) - writer.newline(" static const char* %s;\n" % (prop_field_name)) - cpp_writer.newline("const char* %s%s::%s = \"%s\";\n" % (helper.full_name_prefix_for_impl, class_name, prop_field_name, prop_name)) - - - writer.newline("};\n\n") - - @staticmethod - def generate_forward_declaration(writer): - class_name = fixed_type_name.class_name - writer.newline("class ") - writer.append(class_name) - writer.append(";\n") - - @staticmethod - def register_use(forward_listener): - helper.add_to_forward_listener(forward_listener) - - @staticmethod - def get_generate_pass_id(): - return TypeBuilderPass.MAIN - - return CodeGenerator - - @staticmethod - def get_validator_call_text(): - return helper.full_name_prefix_for_use + fixed_type_name.class_name + "::assertCorrectValue" - - @classmethod - def get_array_item_c_type_text(cls): - return helper.full_name_prefix_for_use + fixed_type_name.class_name - - @staticmethod - def get_setter_value_expression_pattern(): - return None - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.Object - - @staticmethod - def get_type_model(): - return TypeModel.RefPtrBased(helper.full_name_prefix_for_use + fixed_type_name.class_name) - - class AdHocTypeContextImpl: - def __init__(self, property_name, class_name, resolve_context, ad_hoc_type_list, parent_full_name_prefix): - self.property_name = property_name - self.class_name = class_name - self.resolve_context = resolve_context - self.ad_hoc_type_list = ad_hoc_type_list - self.container_full_name_prefix = parent_full_name_prefix + class_name + "::" - self.container_relative_name_prefix = "" - - def get_type_name_fix(self): - class NameFix: - class_name = Capitalizer.lower_camel_case_to_upper(self.property_name) - - @staticmethod - def output_comment(writer): - writer.newline("// Named after property name '%s' while generating %s.\n" % (self.property_name, self.class_name)) - - return NameFix - - def add_type(self, binding): - self.ad_hoc_type_list.append(binding) - - return ClassBinding - else: - - class PlainObjectBinding: - @classmethod - def resolve_inner(cls, resolve_context): - pass - - @staticmethod - def request_user_runtime_cast(request): - pass - - @staticmethod - def request_internal_runtime_cast(): - RawTypes.Object.request_raw_internal_runtime_cast() - - @staticmethod - def get_code_generator(): - pass - - @staticmethod - def get_validator_call_text(): - return "RuntimeCastHelper::assertType<InspectorValue::TypeObject>" - - @classmethod - def get_array_item_c_type_text(cls): - return cls.reduce_to_raw_type().get_array_item_raw_c_type_text() - - @staticmethod - def get_setter_value_expression_pattern(): - return None - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.Object - - @staticmethod - def get_type_model(): - return TypeModel.Object - - return PlainObjectBinding - elif json_typable["type"] == "array": - if "items" in json_typable: - - ad_hoc_types = [] - - class AdHocTypeContext: - container_full_name_prefix = "<not yet defined>" - container_relative_name_prefix = "" - - @staticmethod - def get_type_name_fix(): - return fixed_type_name - - @staticmethod - def add_type(binding): - ad_hoc_types.append(binding) - - item_binding = resolve_param_type(json_typable["items"], context_domain_name, AdHocTypeContext) - - class ArrayBinding: - resolve_data_ = None - need_internal_runtime_cast_ = False - - @classmethod - def resolve_inner(cls, resolve_context): - if cls.resolve_data_: - return - - class ResolveData: - item_type_binding = item_binding - ad_hoc_type_list = ad_hoc_types - - cls.resolve_data_ = ResolveData - - for t in ad_hoc_types: - t.resolve_inner(resolve_context) - - @classmethod - def request_user_runtime_cast(cls, request): - raise Exception("Not implemented yet") - - @classmethod - def request_internal_runtime_cast(cls): - if cls.need_internal_runtime_cast_: - return - cls.need_internal_runtime_cast_ = True - cls.resolve_data_.item_type_binding.request_internal_runtime_cast() - - @classmethod - def get_code_generator(array_binding_cls): - - class CodeGenerator: - @staticmethod - def generate_type_builder(writer, generate_context): - ad_hoc_type_writer = writer - - resolve_data = array_binding_cls.resolve_data_ - - for ad_hoc_type in resolve_data.ad_hoc_type_list: - code_generator = ad_hoc_type.get_code_generator() - if code_generator: - code_generator.generate_type_builder(ad_hoc_type_writer, generate_context) - - @staticmethod - def generate_forward_declaration(writer): - pass - - @staticmethod - def register_use(forward_listener): - item_code_generator = item_binding.get_code_generator() - if item_code_generator: - item_code_generator.register_use(forward_listener) - - @staticmethod - def get_generate_pass_id(): - return TypeBuilderPass.MAIN - - return CodeGenerator - - @classmethod - def get_validator_call_text(cls): - return cls.get_array_item_c_type_text() + "::assertCorrectValue" - - @classmethod - def get_array_item_c_type_text(cls): - return replace_right_shift("Inspector::TypeBuilder::Array<%s>" % cls.resolve_data_.item_type_binding.get_array_item_c_type_text()) - - @staticmethod - def get_setter_value_expression_pattern(): - return None - - @staticmethod - def reduce_to_raw_type(): - return RawTypes.Array - - @classmethod - def get_type_model(cls): - return TypeModel.RefPtrBased(cls.get_array_item_c_type_text()) - - return ArrayBinding - else: - # Fall-through to raw type. - pass - - raw_type = RawTypes.get(json_typable["type"]) - - return RawTypeBinding(raw_type) - - -class RawTypeBinding: - def __init__(self, raw_type): - self.raw_type_ = raw_type - - def resolve_inner(self, resolve_context): - pass - - def request_user_runtime_cast(self, request): - raise Exception("Unsupported") - - def request_internal_runtime_cast(self): - self.raw_type_.request_raw_internal_runtime_cast() - - def get_code_generator(self): - return None - - def get_validator_call_text(self): - return self.raw_type_.get_raw_validator_call_text() - - def get_array_item_c_type_text(self): - return self.raw_type_.get_array_item_raw_c_type_text() - - def get_setter_value_expression_pattern(self): - return None - - def reduce_to_raw_type(self): - return self.raw_type_ - - def get_type_model(self): - return self.raw_type_.get_raw_type_model() - - -class TypeData(object): - def __init__(self, json_type, json_domain, domain_data): - self.json_type_ = json_type - self.json_domain_ = json_domain - self.domain_data_ = domain_data - - if "type" not in json_type: - raise Exception("Unknown type") - - json_type_name = json_type["type"] - self.raw_type_ = RawTypes.get(json_type_name) - self.binding_being_resolved_ = False - self.binding_ = None - - def get_raw_type(self): - return self.raw_type_ - - def get_binding(self): - if not self.binding_: - if self.binding_being_resolved_: - raise Exception("Type %s is already being resolved" % self.json_type_["type"]) - # Resolve only lazily, because resolving one named type may require resolving some other named type. - self.binding_being_resolved_ = True - try: - self.binding_ = TypeBindings.create_named_type_declaration(self.json_type_, self.json_domain_["domain"], self) - finally: - self.binding_being_resolved_ = False - - return self.binding_ - - def get_json_type(self): - return self.json_type_ - - def get_name(self): - return self.json_type_["id"] - - def get_domain_name(self): - return self.json_domain_["domain"] - - -class DomainData: - def __init__(self, json_domain): - self.json_domain = json_domain - self.types_ = [] - - def add_type(self, type_data): - self.types_.append(type_data) - - def name(self): - return self.json_domain["domain"] - - def types(self): - return self.types_ - - -class TypeMap: - def __init__(self, api, dependency_api): - self.map_ = {} - self.domains_ = [] - self.domains_to_generate_ = [] - for json_domain in api["domains"]: - self.add_domain(json_domain, True) - for json_domain in dependency_api["domains"]: - self.add_domain(json_domain, False) - - def add_domain(self, json_domain, should_generate): - domain_name = json_domain["domain"] - - domain_map = {} - self.map_[domain_name] = domain_map - - domain_data = DomainData(json_domain) - self.domains_.append(domain_data) - - if should_generate: - # FIXME: The order of types should not matter. The generated code should work regardless of the order of types. - if domain_name == "Page": - self.domains_to_generate_.insert(0, domain_data) - else: - self.domains_to_generate_.append(domain_data) - - if "types" in json_domain: - for json_type in json_domain["types"]: - type_name = json_type["id"] - type_data = TypeData(json_type, json_domain, domain_data) - domain_map[type_name] = type_data - domain_data.add_type(type_data) - - def domains(self): - return self.domains_ - - def domains_to_generate(self): - return self.domains_to_generate_ - - def get(self, domain_name, type_name): - return self.map_[domain_name][type_name] - - -def resolve_param_type(json_parameter, scope_domain_name, ad_hoc_type_context): - if "$ref" in json_parameter: - json_ref = json_parameter["$ref"] - type_data = get_ref_data(json_ref, scope_domain_name) - return type_data.get_binding() - elif "type" in json_parameter: - result = TypeBindings.create_ad_hoc_type_declaration(json_parameter, scope_domain_name, ad_hoc_type_context) - ad_hoc_type_context.add_type(result) - return result - else: - raise Exception("Unknown type") - - -def resolve_param_raw_type(json_parameter, scope_domain_name): - if "$ref" in json_parameter: - json_ref = json_parameter["$ref"] - type_data = get_ref_data(json_ref, scope_domain_name) - return type_data.get_raw_type() - elif "type" in json_parameter: - json_type = json_parameter["type"] - return RawTypes.get(json_type) - else: - raise Exception("Unknown type") - - -def get_ref_data(json_ref, scope_domain_name): - dot_pos = json_ref.find(".") - if dot_pos == -1: - domain_name = scope_domain_name - type_name = json_ref - else: - domain_name = json_ref[:dot_pos] - type_name = json_ref[dot_pos + 1:] - - return type_map.get(domain_name, type_name) - - -input_file = open(input_json_filename, "r") -json_string = input_file.read() -json_api = json.loads(json_string) -input_file.close() -if not "domains" in json_api: - json_api = {"domains": [json_api]} - -dependency_api = {"domains": []} -for dependency_json_filename in dependency_json_filenames: - dependency_input_file = open(dependency_json_filename, "r") - dependency_json_string = dependency_input_file.read() - dependency_json_api = json.loads(dependency_json_string) - dependency_input_file.close() - if not "domains" in dependency_json_api: - dependency_json_api = {"domains": [dependency_json_api]} - dependency_api["domains"] += dependency_json_api["domains"] - - -class Templates: - def get_this_script_path_(absolute_path): - absolute_path = os.path.abspath(absolute_path) - components = [] - - def fill_recursive(path_part, depth): - if depth <= 0 or path_part == '/': - return - fill_recursive(os.path.dirname(path_part), depth - 1) - components.append(os.path.basename(path_part)) - - # Typical path is /Source/WebCore/inspector/CodeGeneratorInspector.py - # Let's take 4 components from the real path then. - fill_recursive(absolute_path, 4) - - return "/".join(components) - - file_header_ = ("// File is generated by %s\n\n" % get_this_script_path_(sys.argv[0]) + -"""// Copyright (c) 2013 Apple Inc. All Rights Reserved. -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -""") - - frontend_domain_class = string.Template(CodeGeneratorInspectorStrings.frontend_domain_class) - backend_dispatcher_constructor = string.Template(CodeGeneratorInspectorStrings.backend_dispatcher_constructor) - backend_dispatcher_dispatch_method = string.Template(CodeGeneratorInspectorStrings.backend_dispatcher_dispatch_method) - backend_dispatcher_dispatch_method_simple = string.Template(CodeGeneratorInspectorStrings.backend_dispatcher_dispatch_method_simple) - backend_method = string.Template(CodeGeneratorInspectorStrings.backend_method) - frontend_method = string.Template(CodeGeneratorInspectorStrings.frontend_method) - callback_method = string.Template(CodeGeneratorInspectorStrings.callback_method) - frontend_h = string.Template(file_header_ + CodeGeneratorInspectorStrings.frontend_h) - backend_h = string.Template(file_header_ + CodeGeneratorInspectorStrings.backend_h) - backend_cpp = string.Template(file_header_ + CodeGeneratorInspectorStrings.backend_cpp) - frontend_cpp = string.Template(file_header_ + CodeGeneratorInspectorStrings.frontend_cpp) - typebuilder_h = string.Template(file_header_ + CodeGeneratorInspectorStrings.typebuilder_h) - typebuilder_cpp = string.Template(file_header_ + CodeGeneratorInspectorStrings.typebuilder_cpp) - backend_js = string.Template(file_header_ + CodeGeneratorInspectorStrings.backend_js) - param_container_access_code = CodeGeneratorInspectorStrings.param_container_access_code - - - - - -type_map = TypeMap(json_api, dependency_api) - - -class NeedRuntimeCastRequest: - def __init__(self): - self.ack_ = None - - def acknowledge(self): - self.ack_ = True - - def is_acknowledged(self): - return self.ack_ - - -def resolve_all_types(): - runtime_cast_generate_requests = {} - for type_name in TYPES_WITH_RUNTIME_CAST_SET: - runtime_cast_generate_requests[type_name] = NeedRuntimeCastRequest() - - class ForwardListener: - type_data_set = set() - already_declared_set = set() - - @classmethod - def add_type_data(cls, type_data): - if type_data not in cls.already_declared_set: - cls.type_data_set.add(type_data) - - class ResolveContext: - forward_listener = ForwardListener - - for domain_data in type_map.domains(): - for type_data in domain_data.types(): - binding = type_data.get_binding() - binding.resolve_inner(ResolveContext) - # Do not generate forwards for this type any longer. - ForwardListener.already_declared_set.add(type_data) - - for domain_data in type_map.domains(): - for type_data in domain_data.types(): - full_type_name = "%s.%s" % (type_data.get_domain_name(), type_data.get_name()) - request = runtime_cast_generate_requests.pop(full_type_name, None) - binding = type_data.get_binding() - if request: - binding.request_user_runtime_cast(request) - - if request and not request.is_acknowledged(): - raise Exception("Failed to generate runtimeCast in " + full_type_name) - - # FIXME: This assumes all the domains are processed at once. Change this verification - # to only verify runtime casts for the domains being generated. - # if verification: - # for full_type_name in runtime_cast_generate_requests: - # raise Exception("Failed to generate runtimeCast. Type " + full_type_name + " not found") - - return ForwardListener - - -global_forward_listener = resolve_all_types() - - -def get_annotated_type_text(raw_type, annotated_type): - if annotated_type != raw_type: - return "/*%s*/ %s" % (annotated_type, raw_type) - else: - return raw_type - - -def format_setter_value_expression(param_type_binding, value_ref): - pattern = param_type_binding.get_setter_value_expression_pattern() - if pattern: - return pattern % (INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["prefix"], value_ref) - else: - return value_ref - - -class Generator: - frontend_domain_class_lines = [] - - backend_method_implementation_list = [] - frontend_method_list = [] - backend_js_domain_initializer_list = [] - - backend_handler_interface_list = [] - backend_handler_implementation_list = [] - backend_dispatcher_interface_list = [] - type_builder_fragments = [] - type_builder_forwards = [] - validator_impl_list = [] - type_builder_impl_list = [] - - - @staticmethod - def go(): - Generator.process_types(type_map) - - first_cycle_guardable_list_list = [ - Generator.backend_method_implementation_list, - Generator.backend_handler_interface_list, - Generator.backend_handler_implementation_list, - Generator.backend_dispatcher_interface_list] - - for json_domain in json_api["domains"]: - domain_name = json_domain["domain"] - domain_name_lower = domain_name.lower() - - domain_fixes = DomainNameFixes.get_fixed_data(domain_name) - - domain_guard = domain_fixes.get_guard() - - if domain_guard: - for l in first_cycle_guardable_list_list: - domain_guard.generate_open(l) - - frontend_method_declaration_lines = [] - - if ("commands" in json_domain or "events" in json_domain): - Generator.backend_js_domain_initializer_list.append("// %s.\n" % domain_name) - if not domain_fixes.skip_js_bind: - Generator.backend_js_domain_initializer_list.append("InspectorBackend.register%sDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, \"%s\");\n" % (domain_name, domain_name)) - - if "types" in json_domain: - for json_type in json_domain["types"]: - if "type" in json_type and json_type["type"] == "string" and "enum" in json_type: - enum_name = "%s.%s" % (domain_name, json_type["id"]) - Generator.process_enum(json_type, enum_name) - elif json_type["type"] == "object": - if "properties" in json_type: - for json_property in json_type["properties"]: - if "type" in json_property and json_property["type"] == "string" and "enum" in json_property: - enum_name = "%s.%s%s" % (domain_name, json_type["id"], to_title_case(json_property["name"])) - Generator.process_enum(json_property, enum_name) - - if "events" in json_domain: - if domain_guard: - domain_guard.generate_open(Generator.frontend_method_list) - domain_guard.generate_open(Generator.frontend_domain_class_lines) - - for json_event in json_domain["events"]: - Generator.process_event(json_event, domain_name, frontend_method_declaration_lines) - - Generator.frontend_domain_class_lines.append(Templates.frontend_domain_class.substitute(None, - exportMacro=INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["export_macro"], - domainClassName="Inspector%sFrontendDispatcher" % domain_name, - frontendDomainMethodDeclarations="".join(flatten_list(frontend_method_declaration_lines)))) - - if domain_guard: - domain_guard.generate_close(Generator.frontend_method_list) - domain_guard.generate_close(Generator.frontend_domain_class_lines) - - dispatcher_name = "Inspector" + Capitalizer.lower_camel_case_to_upper(domain_name) + "BackendDispatcher" - agent_interface_name = dispatcher_name + "Handler" - - if "commands" in json_domain: - Generator.backend_dispatcher_interface_list.append("class %s %s final : public Inspector::InspectorSupplementalBackendDispatcher {\n" % (INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["export_macro"], dispatcher_name)) - Generator.backend_dispatcher_interface_list.append("public:\n") - Generator.backend_dispatcher_interface_list.append(" static PassRefPtr<%s> create(Inspector::InspectorBackendDispatcher*, %s*);\n" % (dispatcher_name, agent_interface_name)) - Generator.backend_dispatcher_interface_list.append(" virtual void dispatch(long callId, const String& method, PassRefPtr<Inspector::InspectorObject> message) override;\n") - Generator.backend_dispatcher_interface_list.append("private:\n") - - Generator.backend_handler_interface_list.append("class %s %s {\n" % (INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["export_macro"], agent_interface_name)) - Generator.backend_handler_interface_list.append("public:\n") - - backend_method_count = len(Generator.backend_method_implementation_list) - - dispatcher_if_chain = [] - dispatcher_commands_list = [] - for json_command in json_domain["commands"]: - Generator.process_command(json_command, domain_name, agent_interface_name, dispatcher_name, dispatcher_if_chain, dispatcher_commands_list) - - Generator.backend_handler_interface_list.append("protected:\n") - Generator.backend_handler_interface_list.append(" virtual ~%s();\n" % agent_interface_name) - Generator.backend_handler_interface_list.append("};\n\n") - - Generator.backend_handler_implementation_list.append("%s::~%s() { }\n" % (agent_interface_name, agent_interface_name)) - - Generator.backend_dispatcher_interface_list.append("private:\n") - Generator.backend_dispatcher_interface_list.append(" %s(Inspector::InspectorBackendDispatcher*, %s*);\n" % (dispatcher_name, agent_interface_name)) - Generator.backend_dispatcher_interface_list.append(" %s* m_agent;\n" % agent_interface_name) - Generator.backend_dispatcher_interface_list.append("};\n\n") - - Generator.backend_method_implementation_list.insert(backend_method_count, Templates.backend_dispatcher_constructor.substitute(None, - domainName=domain_name, - dispatcherName=dispatcher_name, - agentName=agent_interface_name)) - - if len(json_domain["commands"]) <= 5: - Generator.backend_method_implementation_list.insert(backend_method_count + 1, Templates.backend_dispatcher_dispatch_method_simple.substitute(None, - domainName=domain_name, - dispatcherName=dispatcher_name, - ifChain="\n".join(dispatcher_if_chain))) - else: - Generator.backend_method_implementation_list.insert(backend_method_count + 1, Templates.backend_dispatcher_dispatch_method.substitute(None, - domainName=domain_name, - dispatcherName=dispatcher_name, - dispatcherCommands="\n".join(dispatcher_commands_list))) - - if domain_guard: - for l in reversed(first_cycle_guardable_list_list): - domain_guard.generate_close(l) - Generator.backend_js_domain_initializer_list.append("\n") - - @staticmethod - def process_enum(json_enum, enum_name): - enum_members = [] - for member in json_enum["enum"]: - enum_members.append("%s: \"%s\"" % (fix_camel_case(member), member)) - - Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEnum(\"%s\", {%s});\n" % ( - enum_name, ", ".join(enum_members))) - - @staticmethod - def process_event(json_event, domain_name, frontend_method_declaration_lines): - event_name = json_event["name"] - - ad_hoc_type_output = [] - frontend_method_declaration_lines.append(ad_hoc_type_output) - ad_hoc_type_writer = Writer(ad_hoc_type_output, " ") - - decl_parameter_list = [] - - json_parameters = json_event.get("parameters") - Generator.generate_send_method(json_parameters, event_name, domain_name, ad_hoc_type_writer, - decl_parameter_list, - Generator.EventMethodStructTemplate, - Generator.frontend_method_list, Templates.frontend_method, {"eventName": event_name}) - - backend_js_event_param_list = [] - if json_parameters: - for parameter in json_parameters: - parameter_name = parameter["name"] - backend_js_event_param_list.append("\"%s\"" % parameter_name) - - frontend_method_declaration_lines.append( - " void %s(%s);\n" % (event_name, ", ".join(decl_parameter_list))) - - Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEvent(\"%s.%s\", [%s]);\n" % ( - domain_name, event_name, ", ".join(backend_js_event_param_list))) - - class EventMethodStructTemplate: - @staticmethod - def append_prolog(line_list): - line_list.append(" RefPtr<InspectorObject> paramsObject = InspectorObject::create();\n") - - @staticmethod - def append_epilog(line_list): - line_list.append(" jsonMessage->setObject(ASCIILiteral(\"params\"), paramsObject);\n") - - container_name = "paramsObject" - - @staticmethod - def process_command(json_command, domain_name, agent_interface_name, dispatcher_name, dispatcher_if_chain, dispatcher_commands_list): - json_command_name = json_command["name"] - - ad_hoc_type_output = [] - Generator.backend_handler_interface_list.append(ad_hoc_type_output) - ad_hoc_type_writer = Writer(ad_hoc_type_output, " ") - - Generator.backend_dispatcher_interface_list.append(" void %s(long callId, const Inspector::InspectorObject& message);\n" % json_command_name) - - Generator.backend_handler_interface_list.append(" virtual void %s(ErrorString*" % json_command_name) - - if not dispatcher_if_chain: - dispatcher_if_chain.append(" if (method == \"%s\")" % json_command_name) - else: - dispatcher_if_chain.append(" else if (method == \"%s\")" % json_command_name) - dispatcher_if_chain.append(" %s(callId, *message.get());" % json_command_name) - dispatcher_commands_list.append(" { \"%s\", &%s::%s }," % (json_command_name, dispatcher_name, json_command_name)) - - method_in_params_handling = [] - method_dispatch_handling = [] - method_out_params_handling = [] - method_ending_handling = [] - method_request_message_param_name = "" - agent_call_param_list = [] - js_parameters_text = "" - if "parameters" in json_command: - json_params = json_command["parameters"] - method_request_message_param_name = " message" - method_in_params_handling.append(" RefPtr<InspectorArray> protocolErrors = InspectorArray::create();\n") - method_in_params_handling.append(" RefPtr<InspectorObject> paramsContainer = message.getObject(ASCIILiteral(\"params\"));\n") - method_in_params_handling.append(" InspectorObject* paramsContainerPtr = paramsContainer.get();\n") - method_in_params_handling.append(" InspectorArray* protocolErrorsPtr = protocolErrors.get();\n") - js_param_list = [] - - for json_parameter in json_params: - json_param_name = json_parameter["name"] - param_raw_type = resolve_param_raw_type(json_parameter, domain_name) - - getter_name = param_raw_type.get_getter_name() - - optional = json_parameter.get("optional") - - non_optional_type_model = param_raw_type.get_raw_type_model() - if optional: - type_model = non_optional_type_model.get_optional() - else: - type_model = non_optional_type_model - - if optional: - code = (" bool %s_valueFound = false;\n" - " %s in_%s = InspectorBackendDispatcher::get%s(paramsContainerPtr, ASCIILiteral(\"%s\"), &%s_valueFound, protocolErrorsPtr);\n" % - (json_param_name, non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name, getter_name, json_param_name, json_param_name)) - param = ", %s_valueFound ? &in_%s : nullptr" % (json_param_name, json_param_name) - # FIXME: pass optional refptr-values as PassRefPtr - formal_param_type_pattern = "const %s*" - else: - code = (" %s in_%s = InspectorBackendDispatcher::get%s(paramsContainerPtr, ASCIILiteral(\"%s\"), nullptr, protocolErrorsPtr);\n" % - (non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name, getter_name, json_param_name)) - param = ", in_%s" % json_param_name - # FIXME: pass not-optional refptr-values as NonNullPassRefPtr - if param_raw_type.is_heavy_value(): - formal_param_type_pattern = "const %s&" - else: - formal_param_type_pattern = "%s" - - method_in_params_handling.append(code) - agent_call_param_list.append(param) - Generator.backend_handler_interface_list.append(", %s in_%s" % (formal_param_type_pattern % non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name)) - - js_bind_type = param_raw_type.get_js_bind_type() - js_param_text = "{\"name\": \"%s\", \"type\": \"%s\", \"optional\": %s}" % ( - json_param_name, - js_bind_type, - ("true" if ("optional" in json_parameter and json_parameter["optional"]) else "false")) - - js_param_list.append(js_param_text) - - method_in_params_handling.append(" if (protocolErrors->length()) {\n") - method_in_params_handling.append(" String errorMessage = String::format(\"Some arguments of method '%%s' can't be processed\", \"%s.%s\");\n" % (domain_name, json_command_name)) - method_in_params_handling.append(" m_backendDispatcher->reportProtocolError(&callId, InspectorBackendDispatcher::InvalidParams, errorMessage, protocolErrors.release());\n") - method_in_params_handling.append(" return;\n") - method_in_params_handling.append(" }\n") - method_in_params_handling.append("\n") - - js_parameters_text = ", ".join(js_param_list) - - method_dispatch_handling.append(" ErrorString error;\n") - method_dispatch_handling.append(" RefPtr<InspectorObject> result = InspectorObject::create();\n") - - if json_command.get("async") == True: - callback_name = Capitalizer.lower_camel_case_to_upper(json_command_name) + "Callback" - - callback_output = [] - callback_writer = Writer(callback_output, ad_hoc_type_writer.get_indent()) - - decl_parameter_list = [] - Generator.generate_send_method(json_command.get("returns"), json_command_name, domain_name, ad_hoc_type_writer, - decl_parameter_list, - Generator.CallbackMethodStructTemplate, - Generator.backend_method_implementation_list, Templates.callback_method, - {"callbackName": callback_name, "handlerName": agent_interface_name}) - - callback_writer.newline("class " + callback_name + " : public Inspector::InspectorBackendDispatcher::CallbackBase {\n") - callback_writer.newline("public:\n") - callback_writer.newline(" " + callback_name + "(PassRefPtr<Inspector::InspectorBackendDispatcher>, int id);\n") - callback_writer.newline(" void sendSuccess(" + ", ".join(decl_parameter_list) + ");\n") - callback_writer.newline("};\n") - - ad_hoc_type_output.append(callback_output) - - method_dispatch_handling.append(" RefPtr<%s::%s> callback = adoptRef(new %s::%s(m_backendDispatcher,callId));\n" % (agent_interface_name, callback_name, agent_interface_name, callback_name)) - method_ending_handling.append(" if (error.length()) {\n") - method_ending_handling.append(" callback->disable();\n") - method_ending_handling.append(" m_backendDispatcher->reportProtocolError(&callId, Inspector::InspectorBackendDispatcher::ServerError, error);\n") - method_ending_handling.append(" return;\n") - method_ending_handling.append(" }") - - agent_call_param_list.append(", callback") - Generator.backend_handler_interface_list.append(", PassRefPtr<%s> callback" % callback_name) - elif "returns" in json_command: - has_multiple_returns = len(json_command["returns"]) > 1 - if has_multiple_returns: - method_out_params_handling.append(" if (!error.length()) {\n") - else: - method_out_params_handling.append(" if (!error.length())\n") - - for json_return in json_command["returns"]: - - json_return_name = json_return["name"] - - optional = bool(json_return.get("optional")) - - return_type_binding = Generator.resolve_type_and_generate_ad_hoc(json_return, json_command_name, domain_name, ad_hoc_type_writer, agent_interface_name + "::") - - raw_type = return_type_binding.reduce_to_raw_type() - setter_type = raw_type.get_setter_name() - initializer = raw_type.get_c_initializer() - - type_model = return_type_binding.get_type_model() - if optional: - type_model = type_model.get_optional() - - code = " %s out_%s;\n" % (type_model.get_command_return_pass_model().get_return_var_type(), json_return_name) - param = ", %sout_%s" % (type_model.get_command_return_pass_model().get_output_argument_prefix(), json_return_name) - var_name = "out_%s" % json_return_name - setter_argument = type_model.get_command_return_pass_model().get_output_to_raw_expression() % var_name - if return_type_binding.get_setter_value_expression_pattern(): - setter_argument = return_type_binding.get_setter_value_expression_pattern() % (INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["prefix"], setter_argument) - - cook = " result->set%s(ASCIILiteral(\"%s\"), %s);\n" % (setter_type, json_return_name, setter_argument) - - set_condition_pattern = type_model.get_command_return_pass_model().get_set_return_condition() - if set_condition_pattern: - cook = (" if (%s)\n " % (set_condition_pattern % var_name)) + cook - annotated_type = type_model.get_command_return_pass_model().get_output_parameter_type() - - param_name = "out_%s" % json_return_name - if optional: - param_name = "opt_" + param_name - - Generator.backend_handler_interface_list.append(", %s %s" % (annotated_type, param_name)) - method_out_params_handling.append(cook) - method_dispatch_handling.append(code) - - agent_call_param_list.append(param) - - if has_multiple_returns: - method_out_params_handling.append(" }\n") - method_out_params_handling.append("\n") - - method_dispatch_handling.append(" m_agent->%s(&error%s);\n" % (json_command_name, "".join(agent_call_param_list))) - method_dispatch_handling.append("\n") - - if not method_ending_handling: - method_ending_handling.append(" m_backendDispatcher->sendResponse(callId, result.release(), error);") - - backend_js_reply_param_list = [] - if "returns" in json_command: - for json_return in json_command["returns"]: - json_return_name = json_return["name"] - backend_js_reply_param_list.append("\"%s\"" % json_return_name) - - js_reply_list = "[%s]" % ", ".join(backend_js_reply_param_list) - - Generator.backend_method_implementation_list.append(Templates.backend_method.substitute(None, - dispatcherName=dispatcher_name, - methodName=json_command_name, - requestMessageObject=method_request_message_param_name, - methodInParametersHandling="".join(method_in_params_handling), - methodDispatchHandling="".join(method_dispatch_handling), - methodOutParametersHandling="".join(method_out_params_handling), - methodEndingHandling="".join(method_ending_handling))) - - Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerCommand(\"%s.%s\", [%s], %s);\n" % (domain_name, json_command_name, js_parameters_text, js_reply_list)) - Generator.backend_handler_interface_list.append(") = 0;\n") - - class CallbackMethodStructTemplate: - @staticmethod - def append_prolog(line_list): - pass - - @staticmethod - def append_epilog(line_list): - pass - - container_name = "jsonMessage" - - # Generates common code for event sending and callback response data sending. - @staticmethod - def generate_send_method(parameters, event_name, domain_name, ad_hoc_type_writer, decl_parameter_list, - method_struct_template, - generator_method_list, method_template, template_params): - method_line_list = [] - if parameters: - method_struct_template.append_prolog(method_line_list) - for json_parameter in parameters: - parameter_name = json_parameter["name"] - - param_type_binding = Generator.resolve_type_and_generate_ad_hoc(json_parameter, event_name, domain_name, ad_hoc_type_writer, "") - - raw_type = param_type_binding.reduce_to_raw_type() - raw_type_binding = RawTypeBinding(raw_type) - - optional = bool(json_parameter.get("optional")) - - setter_type = raw_type.get_setter_name() - - type_model = param_type_binding.get_type_model() - raw_type_model = raw_type_binding.get_type_model() - if optional: - type_model = type_model.get_optional() - raw_type_model = raw_type_model.get_optional() - - annotated_type = type_model.get_input_param_type_text() - mode_type_binding = param_type_binding - - decl_parameter_list.append("%s %s" % (annotated_type, parameter_name)) - - setter_argument = raw_type_model.get_event_setter_expression_pattern() % parameter_name - if mode_type_binding.get_setter_value_expression_pattern(): - setter_argument = mode_type_binding.get_setter_value_expression_pattern() % (INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["prefix"], setter_argument) - - setter_code = " %s->set%s(ASCIILiteral(\"%s\"), %s);\n" % (method_struct_template.container_name, setter_type, parameter_name, setter_argument) - if optional: - setter_code = (" if (%s)\n " % parameter_name) + setter_code - method_line_list.append(setter_code) - - method_struct_template.append_epilog(method_line_list) - - generator_method_list.append(method_template.substitute(None, - domainName=domain_name, - parameters=", ".join(decl_parameter_list), - code="".join(method_line_list), **template_params)) - - @staticmethod - def resolve_type_and_generate_ad_hoc(json_param, method_name, domain_name, ad_hoc_type_writer, container_relative_name_prefix_param): - param_name = json_param["name"] - ad_hoc_type_list = [] - - class AdHocTypeContext: - container_full_name_prefix = "<not yet defined>" - container_relative_name_prefix = container_relative_name_prefix_param - - @staticmethod - def get_type_name_fix(): - class NameFix: - class_name = Capitalizer.lower_camel_case_to_upper(param_name) - - @staticmethod - def output_comment(writer): - writer.newline("// Named after parameter '%s' while generating command/event %s.\n" % (param_name, method_name)) - - return NameFix - - @staticmethod - def add_type(binding): - ad_hoc_type_list.append(binding) - - type_binding = resolve_param_type(json_param, domain_name, AdHocTypeContext) - - class InterfaceForwardListener: - @staticmethod - def add_type_data(type_data): - pass - - class InterfaceResolveContext: - forward_listener = InterfaceForwardListener - - for type in ad_hoc_type_list: - type.resolve_inner(InterfaceResolveContext) - - class InterfaceGenerateContext: - validator_writer = "not supported in InterfaceGenerateContext" - cpp_writer = validator_writer - - for type in ad_hoc_type_list: - generator = type.get_code_generator() - if generator: - generator.generate_type_builder(ad_hoc_type_writer, InterfaceGenerateContext) - - return type_binding - - @staticmethod - def process_types(type_map): - output = Generator.type_builder_fragments - - class GenerateContext: - validator_writer = Writer(Generator.validator_impl_list, "") - cpp_writer = Writer(Generator.type_builder_impl_list, "") - - def generate_all_domains_code(out, type_data_callback): - writer = Writer(out, "") - for domain_data in type_map.domains_to_generate(): - domain_fixes = DomainNameFixes.get_fixed_data(domain_data.name()) - domain_guard = domain_fixes.get_guard() - - namespace_declared = [] - - def namespace_lazy_generator(): - if not namespace_declared: - if domain_guard: - domain_guard.generate_open(out) - writer.newline("namespace ") - writer.append(domain_data.name()) - writer.append(" {\n") - # What is a better way to change value from outer scope? - namespace_declared.append(True) - return writer - - for type_data in domain_data.types(): - type_data_callback(type_data, namespace_lazy_generator) - - if namespace_declared: - writer.append("} // ") - writer.append(domain_data.name()) - writer.append("\n\n") - - if domain_guard: - domain_guard.generate_close(out) - - def create_type_builder_caller(generate_pass_id): - def call_type_builder(type_data, writer_getter): - code_generator = type_data.get_binding().get_code_generator() - if code_generator and generate_pass_id == code_generator.get_generate_pass_id(): - writer = writer_getter() - - code_generator.generate_type_builder(writer, GenerateContext) - return call_type_builder - - generate_all_domains_code(output, create_type_builder_caller(TypeBuilderPass.MAIN)) - - Generator.type_builder_forwards.append("// Forward declarations.\n") - - def generate_forward_callback(type_data, writer_getter): - if type_data in global_forward_listener.type_data_set: - binding = type_data.get_binding() - binding.get_code_generator().generate_forward_declaration(writer_getter()) - generate_all_domains_code(Generator.type_builder_forwards, generate_forward_callback) - - Generator.type_builder_forwards.append("// End of forward declarations.\n\n") - - Generator.type_builder_forwards.append("// Typedefs.\n") - - generate_all_domains_code(Generator.type_builder_forwards, create_type_builder_caller(TypeBuilderPass.TYPEDEF)) - - Generator.type_builder_forwards.append("// End of typedefs.\n\n") - - -def flatten_list(input): - res = [] - - def fill_recursive(l): - for item in l: - if isinstance(item, list): - fill_recursive(item) - else: - res.append(item) - fill_recursive(input) - return res - - -# A writer that only updates file if it actually changed to better support incremental build. -class SmartOutput: - def __init__(self, file_name): - self.file_name_ = file_name - self.output_ = "" - - def write(self, text): - self.output_ += text - - def close(self): - text_changed = True - self.output_ = self.output_.rstrip() + "\n" - - try: - read_file = open(self.file_name_, "r") - old_text = read_file.read() - read_file.close() - text_changed = old_text != self.output_ - except: - # Ignore, just overwrite by default - pass - - if text_changed or write_always: - out_file = open(self.file_name_, "w") - out_file.write(self.output_) - out_file.close() - - -Generator.go() - -output_file_name_prefix = INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["prefix"] - -backend_h_file = SmartOutput(output_header_dirname + ("/Inspector%sBackendDispatchers.h" % output_file_name_prefix)) -backend_cpp_file = SmartOutput(output_cpp_dirname + ("/Inspector%sBackendDispatchers.cpp" % output_file_name_prefix)) - -frontend_h_file = SmartOutput(output_header_dirname + ("/Inspector%sFrontendDispatchers.h" % output_file_name_prefix)) -frontend_cpp_file = SmartOutput(output_cpp_dirname + ("/Inspector%sFrontendDispatchers.cpp" % output_file_name_prefix)) - -typebuilder_h_file = SmartOutput(output_header_dirname + ("/Inspector%sTypeBuilders.h" % output_file_name_prefix)) -typebuilder_cpp_file = SmartOutput(output_cpp_dirname + ("/Inspector%sTypeBuilders.cpp" % output_file_name_prefix)) - -backend_js_file = SmartOutput(output_js_dirname + ("/Inspector%sBackendCommands.js" % output_file_name_prefix)) - - -backend_h_file.write(Templates.backend_h.substitute(None, - outputFileNamePrefix=output_file_name_prefix, - handlerInterfaces="".join(flatten_list(Generator.backend_handler_interface_list)), - dispatcherInterfaces="".join(flatten_list(Generator.backend_dispatcher_interface_list)))) - -backend_cpp_file.write(Templates.backend_cpp.substitute(None, - outputFileNamePrefix=output_file_name_prefix, - handlerImplementations="".join(flatten_list(Generator.backend_handler_implementation_list)), - methods="\n".join(Generator.backend_method_implementation_list))) - -frontend_h_file.write(Templates.frontend_h.substitute(None, - outputFileNamePrefix=output_file_name_prefix, - domainClassList="".join(Generator.frontend_domain_class_lines))) - -frontend_cpp_file.write(Templates.frontend_cpp.substitute(None, - outputFileNamePrefix=output_file_name_prefix, - methods="\n".join(Generator.frontend_method_list))) - -typebuilder_h_file.write(Templates.typebuilder_h.substitute(None, - outputFileNamePrefix=output_file_name_prefix, - typeBuilderDependencies=INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["typebuilder_dependency"], - exportMacro=INSPECTOR_TYPES_GENERATOR_CONFIG_MAP[output_type]["export_macro"], - typeBuilders="".join(flatten_list(Generator.type_builder_fragments)), - forwards="".join(Generator.type_builder_forwards), - validatorIfdefName=VALIDATOR_IFDEF_NAME)) - -typebuilder_cpp_file.write(Templates.typebuilder_cpp.substitute(None, - outputFileNamePrefix=output_file_name_prefix, - enumConstantValues=EnumConstants.get_enum_constant_code(), - implCode="".join(flatten_list(Generator.type_builder_impl_list)), - validatorCode="".join(flatten_list(Generator.validator_impl_list)), - validatorIfdefName=VALIDATOR_IFDEF_NAME)) - -backend_js_file.write(Templates.backend_js.substitute(None, - domainInitializers="".join(Generator.backend_js_domain_initializer_list))) - -backend_h_file.close() -backend_cpp_file.close() - -frontend_h_file.close() -frontend_cpp_file.close() - -typebuilder_h_file.close() -typebuilder_cpp_file.close() - -backend_js_file.close() diff --git a/Source/JavaScriptCore/inspector/scripts/CodeGeneratorInspectorStrings.py b/Source/JavaScriptCore/inspector/scripts/CodeGeneratorInspectorStrings.py deleted file mode 100644 index 8de2cb0fa..000000000 --- a/Source/JavaScriptCore/inspector/scripts/CodeGeneratorInspectorStrings.py +++ /dev/null @@ -1,342 +0,0 @@ -# Copyright (c) 2013 Google Inc. All rights reserved. -# Copyright (c) 2013 Apple Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# This file contains string resources for CodeGeneratorInspector. -# Its syntax is a Python syntax subset, suitable for manual parsing. - -frontend_domain_class = ( -"""class ${exportMacro} ${domainClassName} { -public: - ${domainClassName}(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { } -${frontendDomainMethodDeclarations}private: - InspectorFrontendChannel* m_inspectorFrontendChannel; -}; - -""") - -backend_dispatcher_constructor = ( -"""PassRefPtr<${dispatcherName}> ${dispatcherName}::create(InspectorBackendDispatcher* backendDispatcher, ${agentName}* agent) -{ - return adoptRef(new ${dispatcherName}(backendDispatcher, agent)); -} - -${dispatcherName}::${dispatcherName}(InspectorBackendDispatcher* backendDispatcher, ${agentName}* agent) - : InspectorSupplementalBackendDispatcher(backendDispatcher) - , m_agent(agent) -{ - m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("${domainName}"), this); -} -""") - -backend_dispatcher_dispatch_method_simple = ( -"""void ${dispatcherName}::dispatch(long callId, const String& method, PassRefPtr<InspectorObject> message) -{ - Ref<${dispatcherName}> protect(*this); - -${ifChain} - else - m_backendDispatcher->reportProtocolError(&callId, InspectorBackendDispatcher::MethodNotFound, String("'") + "${domainName}" + '.' + method + "' was not found"); -} -""") - -backend_dispatcher_dispatch_method = ( -"""void ${dispatcherName}::dispatch(long callId, const String& method, PassRefPtr<InspectorObject> message) -{ - Ref<${dispatcherName}> protect(*this); - - typedef void (${dispatcherName}::*CallHandler)(long callId, const Inspector::InspectorObject& message); - typedef HashMap<String, CallHandler> DispatchMap; - DEFINE_STATIC_LOCAL(DispatchMap, dispatchMap, ()); - if (dispatchMap.isEmpty()) { - static const struct MethodTable { - const char* name; - CallHandler handler; - } commands[] = { -${dispatcherCommands} - }; - size_t length = WTF_ARRAY_LENGTH(commands); - for (size_t i = 0; i < length; ++i) - dispatchMap.add(commands[i].name, commands[i].handler); - } - - HashMap<String, CallHandler>::iterator it = dispatchMap.find(method); - if (it == dispatchMap.end()) { - m_backendDispatcher->reportProtocolError(&callId, InspectorBackendDispatcher::MethodNotFound, String("'") + "${domainName}" + '.' + method + "' was not found"); - return; - } - - ((*this).*it->value)(callId, *message.get()); -} -""") - -backend_method = ( -"""void ${dispatcherName}::${methodName}(long callId, const InspectorObject&${requestMessageObject}) -{ -${methodInParametersHandling}${methodDispatchHandling}${methodOutParametersHandling}${methodEndingHandling} -} -""") - -frontend_method = ("""void Inspector${domainName}FrontendDispatcher::${eventName}(${parameters}) -{ - RefPtr<InspectorObject> jsonMessage = InspectorObject::create(); - jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("${domainName}.${eventName}")); -${code} - m_inspectorFrontendChannel->sendMessageToFrontend(jsonMessage->toJSONString()); -} -""") - -callback_method = ( -"""${handlerName}::${callbackName}::${callbackName}(PassRefPtr<InspectorBackendDispatcher> backendDispatcher, int id) : Inspector::InspectorBackendDispatcher::CallbackBase(backendDispatcher, id) { } - -void ${handlerName}::${callbackName}::sendSuccess(${parameters}) -{ - RefPtr<InspectorObject> jsonMessage = InspectorObject::create(); -${code} sendIfActive(jsonMessage, ErrorString()); -} -""") - -frontend_h = ( -"""#ifndef Inspector${outputFileNamePrefix}FrontendDispatchers_h -#define Inspector${outputFileNamePrefix}FrontendDispatchers_h - -#include "Inspector${outputFileNamePrefix}TypeBuilders.h" -#include <inspector/InspectorFrontendChannel.h> -#include <inspector/InspectorValues.h> -#include <wtf/PassRefPtr.h> -#include <wtf/text/WTFString.h> - -namespace Inspector { - -#if ENABLE(INSPECTOR) - -${domainClassList} - -#endif // ENABLE(INSPECTOR) - -} // namespace Inspector - -#endif // !defined(Inspector${outputFileNamePrefix}FrontendDispatchers_h) -""") - -backend_h = ( -"""#ifndef Inspector${outputFileNamePrefix}BackendDispatchers_h -#define Inspector${outputFileNamePrefix}BackendDispatchers_h - -#include "Inspector${outputFileNamePrefix}TypeBuilders.h" -#include <inspector/InspectorBackendDispatcher.h> -#include <wtf/PassRefPtr.h> -#include <wtf/text/WTFString.h> - -namespace Inspector { - -typedef String ErrorString; - -${handlerInterfaces} - -${dispatcherInterfaces} -} // namespace Inspector - -#endif // !defined(Inspector${outputFileNamePrefix}BackendDispatchers_h) -""") - -backend_cpp = ( -""" -#include "config.h" -#include "Inspector${outputFileNamePrefix}BackendDispatchers.h" - -#if ENABLE(INSPECTOR) - -#include <inspector/InspectorFrontendChannel.h> -#include <inspector/InspectorValues.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -namespace Inspector { - -${handlerImplementations} - -${methods} -} // namespace Inspector - -#endif // ENABLE(INSPECTOR) -""") - -frontend_cpp = ( -""" - -#include "config.h" -#include "Inspector${outputFileNamePrefix}FrontendDispatchers.h" - -#if ENABLE(INSPECTOR) - -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -namespace Inspector { - -${methods} - -} // namespace Inspector - -#endif // ENABLE(INSPECTOR) -""") - -typebuilder_h = ( -""" -#ifndef Inspector${outputFileNamePrefix}TypeBuilders_h -#define Inspector${outputFileNamePrefix}TypeBuilders_h - -#if ENABLE(INSPECTOR) - -#include <inspector/InspectorTypeBuilder.h> -${typeBuilderDependencies} -#include <wtf/Assertions.h> -#include <wtf/PassRefPtr.h> - -namespace Inspector { - -namespace TypeBuilder { - -${forwards} - -${exportMacro} String get${outputFileNamePrefix}EnumConstantValue(int code); - -${typeBuilders} -} // namespace TypeBuilder - -} // namespace Inspector - -#endif // ENABLE(INSPECTOR) - -#endif // !defined(Inspector${outputFileNamePrefix}TypeBuilders_h) - -""") - -typebuilder_cpp = ( -""" - -#include "config.h" -#include "Inspector${outputFileNamePrefix}TypeBuilders.h" - -#if ENABLE(INSPECTOR) - -#include <wtf/text/CString.h> - -namespace Inspector { - -namespace TypeBuilder { - -static const char* const enum_constant_values[] = { -${enumConstantValues}}; - -String get${outputFileNamePrefix}EnumConstantValue(int code) { - return enum_constant_values[code]; -} - -} // namespace TypeBuilder - -${implCode} - -#if ${validatorIfdefName} - -${validatorCode} - -#endif // ${validatorIfdefName} - -} // namespace Inspector - -#endif // ENABLE(INSPECTOR) -""") - -backend_js = ( -""" - -${domainInitializers} -""") - -param_container_access_code = """ - RefPtr<InspectorObject> paramsContainer = message.getObject("params"); - InspectorObject* paramsContainerPtr = paramsContainer.get(); - InspectorArray* protocolErrorsPtr = protocolErrors.get(); -""" - -class_binding_builder_part_1 = ( -""" AllFieldsSet = %s - }; - - template<int STATE> - class Builder { - private: - RefPtr<Inspector::InspectorObject> m_result; - - template<int STEP> Builder<STATE | STEP>& castState() - { - return *reinterpret_cast<Builder<STATE | STEP>*>(this); - } - - Builder(PassRefPtr</*%s*/Inspector::InspectorObject> ptr) - { - COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); - m_result = ptr; - } - friend class %s; - public: -""") - -class_binding_builder_part_2 = (""" - Builder<STATE | %s>& set%s(%s value) - { - COMPILE_ASSERT(!(STATE & %s), property_%s_already_set); - m_result->set%s(ASCIILiteral("%s"), %s); - return castState<%s>(); - } -""") - -class_binding_builder_part_3 = (""" - operator RefPtr<%s>& () - { - COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); - COMPILE_ASSERT(sizeof(%s) == sizeof(Inspector::InspectorObject), cannot_cast); - return *reinterpret_cast<RefPtr<%s>*>(&m_result); - } - - PassRefPtr<%s> release() - { - return RefPtr<%s>(*this).release(); - } - }; - -""") - -class_binding_builder_part_4 = ( -""" static Builder<NoFieldsSet> create() - { - return Builder<NoFieldsSet>(Inspector::InspectorObject::create()); - } -""") diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/__init__.py b/Source/JavaScriptCore/inspector/scripts/codegen/__init__.py new file mode 100644 index 000000000..37dbe9436 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/__init__.py @@ -0,0 +1,25 @@ +# Required for Python to search this directory for module files + +from models import * +from generator import * +from cpp_generator import * +from objc_generator import * + +from generate_cpp_alternate_backend_dispatcher_header import * +from generate_cpp_backend_dispatcher_header import * +from generate_cpp_backend_dispatcher_implementation import * +from generate_cpp_frontend_dispatcher_header import * +from generate_cpp_frontend_dispatcher_implementation import * +from generate_cpp_protocol_types_header import * +from generate_cpp_protocol_types_implementation import * +from generate_js_backend_commands import * +from generate_objc_backend_dispatcher_header import * +from generate_objc_backend_dispatcher_implementation import * +from generate_objc_configuration_header import * +from generate_objc_configuration_implementation import * +from generate_objc_frontend_dispatcher_implementation import * +from generate_objc_header import * +from generate_objc_internal_header import * +from generate_objc_protocol_types_implementation import * +from generate_objc_protocol_type_conversions_header import * +from generate_objc_protocol_type_conversions_implementation import * diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/cpp_generator.py b/Source/JavaScriptCore/inspector/scripts/codegen/cpp_generator.py new file mode 100644 index 000000000..c459fcac3 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/cpp_generator.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +import logging +import os.path +import re + +from generator import ucfirst, Generator +from models import PrimitiveType, ObjectType, ArrayType, EnumType, AliasedType, Frameworks + +log = logging.getLogger('global') + +_PRIMITIVE_TO_CPP_NAME_MAP = { + 'boolean': 'bool', + 'integer': 'int', + 'number': 'double', + 'string': 'String', + 'object': 'Inspector::InspectorObject', + 'array': 'Inspector::InspectorArray', + 'any': 'Inspector::InspectorValue' +} + +class CppGenerator(Generator): + def __init__(self, *args, **kwargs): + Generator.__init__(self, *args, **kwargs) + + def protocol_name(self): + return self.model().framework.setting('cpp_protocol_group', '') + + def helpers_namespace(self): + return '%sHelpers' % self.protocol_name() + + # Miscellaneous text manipulation routines. + @staticmethod + def cpp_getter_method_for_type(_type): + if isinstance(_type, ObjectType): + return 'getObject' + if isinstance(_type, ArrayType): + return 'getArray' + if isinstance(_type, PrimitiveType): + if _type.raw_name() is 'integer': + return 'getInteger' + elif _type.raw_name() is 'number': + return 'getDouble' + elif _type.raw_name() is 'any': + return 'getValue' + else: + return 'get' + ucfirst(_type.raw_name()) + if isinstance(_type, AliasedType): + return CppGenerator.cpp_getter_method_for_type(_type.aliased_type) + if isinstance(_type, EnumType): + return CppGenerator.cpp_getter_method_for_type(_type.primitive_type) + + @staticmethod + def cpp_setter_method_for_type(_type): + if isinstance(_type, ObjectType): + return 'setObject' + if isinstance(_type, ArrayType): + return 'setArray' + if isinstance(_type, PrimitiveType): + if _type.raw_name() is 'integer': + return 'setInteger' + elif _type.raw_name() is 'number': + return 'setDouble' + elif _type.raw_name() is 'any': + return 'setValue' + else: + return 'set' + ucfirst(_type.raw_name()) + if isinstance(_type, AliasedType): + return CppGenerator.cpp_setter_method_for_type(_type.aliased_type) + if isinstance(_type, EnumType): + return CppGenerator.cpp_setter_method_for_type(_type.primitive_type) + + # Generate type representations for various situations. + @staticmethod + def cpp_protocol_type_for_type(_type): + if isinstance(_type, ObjectType) and len(_type.members) == 0: + return 'Inspector::InspectorObject' + if isinstance(_type, ArrayType): + if _type.raw_name() is None: # Otherwise, fall through and use typedef'd name. + return 'Inspector::Protocol::Array<%s>' % CppGenerator.cpp_protocol_type_for_type(_type.element_type) + if isinstance(_type, (ObjectType, AliasedType, EnumType, ArrayType)): + return 'Inspector::Protocol::%s::%s' % (_type.type_domain().domain_name, _type.raw_name()) + if isinstance(_type, PrimitiveType): + return CppGenerator.cpp_name_for_primitive_type(_type) + + @staticmethod + def cpp_protocol_type_for_type_member(type_member, object_declaration): + if isinstance(type_member.type, EnumType) and type_member.type.is_anonymous: + return '::'.join([CppGenerator.cpp_protocol_type_for_type(object_declaration.type), ucfirst(type_member.member_name)]) + else: + return CppGenerator.cpp_protocol_type_for_type(type_member.type) + + @staticmethod + def cpp_type_for_unchecked_formal_in_parameter(parameter): + _type = parameter.type + if isinstance(_type, AliasedType): + _type = _type.aliased_type # Fall through to enum or primitive. + + if isinstance(_type, EnumType): + _type = _type.primitive_type # Fall through to primitive. + + # This handles the 'any' type and objects with defined properties. + if isinstance(_type, ObjectType) or _type.qualified_name() is 'object': + cpp_name = 'Inspector::InspectorObject' + if parameter.is_optional: + return 'const %s*' % cpp_name + else: + return 'const %s&' % cpp_name + if isinstance(_type, ArrayType): + cpp_name = 'Inspector::InspectorArray' + if parameter.is_optional: + return 'const %s*' % cpp_name + else: + return 'const %s&' % cpp_name + if isinstance(_type, PrimitiveType): + cpp_name = CppGenerator.cpp_name_for_primitive_type(_type) + if parameter.is_optional: + return 'const %s* const' % cpp_name + elif _type.raw_name() in ['string']: + return 'const %s&' % cpp_name + else: + return cpp_name + + return "unknown_unchecked_formal_in_parameter_type" + + @staticmethod + def cpp_type_for_checked_formal_event_parameter(parameter): + return CppGenerator.cpp_type_for_type_with_name(parameter.type, parameter.parameter_name, parameter.is_optional) + + @staticmethod + def cpp_type_for_type_member(member): + return CppGenerator.cpp_type_for_type_with_name(member.type, member.member_name, False) + + @staticmethod + def cpp_type_for_type_with_name(_type, type_name, is_optional): + if isinstance(_type, (ArrayType, ObjectType)): + return 'RefPtr<%s>' % CppGenerator.cpp_protocol_type_for_type(_type) + if isinstance(_type, AliasedType): + builder_type = CppGenerator.cpp_protocol_type_for_type(_type) + if is_optional: + return 'const %s* const' % builder_type + elif _type.aliased_type.qualified_name() in ['integer', 'number']: + return CppGenerator.cpp_name_for_primitive_type(_type.aliased_type) + elif _type.aliased_type.qualified_name() in ['string']: + return 'const %s&' % builder_type + else: + return builder_type + if isinstance(_type, PrimitiveType): + cpp_name = CppGenerator.cpp_name_for_primitive_type(_type) + if _type.qualified_name() in ['object']: + return 'RefPtr<Inspector::InspectorObject>' + elif _type.qualified_name() in ['any']: + return 'RefPtr<Inspector::InspectorValue>' + elif is_optional: + return 'const %s* const' % cpp_name + elif _type.qualified_name() in ['string']: + return 'const %s&' % cpp_name + else: + return cpp_name + if isinstance(_type, EnumType): + if _type.is_anonymous: + enum_type_name = ucfirst(type_name) + else: + enum_type_name = 'Inspector::Protocol::%s::%s' % (_type.type_domain().domain_name, _type.raw_name()) + + if is_optional: + return '%s*' % enum_type_name + else: + return '%s' % enum_type_name + + @staticmethod + def cpp_type_for_formal_out_parameter(parameter): + _type = parameter.type + + if isinstance(_type, AliasedType): + _type = _type.aliased_type # Fall through. + + if isinstance(_type, (ObjectType, ArrayType)): + return 'RefPtr<%s>&' % CppGenerator.cpp_protocol_type_for_type(_type) + if isinstance(_type, PrimitiveType): + cpp_name = CppGenerator.cpp_name_for_primitive_type(_type) + if parameter.is_optional: + return "Inspector::Protocol::OptOutput<%s>*" % cpp_name + else: + return '%s*' % cpp_name + if isinstance(_type, EnumType): + if _type.is_anonymous: + return '%sBackendDispatcherHandler::%s*' % (_type.type_domain().domain_name, ucfirst(parameter.parameter_name)) + else: + return 'Inspector::Protocol::%s::%s*' % (_type.type_domain().domain_name, _type.raw_name()) + + raise ValueError("unknown formal out parameter type.") + + # FIXME: this is only slightly different from out parameters; they could be unified. + @staticmethod + def cpp_type_for_formal_async_parameter(parameter): + _type = parameter.type + if isinstance(_type, AliasedType): + _type = _type.aliased_type # Fall through. + + if isinstance(_type, EnumType): + _type = _type.primitive_type # Fall through. + + if isinstance(_type, (ObjectType, ArrayType)): + return 'RefPtr<%s>&&' % CppGenerator.cpp_protocol_type_for_type(_type) + if isinstance(_type, PrimitiveType): + cpp_name = CppGenerator.cpp_name_for_primitive_type(_type) + if parameter.is_optional: + return "Inspector::Protocol::OptOutput<%s>*" % cpp_name + elif _type.qualified_name() in ['integer', 'number']: + return CppGenerator.cpp_name_for_primitive_type(_type) + elif _type.qualified_name() in ['string']: + return 'const %s&' % cpp_name + else: + return cpp_name + + raise ValueError("Unknown formal async parameter type.") + + # In-parameters don't use builder types, because they could be passed + # "open types" that are manually constructed out of InspectorObjects. + + # FIXME: Only parameters that are actually open types should need non-builder parameter types. + @staticmethod + def cpp_type_for_stack_in_parameter(parameter): + _type = parameter.type + if isinstance(_type, AliasedType): + _type = _type.aliased_type # Fall through. + + if isinstance(_type, EnumType): + _type = _type.primitive_type # Fall through. + + if isinstance(_type, ObjectType): + return "RefPtr<Inspector::InspectorObject>" + if isinstance(_type, ArrayType): + return "RefPtr<Inspector::InspectorArray>" + if isinstance(_type, PrimitiveType): + cpp_name = CppGenerator.cpp_name_for_primitive_type(_type) + if _type.qualified_name() in ['any', 'object']: + return "RefPtr<%s>" % CppGenerator.cpp_name_for_primitive_type(_type) + elif parameter.is_optional and _type.qualified_name() not in ['boolean', 'string', 'integer']: + return "Inspector::Protocol::OptOutput<%s>" % cpp_name + else: + return cpp_name + + @staticmethod + def cpp_type_for_stack_out_parameter(parameter): + _type = parameter.type + if isinstance(_type, (ArrayType, ObjectType)): + return 'RefPtr<%s>' % CppGenerator.cpp_protocol_type_for_type(_type) + if isinstance(_type, AliasedType): + builder_type = CppGenerator.cpp_protocol_type_for_type(_type) + if parameter.is_optional: + return "Inspector::Protocol::OptOutput<%s>" % builder_type + return '%s' % builder_type + if isinstance(_type, PrimitiveType): + cpp_name = CppGenerator.cpp_name_for_primitive_type(_type) + if parameter.is_optional: + return "Inspector::Protocol::OptOutput<%s>" % cpp_name + else: + return cpp_name + if isinstance(_type, EnumType): + if _type.is_anonymous: + return '%sBackendDispatcherHandler::%s' % (_type.type_domain().domain_name, ucfirst(parameter.parameter_name)) + else: + return 'Inspector::Protocol::%s::%s' % (_type.type_domain().domain_name, _type.raw_name()) + + @staticmethod + def cpp_assertion_method_for_type_member(type_member, object_declaration): + + def assertion_method_for_type(_type): + return 'BindingTraits<%s>::assertValueHasExpectedType' % CppGenerator.cpp_protocol_type_for_type(_type) + + if isinstance(type_member.type, AliasedType): + return assertion_method_for_type(type_member.type.aliased_type) + if isinstance(type_member.type, EnumType) and type_member.type.is_anonymous: + return 'BindingTraits<%s>::assertValueHasExpectedType' % CppGenerator.cpp_protocol_type_for_type_member(type_member, object_declaration) + + return assertion_method_for_type(type_member.type) + + @staticmethod + def cpp_name_for_primitive_type(_type): + return _PRIMITIVE_TO_CPP_NAME_MAP.get(_type.raw_name()) + + # Decide whether certain helpers are necessary in a situation. + @staticmethod + def should_use_wrapper_for_return_type(_type): + return not isinstance(_type, (ArrayType, ObjectType)) + + @staticmethod + def should_use_references_for_type(_type): + return isinstance(_type, (ArrayType, ObjectType)) or (isinstance(_type, (PrimitiveType)) and _type.qualified_name() in ["any", "object"]) + + @staticmethod + def should_pass_by_copy_for_return_type(_type): + return isinstance(_type, (ArrayType, ObjectType)) or (isinstance(_type, (PrimitiveType)) and _type.qualified_name() == "object") diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/cpp_generator_templates.py b/Source/JavaScriptCore/inspector/scripts/codegen/cpp_generator_templates.py new file mode 100755 index 000000000..b2523ffe2 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/cpp_generator_templates.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2015 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +# Generator templates, which can be filled with string.Template. +# Following are classes that fill the templates from the typechecked model. + +class CppGeneratorTemplates: + + HeaderPrelude = ( + """#pragma once + +${includes} + +namespace Inspector { + +${typedefs}""") + + HeaderPostlude = ( + """} // namespace Inspector""") + + ImplementationPrelude = ( + """#include "config.h" +#include ${primaryInclude} + +${secondaryIncludes} + +namespace Inspector {""") + + ImplementationPostlude = ( + """} // namespace Inspector +""") + + AlternateDispatchersHeaderPrelude = ( + """#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +${includes} + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; +""") + + AlternateDispatchersHeaderPostlude = ( + """} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS)""") + + AlternateBackendDispatcherHeaderDomainHandlerInterfaceDeclaration = ( + """class Alternate${domainName}BackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~Alternate${domainName}BackendDispatcher() { } +${commandDeclarations} +};""") + + BackendDispatcherHeaderDomainHandlerDeclaration = ( + """${classAndExportMacro} ${domainName}BackendDispatcherHandler { +public: +${commandDeclarations} +protected: + virtual ~${domainName}BackendDispatcherHandler(); +};""") + + BackendDispatcherHeaderDomainDispatcherDeclaration = ( + """${classAndExportMacro} ${domainName}BackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<${domainName}BackendDispatcher> create(BackendDispatcher&, ${domainName}BackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +${commandDeclarations} +private: + ${domainName}BackendDispatcher(BackendDispatcher&, ${domainName}BackendDispatcherHandler*); + ${domainName}BackendDispatcherHandler* m_agent { nullptr }; +};""") + + BackendDispatcherHeaderDomainDispatcherAlternatesDeclaration = ( + """#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(Alternate${domainName}BackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + Alternate${domainName}BackendDispatcher* m_alternateDispatcher { nullptr }; +#endif""") + + BackendDispatcherHeaderAsyncCommandDeclaration = ( + """ ${classAndExportMacro} ${callbackName} : public BackendDispatcher::CallbackBase { + public: + ${callbackName}(Ref<BackendDispatcher>&&, int id); + void sendSuccess(${outParameters}); + }; + virtual void ${commandName}(${inParameters}) = 0;""") + + BackendDispatcherImplementationSmallSwitch = ( + """void ${domainName}BackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<${domainName}BackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + +${dispatchCases} + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\\'', "${domainName}", '.', method, "' was not found")); +}""") + + BackendDispatcherImplementationLargeSwitch = ( +"""void ${domainName}BackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<${domainName}BackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + typedef void (${domainName}BackendDispatcher::*CallHandler)(long requestId, RefPtr<InspectorObject>&& message); + typedef HashMap<String, CallHandler> DispatchMap; + static NeverDestroyed<DispatchMap> dispatchMap; + if (dispatchMap.get().isEmpty()) { + static const struct MethodTable { + const char* name; + CallHandler handler; + } commands[] = { +${dispatchCases} + }; + size_t length = WTF_ARRAY_LENGTH(commands); + for (size_t i = 0; i < length; ++i) + dispatchMap.get().add(commands[i].name, commands[i].handler); + } + + auto findResult = dispatchMap.get().find(method); + if (findResult == dispatchMap.get().end()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\\'', "${domainName}", '.', method, "' was not found")); + return; + } + + ((*this).*findResult->value)(requestId, WTFMove(parameters)); +}""") + + BackendDispatcherImplementationDomainConstructor = ( + """Ref<${domainName}BackendDispatcher> ${domainName}BackendDispatcher::create(BackendDispatcher& backendDispatcher, ${domainName}BackendDispatcherHandler* agent) +{ + return adoptRef(*new ${domainName}BackendDispatcher(backendDispatcher, agent)); +} + +${domainName}BackendDispatcher::${domainName}BackendDispatcher(BackendDispatcher& backendDispatcher, ${domainName}BackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("${domainName}"), this); +}""") + + BackendDispatcherImplementationPrepareCommandArguments = ( +"""${inParameterDeclarations} + if (m_backendDispatcher->hasProtocolErrors()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Some arguments of method \'%s\' can't be processed", "${domainName}.${commandName}")); + return; + } +""") + + BackendDispatcherImplementationAsyncCommand = ( +"""${domainName}BackendDispatcherHandler::${callbackName}::${callbackName}(Ref<BackendDispatcher>&& backendDispatcher, int id) : BackendDispatcher::CallbackBase(WTFMove(backendDispatcher), id) { } + +void ${domainName}BackendDispatcherHandler::${callbackName}::sendSuccess(${formalParameters}) +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); +${outParameterAssignments} + CallbackBase::sendSuccess(WTFMove(jsonMessage)); +}""") + + FrontendDispatcherDomainDispatcherDeclaration = ( +"""${classAndExportMacro} ${domainName}FrontendDispatcher { +public: + ${domainName}FrontendDispatcher(FrontendRouter& frontendRouter) : m_frontendRouter(frontendRouter) { } +${eventDeclarations} +private: + FrontendRouter& m_frontendRouter; +};""") + + ProtocolObjectBuilderDeclarationPrelude = ( +""" template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*${objectType}*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class ${objectType}; + public:""") + + ProtocolObjectBuilderDeclarationPostlude = ( +""" + Ref<${objectType}> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(${objectType}) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<${objectType}>*>(&result)); + } + }; + + /* + * Synthetic constructor: +${constructorExample} + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + }""") + + ProtocolObjectRuntimeCast = ( +"""RefPtr<${objectType}> BindingTraits<${objectType}>::runtimeCast(RefPtr<InspectorValue>&& value) +{ + RefPtr<InspectorObject> result; + bool castSucceeded = value->asObject(result); + ASSERT_UNUSED(castSucceeded, castSucceeded); +#if !ASSERT_DISABLED + BindingTraits<${objectType}>::assertValueHasExpectedType(result.get()); +#endif // !ASSERT_DISABLED + COMPILE_ASSERT(sizeof(${objectType}) == sizeof(InspectorObjectBase), type_cast_problem); + return static_cast<${objectType}*>(static_cast<InspectorObjectBase*>(result.get())); +} +""") diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_alternate_backend_dispatcher_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_alternate_backend_dispatcher_header.py new file mode 100755 index 000000000..86e864974 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_alternate_backend_dispatcher_header.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +import re +from string import Template + +from cpp_generator import CppGenerator +from cpp_generator_templates import CppGeneratorTemplates as CppTemplates + +log = logging.getLogger('global') + + +class CppAlternateBackendDispatcherHeaderGenerator(CppGenerator): + def __init__(self, *args, **kwargs): + CppGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sAlternateBackendDispatchers.h' % self.protocol_name() + + def generate_output(self): + headers = [ + '"%sProtocolTypes.h"' % self.protocol_name(), + '<inspector/InspectorFrontendRouter.h>', + '<JavaScriptCore/InspectorBackendDispatcher.h>', + ] + + header_args = { + 'includes': '\n'.join(['#include ' + header for header in headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(CppTemplates.AlternateDispatchersHeaderPrelude).substitute(None, **header_args)) + sections.append('\n'.join(filter(None, map(self._generate_handler_declarations_for_domain, domains)))) + sections.append(Template(CppTemplates.AlternateDispatchersHeaderPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_handler_declarations_for_domain(self, domain): + commands = self.commands_for_domain(domain) + + if not len(commands): + return '' + + command_declarations = [] + for command in commands: + command_declarations.append(self._generate_handler_declaration_for_command(command)) + + handler_args = { + 'domainName': domain.domain_name, + 'commandDeclarations': '\n'.join(command_declarations), + } + + return self.wrap_with_guard_for_domain(domain, Template(CppTemplates.AlternateBackendDispatcherHeaderDomainHandlerInterfaceDeclaration).substitute(None, **handler_args)) + + def _generate_handler_declaration_for_command(self, command): + lines = [] + parameters = ['long callId'] + for _parameter in command.call_parameters: + parameters.append('%s in_%s' % (CppGenerator.cpp_type_for_unchecked_formal_in_parameter(_parameter), _parameter.parameter_name)) + + command_args = { + 'commandName': command.command_name, + 'parameters': ', '.join(parameters), + } + lines.append(' virtual void %(commandName)s(%(parameters)s) = 0;' % command_args) + return '\n'.join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_backend_dispatcher_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_backend_dispatcher_header.py new file mode 100755 index 000000000..992622bdd --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_backend_dispatcher_header.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014-2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import re +import string +from string import Template + +from cpp_generator import CppGenerator +from cpp_generator_templates import CppGeneratorTemplates as CppTemplates +from generator import Generator, ucfirst +from models import EnumType + +log = logging.getLogger('global') + + +class CppBackendDispatcherHeaderGenerator(CppGenerator): + def __init__(self, *args, **kwargs): + CppGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return "%sBackendDispatchers.h" % self.protocol_name() + + def domains_to_generate(self): + return filter(lambda domain: len(self.commands_for_domain(domain)) > 0, Generator.domains_to_generate(self)) + + def generate_output(self): + headers = [ + '"%sProtocolObjects.h"' % self.protocol_name(), + '<inspector/InspectorBackendDispatcher.h>', + '<wtf/text/WTFString.h>'] + + typedefs = [('String', 'ErrorString')] + + header_args = { + 'includes': '\n'.join(['#include ' + header for header in headers]), + 'typedefs': '\n'.join(['typedef %s %s;' % typedef for typedef in typedefs]), + } + + domains = self.domains_to_generate() + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(CppTemplates.HeaderPrelude).substitute(None, **header_args)) + if self.model().framework.setting('alternate_dispatchers', False): + sections.append(self._generate_alternate_handler_forward_declarations_for_domains(domains)) + sections.extend(map(self._generate_handler_declarations_for_domain, domains)) + sections.extend(map(self._generate_dispatcher_declarations_for_domain, domains)) + sections.append(Template(CppTemplates.HeaderPostlude).substitute(None, **header_args)) + return "\n\n".join(sections) + + # Private methods. + + def _generate_alternate_handler_forward_declarations_for_domains(self, domains): + if not domains: + return '' + + lines = [] + lines.append('#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS)') + for domain in domains: + lines.append(self.wrap_with_guard_for_domain(domain, 'class Alternate%sBackendDispatcher;' % domain.domain_name)) + lines.append('#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS)') + return '\n'.join(lines) + + def _generate_handler_declarations_for_domain(self, domain): + classComponents = ['class'] + exportMacro = self.model().framework.setting('export_macro', None) + if exportMacro is not None: + classComponents.append(exportMacro) + + used_enum_names = set() + + command_declarations = [] + for command in self.commands_for_domain(domain): + command_declarations.append(self._generate_handler_declaration_for_command(command, used_enum_names)) + + handler_args = { + 'classAndExportMacro': " ".join(classComponents), + 'domainName': domain.domain_name, + 'commandDeclarations': "\n".join(command_declarations) + } + + return self.wrap_with_guard_for_domain(domain, Template(CppTemplates.BackendDispatcherHeaderDomainHandlerDeclaration).substitute(None, **handler_args)) + + def _generate_anonymous_enum_for_parameter(self, parameter, command): + enum_args = { + 'parameterName': parameter.parameter_name, + 'commandName': command.command_name + } + + lines = [] + lines.append(' // Named after parameter \'%(parameterName)s\' while generating command/event %(commandName)s.' % enum_args) + lines.append(' enum class %s {' % ucfirst(parameter.parameter_name)) + for enum_value in parameter.type.enum_values(): + lines.append(' %s = %d,' % (Generator.stylized_name_for_enum_value(enum_value), self.encoding_for_enum_value(enum_value))) + lines.append(' }; // enum class %s' % ucfirst(parameter.parameter_name)) + return '\n'.join(lines) + + def _generate_handler_declaration_for_command(self, command, used_enum_names): + if command.is_async: + return self._generate_async_handler_declaration_for_command(command) + + lines = [] + parameters = ['ErrorString&'] + for _parameter in command.call_parameters: + parameter_name = 'in_' + _parameter.parameter_name + if _parameter.is_optional: + parameter_name = 'opt_' + parameter_name + + parameters.append("%s %s" % (CppGenerator.cpp_type_for_unchecked_formal_in_parameter(_parameter), parameter_name)) + + if isinstance(_parameter.type, EnumType) and _parameter.type.is_anonymous and _parameter.parameter_name not in used_enum_names: + lines.append(self._generate_anonymous_enum_for_parameter(_parameter, command)) + used_enum_names.add(_parameter.parameter_name) + + for _parameter in command.return_parameters: + parameter_name = 'out_' + _parameter.parameter_name + if _parameter.is_optional: + parameter_name = 'opt_' + parameter_name + parameters.append("%s %s" % (CppGenerator.cpp_type_for_formal_out_parameter(_parameter), parameter_name)) + + if isinstance(_parameter.type, EnumType) and _parameter.type.is_anonymous and _parameter.parameter_name not in used_enum_names: + lines.append(self._generate_anonymous_enum_for_parameter(_parameter, command)) + used_enum_names.add(_parameter.parameter_name) + + command_args = { + 'commandName': command.command_name, + 'parameters': ", ".join(parameters) + } + lines.append(' virtual void %(commandName)s(%(parameters)s) = 0;' % command_args) + return '\n'.join(lines) + + def _generate_async_handler_declaration_for_command(self, command): + callbackName = "%sCallback" % ucfirst(command.command_name) + + in_parameters = ['ErrorString&'] + for _parameter in command.call_parameters: + parameter_name = 'in_' + _parameter.parameter_name + if _parameter.is_optional: + parameter_name = 'opt_' + parameter_name + + in_parameters.append("%s %s" % (CppGenerator.cpp_type_for_unchecked_formal_in_parameter(_parameter), parameter_name)) + in_parameters.append("Ref<%s>&& callback" % callbackName) + + out_parameters = [] + for _parameter in command.return_parameters: + out_parameters.append("%s %s" % (CppGenerator.cpp_type_for_formal_async_parameter(_parameter), _parameter.parameter_name)) + + class_components = ['class'] + export_macro = self.model().framework.setting('export_macro', None) + if export_macro: + class_components.append(export_macro) + + command_args = { + 'classAndExportMacro': ' '.join(class_components), + 'callbackName': callbackName, + 'commandName': command.command_name, + 'inParameters': ", ".join(in_parameters), + 'outParameters': ", ".join(out_parameters), + } + + return Template(CppTemplates.BackendDispatcherHeaderAsyncCommandDeclaration).substitute(None, **command_args) + + def _generate_dispatcher_declarations_for_domain(self, domain): + classComponents = ['class'] + exportMacro = self.model().framework.setting('export_macro', None) + if exportMacro is not None: + classComponents.append(exportMacro) + + declarations = [] + commands = self.commands_for_domain(domain) + if len(commands) > 0: + declarations.append('private:') + declarations.extend(map(self._generate_dispatcher_declaration_for_command, commands)) + + declaration_args = { + 'domainName': domain.domain_name, + } + + # Add in a few more declarations at the end if needed. + if self.model().framework.setting('alternate_dispatchers', False): + declarations.append(Template(CppTemplates.BackendDispatcherHeaderDomainDispatcherAlternatesDeclaration).substitute(None, **declaration_args)) + + handler_args = { + 'classAndExportMacro': " ".join(classComponents), + 'domainName': domain.domain_name, + 'commandDeclarations': "\n".join(declarations) + } + + return self.wrap_with_guard_for_domain(domain, Template(CppTemplates.BackendDispatcherHeaderDomainDispatcherDeclaration).substitute(None, **handler_args)) + + def _generate_dispatcher_declaration_for_command(self, command): + return " void %s(long requestId, RefPtr<InspectorObject>&& parameters);" % command.command_name diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_backend_dispatcher_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_backend_dispatcher_implementation.py new file mode 100755 index 000000000..fccedcba7 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_backend_dispatcher_implementation.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014-2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from cpp_generator import CppGenerator +from cpp_generator_templates import CppGeneratorTemplates as CppTemplates +from generator import Generator, ucfirst +from models import ObjectType, ArrayType + +log = logging.getLogger('global') + + +class CppBackendDispatcherImplementationGenerator(CppGenerator): + def __init__(self, *args, **kwargs): + CppGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return "%sBackendDispatchers.cpp" % self.protocol_name() + + def domains_to_generate(self): + return filter(lambda domain: len(self.commands_for_domain(domain)) > 0, Generator.domains_to_generate(self)) + + def generate_output(self): + secondary_headers = [ + '<inspector/InspectorFrontendRouter.h>', + '<inspector/InspectorValues.h>', + '<wtf/NeverDestroyed.h>', + '<wtf/text/CString.h>'] + + secondary_includes = ['#include %s' % header for header in secondary_headers] + + if self.model().framework.setting('alternate_dispatchers', False): + secondary_includes.append('') + secondary_includes.append('#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS)') + secondary_includes.append('#include "%sAlternateBackendDispatchers.h"' % self.protocol_name()) + secondary_includes.append('#endif') + + header_args = { + 'primaryInclude': '"%sBackendDispatchers.h"' % self.protocol_name(), + 'secondaryIncludes': '\n'.join(secondary_includes), + } + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(CppTemplates.ImplementationPrelude).substitute(None, **header_args)) + sections.append("\n".join(map(self._generate_handler_class_destructor_for_domain, self.domains_to_generate()))) + sections.extend(map(self._generate_dispatcher_implementations_for_domain, self.domains_to_generate())) + sections.append(Template(CppTemplates.ImplementationPostlude).substitute(None, **header_args)) + return "\n\n".join(sections) + + # Private methods. + + def _generate_handler_class_destructor_for_domain(self, domain): + destructor_args = { + 'domainName': domain.domain_name + } + destructor = '%(domainName)sBackendDispatcherHandler::~%(domainName)sBackendDispatcherHandler() { }' % destructor_args + return self.wrap_with_guard_for_domain(domain, destructor) + + def _generate_dispatcher_implementations_for_domain(self, domain): + implementations = [] + + constructor_args = { + 'domainName': domain.domain_name, + } + implementations.append(Template(CppTemplates.BackendDispatcherImplementationDomainConstructor).substitute(None, **constructor_args)) + + commands = self.commands_for_domain(domain) + + if len(commands) <= 5: + implementations.append(self._generate_small_dispatcher_switch_implementation_for_domain(domain)) + else: + implementations.append(self._generate_large_dispatcher_switch_implementation_for_domain(domain)) + + for command in commands: + if command.is_async: + implementations.append(self._generate_async_dispatcher_class_for_domain(command, domain)) + implementations.append(self._generate_dispatcher_implementation_for_command(command, domain)) + + return self.wrap_with_guard_for_domain(domain, '\n\n'.join(implementations)) + + def _generate_small_dispatcher_switch_implementation_for_domain(self, domain): + commands = self.commands_for_domain(domain) + + cases = [] + cases.append(' if (method == "%s")' % commands[0].command_name) + cases.append(' %s(requestId, WTFMove(parameters));' % commands[0].command_name) + for command in commands[1:]: + cases.append(' else if (method == "%s")' % command.command_name) + cases.append(' %s(requestId, WTFMove(parameters));' % command.command_name) + + switch_args = { + 'domainName': domain.domain_name, + 'dispatchCases': "\n".join(cases) + } + + return Template(CppTemplates.BackendDispatcherImplementationSmallSwitch).substitute(None, **switch_args) + + def _generate_large_dispatcher_switch_implementation_for_domain(self, domain): + commands = self.commands_for_domain(domain) + + cases = [] + for command in commands: + args = { + 'domainName': domain.domain_name, + 'commandName': command.command_name + } + cases.append(' { "%(commandName)s", &%(domainName)sBackendDispatcher::%(commandName)s },' % args) + + switch_args = { + 'domainName': domain.domain_name, + 'dispatchCases': "\n".join(cases) + } + + return Template(CppTemplates.BackendDispatcherImplementationLargeSwitch).substitute(None, **switch_args) + + def _generate_async_dispatcher_class_for_domain(self, command, domain): + out_parameter_assignments = [] + formal_parameters = [] + + for parameter in command.return_parameters: + param_args = { + 'keyedSetMethod': CppGenerator.cpp_setter_method_for_type(parameter.type), + 'parameterKey': parameter.parameter_name, + 'parameterName': parameter.parameter_name, + 'parameterType': CppGenerator.cpp_type_for_stack_in_parameter(parameter), + 'helpersNamespace': self.helpers_namespace(), + } + + formal_parameters.append('%s %s' % (CppGenerator.cpp_type_for_formal_async_parameter(parameter), parameter.parameter_name)) + + if parameter.is_optional: + if CppGenerator.should_use_wrapper_for_return_type(parameter.type): + out_parameter_assignments.append(' if (%(parameterName)s.isAssigned())' % param_args) + out_parameter_assignments.append(' jsonMessage->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), %(parameterName)s.getValue());' % param_args) + else: + out_parameter_assignments.append(' if (%(parameterName)s)' % param_args) + out_parameter_assignments.append(' jsonMessage->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), %(parameterName)s);' % param_args) + elif parameter.type.is_enum(): + out_parameter_assignments.append(' jsonMessage->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), Inspector::Protocol::%(helpersNamespace)s::getEnumConstantValue(%(parameterName)s));' % param_args) + else: + out_parameter_assignments.append(' jsonMessage->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), %(parameterName)s);' % param_args) + + async_args = { + 'domainName': domain.domain_name, + 'callbackName': ucfirst(command.command_name) + 'Callback', + 'formalParameters': ", ".join(formal_parameters), + 'outParameterAssignments': "\n".join(out_parameter_assignments) + } + return Template(CppTemplates.BackendDispatcherImplementationAsyncCommand).substitute(None, **async_args) + + def _generate_dispatcher_implementation_for_command(self, command, domain): + in_parameter_declarations = [] + out_parameter_declarations = [] + out_parameter_assignments = [] + alternate_dispatcher_method_parameters = ['requestId'] + method_parameters = ['error'] + + for parameter in command.call_parameters: + parameter_name = 'in_' + parameter.parameter_name + if parameter.is_optional: + parameter_name = 'opt_' + parameter_name + + out_success_argument = 'nullptr' + if parameter.is_optional: + out_success_argument = '&%s_valueFound' % parameter_name + in_parameter_declarations.append(' bool %s_valueFound = false;' % parameter_name) + + # Now add appropriate operators. + parameter_expression = parameter_name + + if CppGenerator.should_use_references_for_type(parameter.type): + if parameter.is_optional: + parameter_expression = '%s.get()' % parameter_expression + else: + # This assumes that we have already proved the object is non-null. + # If a required property is missing, InspectorBackend::getObject will + # append a protocol error, and the method dispatcher will return without + # invoking the backend method (and dereferencing the object). + parameter_expression = '*%s' % parameter_expression + elif parameter.is_optional: + parameter_expression = '&%s' % parameter_expression + + param_args = { + 'parameterType': CppGenerator.cpp_type_for_stack_in_parameter(parameter), + 'parameterKey': parameter.parameter_name, + 'parameterName': parameter_name, + 'parameterExpression': parameter_expression, + 'keyedGetMethod': CppGenerator.cpp_getter_method_for_type(parameter.type), + 'successOutParam': out_success_argument + } + + in_parameter_declarations.append(' %(parameterType)s %(parameterName)s = m_backendDispatcher->%(keyedGetMethod)s(parameters.get(), ASCIILiteral("%(parameterKey)s"), %(successOutParam)s);' % param_args) + + if parameter.is_optional: + optional_in_parameter_string = '%(parameterName)s_valueFound ? %(parameterExpression)s : nullptr' % param_args + alternate_dispatcher_method_parameters.append(optional_in_parameter_string) + method_parameters.append(optional_in_parameter_string) + else: + alternate_dispatcher_method_parameters.append(parameter_expression) + method_parameters.append(parameter_expression) + + if command.is_async: + async_args = { + 'domainName': domain.domain_name, + 'callbackName': ucfirst(command.command_name) + 'Callback' + } + + out_parameter_assignments.append(' callback->disable();') + out_parameter_assignments.append(' m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, error);') + out_parameter_assignments.append(' return;') + method_parameters.append('callback.copyRef()') + + else: + for parameter in command.return_parameters: + param_args = { + 'parameterType': CppGenerator.cpp_type_for_stack_out_parameter(parameter), + 'parameterKey': parameter.parameter_name, + 'parameterName': parameter.parameter_name, + 'keyedSetMethod': CppGenerator.cpp_setter_method_for_type(parameter.type), + 'helpersNamespace': self.helpers_namespace(), + } + + out_parameter_declarations.append(' %(parameterType)s out_%(parameterName)s;' % param_args) + if parameter.is_optional: + if CppGenerator.should_use_wrapper_for_return_type(parameter.type): + out_parameter_assignments.append(' if (out_%(parameterName)s.isAssigned())' % param_args) + out_parameter_assignments.append(' result->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), out_%(parameterName)s.getValue());' % param_args) + else: + out_parameter_assignments.append(' if (out_%(parameterName)s)' % param_args) + out_parameter_assignments.append(' result->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), out_%(parameterName)s);' % param_args) + elif parameter.type.is_enum(): + out_parameter_assignments.append(' result->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), Inspector::Protocol::%(helpersNamespace)s::getEnumConstantValue(out_%(parameterName)s));' % param_args) + else: + out_parameter_assignments.append(' result->%(keyedSetMethod)s(ASCIILiteral("%(parameterKey)s"), out_%(parameterName)s);' % param_args) + + if CppGenerator.should_pass_by_copy_for_return_type(parameter.type): + method_parameters.append('out_' + parameter.parameter_name) + else: + method_parameters.append('&out_' + parameter.parameter_name) + + command_args = { + 'domainName': domain.domain_name, + 'callbackName': '%sCallback' % ucfirst(command.command_name), + 'commandName': command.command_name, + 'inParameterDeclarations': '\n'.join(in_parameter_declarations), + 'invocationParameters': ', '.join(method_parameters), + 'alternateInvocationParameters': ', '.join(alternate_dispatcher_method_parameters), + } + + lines = [] + if len(command.call_parameters) == 0: + lines.append('void %(domainName)sBackendDispatcher::%(commandName)s(long requestId, RefPtr<InspectorObject>&&)' % command_args) + else: + lines.append('void %(domainName)sBackendDispatcher::%(commandName)s(long requestId, RefPtr<InspectorObject>&& parameters)' % command_args) + lines.append('{') + + if len(command.call_parameters) > 0: + lines.append(Template(CppTemplates.BackendDispatcherImplementationPrepareCommandArguments).substitute(None, **command_args)) + + if self.model().framework.setting('alternate_dispatchers', False): + lines.append('#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS)') + lines.append(' if (m_alternateDispatcher) {') + lines.append(' m_alternateDispatcher->%(commandName)s(%(alternateInvocationParameters)s);' % command_args) + lines.append(' return;') + lines.append(' }') + lines.append('#endif') + lines.append('') + + lines.append(' ErrorString error;') + lines.append(' Ref<InspectorObject> result = InspectorObject::create();') + if command.is_async: + lines.append(' Ref<%(domainName)sBackendDispatcherHandler::%(callbackName)s> callback = adoptRef(*new %(domainName)sBackendDispatcherHandler::%(callbackName)s(m_backendDispatcher.copyRef(), requestId));' % command_args) + if len(command.return_parameters) > 0: + lines.extend(out_parameter_declarations) + lines.append(' m_agent->%(commandName)s(%(invocationParameters)s);' % command_args) + lines.append('') + if command.is_async: + lines.append(' if (error.length()) {') + lines.extend(out_parameter_assignments) + lines.append(' }') + elif len(command.return_parameters) > 1: + lines.append(' if (!error.length()) {') + lines.extend(out_parameter_assignments) + lines.append(' }') + elif len(command.return_parameters) == 1: + lines.append(' if (!error.length())') + lines.extend(out_parameter_assignments) + lines.append('') + + if not command.is_async: + lines.append(' if (!error.length())') + lines.append(' m_backendDispatcher->sendResponse(requestId, WTFMove(result));') + lines.append(' else') + lines.append(' m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error));') + lines.append('}') + return "\n".join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_frontend_dispatcher_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_frontend_dispatcher_header.py new file mode 100755 index 000000000..ed58b1e2f --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_frontend_dispatcher_header.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014-2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import re +import string +from string import Template + +from cpp_generator import CppGenerator +from cpp_generator_templates import CppGeneratorTemplates as CppTemplates +from generator import Generator, ucfirst +from models import EnumType + +log = logging.getLogger('global') + + +class CppFrontendDispatcherHeaderGenerator(CppGenerator): + def __init__(self, *args, **kwargs): + CppGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return "%sFrontendDispatchers.h" % self.protocol_name() + + def domains_to_generate(self): + return filter(lambda domain: len(self.events_for_domain(domain)) > 0, Generator.domains_to_generate(self)) + + def generate_output(self): + headers = [ + '"%sProtocolObjects.h"' % self.protocol_name(), + '<inspector/InspectorValues.h>', + '<wtf/text/WTFString.h>'] + + header_args = { + 'includes': '\n'.join(['#include ' + header for header in headers]), + 'typedefs': 'class FrontendRouter;', + } + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(CppTemplates.HeaderPrelude).substitute(None, **header_args)) + sections.extend(map(self._generate_dispatcher_declarations_for_domain, self.domains_to_generate())) + sections.append(Template(CppTemplates.HeaderPostlude).substitute(None, **header_args)) + return "\n\n".join(sections) + + # Private methods. + + def _generate_anonymous_enum_for_parameter(self, parameter, event): + enum_args = { + 'parameterName': parameter.parameter_name, + 'eventName': event.event_name + } + + lines = [] + lines.append(' // Named after parameter \'%(parameterName)s\' while generating command/event %(eventName)s.' % enum_args) + lines.append(' enum class %s {' % ucfirst(parameter.parameter_name)) + for enum_value in parameter.type.enum_values(): + lines.append(' %s = %d,' % (Generator.stylized_name_for_enum_value(enum_value), self.encoding_for_enum_value(enum_value))) + lines.append(' }; // enum class %s' % ucfirst(parameter.parameter_name)) + return "\n".join(lines) + + def _generate_dispatcher_declarations_for_domain(self, domain): + classComponents = ['class'] + exportMacro = self.model().framework.setting('export_macro', None) + if exportMacro is not None: + classComponents.append(exportMacro) + + used_enum_names = set([]) + + events = self.events_for_domain(domain) + event_declarations = [] + for event in events: + event_declarations.append(self._generate_dispatcher_declaration_for_event(event, domain, used_enum_names)) + + handler_args = { + 'classAndExportMacro': " ".join(classComponents), + 'domainName': domain.domain_name, + 'eventDeclarations': "\n".join(event_declarations) + } + + return self.wrap_with_guard_for_domain(domain, Template(CppTemplates.FrontendDispatcherDomainDispatcherDeclaration).substitute(None, **handler_args)) + + def _generate_dispatcher_declaration_for_event(self, event, domain, used_enum_names): + formal_parameters = [] + lines = [] + for parameter in event.event_parameters: + formal_parameters.append('%s %s' % (CppGenerator.cpp_type_for_checked_formal_event_parameter(parameter), parameter.parameter_name)) + if isinstance(parameter.type, EnumType) and parameter.parameter_name not in used_enum_names: + lines.append(self._generate_anonymous_enum_for_parameter(parameter, event)) + used_enum_names.add(parameter.parameter_name) + + lines.append(" void %s(%s);" % (event.event_name, ", ".join(formal_parameters))) + return "\n".join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_frontend_dispatcher_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_frontend_dispatcher_implementation.py new file mode 100755 index 000000000..0d0806903 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_frontend_dispatcher_implementation.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014-2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from cpp_generator import CppGenerator +from cpp_generator_templates import CppGeneratorTemplates as CppTemplates +from generator import Generator, ucfirst +from models import ObjectType, ArrayType + +log = logging.getLogger('global') + + +class CppFrontendDispatcherImplementationGenerator(CppGenerator): + def __init__(self, *args, **kwargs): + CppGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return "%sFrontendDispatchers.cpp" % self.protocol_name() + + def domains_to_generate(self): + return filter(lambda domain: len(self.events_for_domain(domain)) > 0, Generator.domains_to_generate(self)) + + def generate_output(self): + secondary_headers = [ + '"InspectorFrontendRouter.h"', + '<wtf/text/CString.h>', + ] + + header_args = { + 'primaryInclude': '"%sFrontendDispatchers.h"' % self.protocol_name(), + 'secondaryIncludes': "\n".join(['#include %s' % header for header in secondary_headers]), + } + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(CppTemplates.ImplementationPrelude).substitute(None, **header_args)) + sections.extend(map(self._generate_dispatcher_implementations_for_domain, self.domains_to_generate())) + sections.append(Template(CppTemplates.ImplementationPostlude).substitute(None, **header_args)) + return "\n\n".join(sections) + + # Private methods. + + def _generate_dispatcher_implementations_for_domain(self, domain): + implementations = [] + events = self.events_for_domain(domain) + for event in events: + implementations.append(self._generate_dispatcher_implementation_for_event(event, domain)) + + return self.wrap_with_guard_for_domain(domain, '\n\n'.join(implementations)) + + def _generate_dispatcher_implementation_for_event(self, event, domain): + lines = [] + parameter_assignments = [] + formal_parameters = [] + + for parameter in event.event_parameters: + + parameter_value = parameter.parameter_name + if parameter.is_optional and not CppGenerator.should_pass_by_copy_for_return_type(parameter.type): + parameter_value = '*' + parameter_value + if parameter.type.is_enum(): + parameter_value = 'Inspector::Protocol::%s::getEnumConstantValue(%s)' % (self.helpers_namespace(), parameter_value) + + parameter_args = { + 'parameterType': CppGenerator.cpp_type_for_stack_out_parameter(parameter), + 'parameterName': parameter.parameter_name, + 'parameterValue': parameter_value, + 'keyedSetMethod': CppGenerator.cpp_setter_method_for_type(parameter.type), + } + + if parameter.is_optional: + parameter_assignments.append(' if (%(parameterName)s)' % parameter_args) + parameter_assignments.append(' paramsObject->%(keyedSetMethod)s(ASCIILiteral("%(parameterName)s"), %(parameterValue)s);' % parameter_args) + else: + parameter_assignments.append(' paramsObject->%(keyedSetMethod)s(ASCIILiteral("%(parameterName)s"), %(parameterValue)s);' % parameter_args) + + formal_parameters.append('%s %s' % (CppGenerator.cpp_type_for_checked_formal_event_parameter(parameter), parameter.parameter_name)) + + event_args = { + 'domainName': domain.domain_name, + 'eventName': event.event_name, + 'formalParameters': ", ".join(formal_parameters) + } + + lines.append('void %(domainName)sFrontendDispatcher::%(eventName)s(%(formalParameters)s)' % event_args) + lines.append('{') + lines.append(' Ref<InspectorObject> jsonMessage = InspectorObject::create();') + lines.append(' jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("%(domainName)s.%(eventName)s"));' % event_args) + + if len(parameter_assignments) > 0: + lines.append(' Ref<InspectorObject> paramsObject = InspectorObject::create();') + lines.extend(parameter_assignments) + lines.append(' jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject));') + + lines.append('') + lines.append(' m_frontendRouter.sendEvent(jsonMessage->toJSONString());') + lines.append('}') + return "\n".join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_protocol_types_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_protocol_types_header.py new file mode 100755 index 000000000..1f91cdd0f --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_protocol_types_header.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import re +import string +from operator import methodcaller +from string import Template + +from cpp_generator import CppGenerator +from cpp_generator_templates import CppGeneratorTemplates as CppTemplates +from generator import Generator, ucfirst +from models import EnumType, ObjectType, PrimitiveType, AliasedType, ArrayType, Frameworks + +log = logging.getLogger('global') + + +class CppProtocolTypesHeaderGenerator(CppGenerator): + def __init__(self, *args, **kwargs): + CppGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return "%sProtocolObjects.h" % self.protocol_name() + + def generate_output(self): + domains = self.domains_to_generate() + self.calculate_types_requiring_shape_assertions(domains) + + headers = set([ + '<inspector/InspectorProtocolTypes.h>', + '<wtf/Assertions.h>', + ]) + + header_args = { + 'includes': '\n'.join(['#include ' + header for header in sorted(headers)]), + 'typedefs': '', + } + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(CppTemplates.HeaderPrelude).substitute(None, **header_args)) + sections.append('namespace Protocol {') + sections.append(self._generate_forward_declarations(domains)) + sections.append(self._generate_typedefs(domains)) + sections.extend(self._generate_enum_constant_value_conversion_methods()) + builder_sections = map(self._generate_builders_for_domain, domains) + sections.extend(filter(lambda section: len(section) > 0, builder_sections)) + sections.append(self._generate_forward_declarations_for_binding_traits()) + sections.extend(self._generate_declarations_for_enum_conversion_methods()) + sections.append('} // namespace Protocol') + sections.append(Template(CppTemplates.HeaderPostlude).substitute(None, **header_args)) + return "\n\n".join(sections) + + # Private methods. + + # FIXME: move builders out of classes, uncomment forward declaration + + def _generate_forward_declarations(self, domains): + sections = [] + + for domain in domains: + declaration_types = [decl.type for decl in self.type_declarations_for_domain(domain)] + object_types = filter(lambda _type: isinstance(_type, ObjectType), declaration_types) + enum_types = filter(lambda _type: isinstance(_type, EnumType), declaration_types) + sorted(object_types, key=methodcaller('raw_name')) + sorted(enum_types, key=methodcaller('raw_name')) + + if len(object_types) + len(enum_types) == 0: + continue + + domain_lines = [] + domain_lines.append('namespace %s {' % domain.domain_name) + + # Forward-declare all classes so the type builders won't break if rearranged. + domain_lines.extend('class %s;' % object_type.raw_name() for object_type in object_types) + domain_lines.extend('enum class %s;' % enum_type.raw_name() for enum_type in enum_types) + domain_lines.append('} // %s' % domain.domain_name) + sections.append(self.wrap_with_guard_for_domain(domain, '\n'.join(domain_lines))) + + if len(sections) == 0: + return '' + else: + return """// Forward declarations. +%s +// End of forward declarations. +""" % '\n\n'.join(sections) + + def _generate_typedefs(self, domains): + sections = map(self._generate_typedefs_for_domain, domains) + sections = filter(lambda text: len(text) > 0, sections) + + if len(sections) == 0: + return '' + else: + return """// Typedefs. +%s +// End of typedefs.""" % '\n\n'.join(sections) + + def _generate_typedefs_for_domain(self, domain): + type_declarations = self.type_declarations_for_domain(domain) + primitive_declarations = filter(lambda decl: isinstance(decl.type, AliasedType), type_declarations) + array_declarations = filter(lambda decl: isinstance(decl.type, ArrayType), type_declarations) + if len(primitive_declarations) == 0 and len(array_declarations) == 0: + return '' + + sections = [] + for declaration in primitive_declarations: + primitive_name = CppGenerator.cpp_name_for_primitive_type(declaration.type.aliased_type) + typedef_lines = [] + if len(declaration.description) > 0: + typedef_lines.append('/* %s */' % declaration.description) + typedef_lines.append('typedef %s %s;' % (primitive_name, declaration.type_name)) + sections.append('\n'.join(typedef_lines)) + + for declaration in array_declarations: + element_type = CppGenerator.cpp_protocol_type_for_type(declaration.type.element_type) + typedef_lines = [] + if len(declaration.description) > 0: + typedef_lines.append('/* %s */' % declaration.description) + typedef_lines.append('typedef Inspector::Protocol::Array<%s> %s;' % (element_type, declaration.type_name)) + sections.append('\n'.join(typedef_lines)) + + lines = [] + lines.append('namespace %s {' % domain.domain_name) + lines.append('\n'.join(sections)) + lines.append('} // %s' % domain.domain_name) + return self.wrap_with_guard_for_domain(domain, '\n'.join(lines)) + + def _generate_enum_constant_value_conversion_methods(self): + if not self.assigned_enum_values(): + return [] + + return_type = 'String' + return_type_with_export_macro = [return_type] + export_macro = self.model().framework.setting('export_macro', None) + if export_macro is not None: + return_type_with_export_macro[:0] = [export_macro] + + lines = [] + lines.append('namespace %s {' % self.helpers_namespace()) + lines.append('\n'.join([ + '%s getEnumConstantValue(int code);' % ' '.join(return_type_with_export_macro), + '', + 'template<typename T> %s getEnumConstantValue(T enumValue)' % return_type, + '{', + ' return getEnumConstantValue(static_cast<int>(enumValue));', + '}', + ])) + lines.append('} // namespace %s' % self.helpers_namespace()) + return lines + + def _generate_builders_for_domain(self, domain): + sections = [] + + type_declarations = self.type_declarations_for_domain(domain) + for type_declaration in type_declarations: + if isinstance(type_declaration.type, EnumType): + sections.append(self._generate_struct_for_enum_declaration(type_declaration)) + elif isinstance(type_declaration.type, ObjectType): + sections.append(self._generate_class_for_object_declaration(type_declaration, domain)) + + sections = filter(lambda section: len(section) > 0, sections) + if len(sections) == 0: + return '' + + lines = [] + lines.append('namespace %s {' % domain.domain_name) + lines.append('\n'.join(sections)) + lines.append('} // %s' % domain.domain_name) + return self.wrap_with_guard_for_domain(domain, '\n'.join(lines)) + + def _generate_class_for_object_declaration(self, type_declaration, domain): + if len(type_declaration.type_members) == 0: + return '' + + enum_members = filter(lambda member: isinstance(member.type, EnumType) and member.type.is_anonymous, type_declaration.type_members) + required_members = filter(lambda member: not member.is_optional, type_declaration.type_members) + optional_members = filter(lambda member: member.is_optional, type_declaration.type_members) + object_name = type_declaration.type_name + + lines = [] + if len(type_declaration.description) > 0: + lines.append('/* %s */' % type_declaration.description) + base_class = 'Inspector::InspectorObject' + if not Generator.type_has_open_fields(type_declaration.type): + base_class = base_class + 'Base' + lines.append('class %s : public %s {' % (object_name, base_class)) + lines.append('public:') + for enum_member in enum_members: + lines.append(' // Named after property name \'%s\' while generating %s.' % (enum_member.member_name, object_name)) + lines.append(self._generate_struct_for_anonymous_enum_member(enum_member)) + lines.append(self._generate_builder_state_enum(type_declaration)) + + constructor_example = [] + constructor_example.append(' * Ref<%s> result = %s::create()' % (object_name, object_name)) + for member in required_members: + constructor_example.append(' * .set%s(...)' % ucfirst(member.member_name)) + constructor_example.append(' * .release()') + + builder_args = { + 'objectType': object_name, + 'constructorExample': '\n'.join(constructor_example) + ';', + } + + lines.append(Template(CppTemplates.ProtocolObjectBuilderDeclarationPrelude).substitute(None, **builder_args)) + for type_member in required_members: + lines.append(self._generate_builder_setter_for_member(type_member, domain)) + lines.append(Template(CppTemplates.ProtocolObjectBuilderDeclarationPostlude).substitute(None, **builder_args)) + for member in optional_members: + lines.append(self._generate_unchecked_setter_for_member(member, domain)) + + if Generator.type_has_open_fields(type_declaration.type): + lines.append('') + lines.append(' // Property names for type generated as open.') + for type_member in type_declaration.type_members: + export_macro = self.model().framework.setting('export_macro', None) + lines.append(' %s static const char* %s;' % (export_macro, ucfirst(type_member.member_name))) + + lines.append('};') + lines.append('') + return '\n'.join(lines) + + def _generate_struct_for_enum_declaration(self, enum_declaration): + lines = [] + lines.append('/* %s */' % enum_declaration.description) + lines.extend(self._generate_struct_for_enum_type(enum_declaration.type_name, enum_declaration.type)) + return '\n'.join(lines) + + def _generate_struct_for_anonymous_enum_member(self, enum_member): + def apply_indentation(line): + if line.startswith(('#', '/*', '*/', '//')) or len(line) is 0: + return line + else: + return ' ' + line + + indented_lines = map(apply_indentation, self._generate_struct_for_enum_type(enum_member.member_name, enum_member.type)) + return '\n'.join(indented_lines) + + def _generate_struct_for_enum_type(self, enum_name, enum_type): + lines = [] + enum_name = ucfirst(enum_name) + lines.append('enum class %s {' % enum_name) + for enum_value in enum_type.enum_values(): + lines.append(' %s = %s,' % (Generator.stylized_name_for_enum_value(enum_value), self.encoding_for_enum_value(enum_value))) + lines.append('}; // enum class %s' % enum_name) + return lines # The caller may want to adjust indentation, so don't join these lines. + + def _generate_builder_state_enum(self, type_declaration): + lines = [] + required_members = filter(lambda member: not member.is_optional, type_declaration.type_members) + enum_values = [] + + lines.append(' enum {') + lines.append(' NoFieldsSet = 0,') + for i in range(len(required_members)): + enum_value = "%sSet" % ucfirst(required_members[i].member_name) + enum_values.append(enum_value) + lines.append(' %s = 1 << %d,' % (enum_value, i)) + if len(enum_values) > 0: + lines.append(' AllFieldsSet = (%s)' % ' | '.join(enum_values)) + else: + lines.append(' AllFieldsSet = 0') + lines.append(' };') + lines.append('') + return '\n'.join(lines) + + def _generate_builder_setter_for_member(self, type_member, domain): + setter_args = { + 'camelName': ucfirst(type_member.member_name), + 'keyedSet': CppGenerator.cpp_setter_method_for_type(type_member.type), + 'name': type_member.member_name, + 'parameterType': CppGenerator.cpp_type_for_type_member(type_member), + 'helpersNamespace': self.helpers_namespace(), + } + + lines = [] + lines.append('') + lines.append(' Builder<STATE | %(camelName)sSet>& set%(camelName)s(%(parameterType)s value)' % setter_args) + lines.append(' {') + lines.append(' COMPILE_ASSERT(!(STATE & %(camelName)sSet), property_%(name)s_already_set);' % setter_args) + + if isinstance(type_member.type, EnumType): + lines.append(' m_result->%(keyedSet)s(ASCIILiteral("%(name)s"), Inspector::Protocol::%(helpersNamespace)s::getEnumConstantValue(value));' % setter_args) + else: + lines.append(' m_result->%(keyedSet)s(ASCIILiteral("%(name)s"), value);' % setter_args) + lines.append(' return castState<%(camelName)sSet>();' % setter_args) + lines.append(' }') + return '\n'.join(lines) + + def _generate_unchecked_setter_for_member(self, type_member, domain): + setter_args = { + 'camelName': ucfirst(type_member.member_name), + 'keyedSet': CppGenerator.cpp_setter_method_for_type(type_member.type), + 'name': type_member.member_name, + 'parameterType': CppGenerator.cpp_type_for_type_member(type_member), + 'helpersNamespace': self.helpers_namespace(), + } + + lines = [] + lines.append('') + lines.append(' void set%(camelName)s(%(parameterType)s value)' % setter_args) + lines.append(' {') + if isinstance(type_member.type, EnumType): + lines.append(' InspectorObjectBase::%(keyedSet)s(ASCIILiteral("%(name)s"), Inspector::Protocol::%(helpersNamespace)s::getEnumConstantValue(value));' % setter_args) + elif CppGenerator.should_use_references_for_type(type_member.type): + lines.append(' InspectorObjectBase::%(keyedSet)s(ASCIILiteral("%(name)s"), WTFMove(value));' % setter_args) + else: + lines.append(' InspectorObjectBase::%(keyedSet)s(ASCIILiteral("%(name)s"), value);' % setter_args) + lines.append(' }') + return '\n'.join(lines) + + def _generate_forward_declarations_for_binding_traits(self): + # A list of (builder_type, needs_runtime_cast) + type_arguments = [] + + for domain in self.domains_to_generate(): + type_declarations = self.type_declarations_for_domain(domain) + declarations_to_generate = filter(lambda decl: self.type_needs_shape_assertions(decl.type), type_declarations) + + for type_declaration in declarations_to_generate: + for type_member in type_declaration.type_members: + if isinstance(type_member.type, EnumType): + type_arguments.append((CppGenerator.cpp_protocol_type_for_type_member(type_member, type_declaration), False)) + + if isinstance(type_declaration.type, ObjectType): + type_arguments.append((CppGenerator.cpp_protocol_type_for_type(type_declaration.type), Generator.type_needs_runtime_casts(type_declaration.type))) + + struct_keywords = ['struct'] + function_keywords = ['static void'] + export_macro = self.model().framework.setting('export_macro', None) + if export_macro is not None: + struct_keywords.append(export_macro) + #function_keywords[1:1] = [export_macro] + + lines = [] + for argument in type_arguments: + lines.append('template<> %s BindingTraits<%s> {' % (' '.join(struct_keywords), argument[0])) + if argument[1]: + lines.append('static RefPtr<%s> runtimeCast(RefPtr<Inspector::InspectorValue>&& value);' % argument[0]) + lines.append('#if !ASSERT_DISABLED') + lines.append('%s assertValueHasExpectedType(Inspector::InspectorValue*);' % ' '.join(function_keywords)) + lines.append('#endif // !ASSERT_DISABLED') + lines.append('};') + return '\n'.join(lines) + + def _generate_declarations_for_enum_conversion_methods(self): + sections = [] + sections.append('\n'.join([ + 'namespace %s {' % self.helpers_namespace(), + '', + 'template<typename ProtocolEnumType>', + 'std::optional<ProtocolEnumType> parseEnumValueFromString(const String&);', + ])) + + def return_type_with_export_macro(cpp_protocol_type): + enum_return_type = 'std::optional<%s>' % cpp_protocol_type + result_terms = [enum_return_type] + export_macro = self.model().framework.setting('export_macro', None) + if export_macro is not None: + result_terms[:0] = [export_macro] + return ' '.join(result_terms) + + def type_member_is_anonymous_enum_type(type_member): + return isinstance(type_member.type, EnumType) and type_member.type.is_anonymous + + for domain in self.domains_to_generate(): + type_declarations = self.type_declarations_for_domain(domain) + declaration_types = [decl.type for decl in type_declarations] + object_types = filter(lambda _type: isinstance(_type, ObjectType), declaration_types) + enum_types = filter(lambda _type: isinstance(_type, EnumType), declaration_types) + if len(object_types) + len(enum_types) == 0: + continue + + sorted(object_types, key=methodcaller('raw_name')) + sorted(enum_types, key=methodcaller('raw_name')) + + domain_lines = [] + domain_lines.append("// Enums in the '%s' Domain" % domain.domain_name) + for enum_type in enum_types: + cpp_protocol_type = CppGenerator.cpp_protocol_type_for_type(enum_type) + domain_lines.append('template<>') + domain_lines.append('%s parseEnumValueFromString<%s>(const String&);' % (return_type_with_export_macro(cpp_protocol_type), cpp_protocol_type)) + + for object_type in object_types: + for enum_member in filter(type_member_is_anonymous_enum_type, object_type.members): + cpp_protocol_type = CppGenerator.cpp_protocol_type_for_type_member(enum_member, object_type.declaration()) + domain_lines.append('template<>') + domain_lines.append('%s parseEnumValueFromString<%s>(const String&);' % (return_type_with_export_macro(cpp_protocol_type), cpp_protocol_type)) + + if len(domain_lines) == 1: + continue # No real declarations to emit, just the domain comment. Skip. + + sections.append(self.wrap_with_guard_for_domain(domain, '\n'.join(domain_lines))) + + if len(sections) == 1: + return [] # No real sections to emit, just the namespace and template declaration. Skip. + + sections.append('} // namespace %s' % self.helpers_namespace()) + + return ['\n\n'.join(sections)] diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_protocol_types_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_protocol_types_implementation.py new file mode 100755 index 000000000..f302a7342 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_cpp_protocol_types_implementation.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template +from operator import methodcaller + +from cpp_generator import CppGenerator +from cpp_generator_templates import CppGeneratorTemplates as CppTemplates +from generator import Generator, ucfirst +from models import AliasedType, ArrayType, EnumType, ObjectType + +log = logging.getLogger('global') + + +class CppProtocolTypesImplementationGenerator(CppGenerator): + def __init__(self, *args, **kwargs): + CppGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return "%sProtocolObjects.cpp" % self.protocol_name() + + def generate_output(self): + domains = self.domains_to_generate() + self.calculate_types_requiring_shape_assertions(domains) + + secondary_headers = [ + '<wtf/Optional.h>', + '<wtf/text/CString.h>', + ] + + header_args = { + 'primaryInclude': '"%sProtocolObjects.h"' % self.protocol_name(), + 'secondaryIncludes': "\n".join(['#include %s' % header for header in secondary_headers]), + } + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(CppTemplates.ImplementationPrelude).substitute(None, **header_args)) + sections.append('namespace Protocol {') + sections.extend(self._generate_enum_mapping_and_conversion_methods(domains)) + sections.append(self._generate_open_field_names()) + builder_sections = map(self._generate_builders_for_domain, domains) + sections.extend(filter(lambda section: len(section) > 0, builder_sections)) + sections.append('} // namespace Protocol') + sections.append(Template(CppTemplates.ImplementationPostlude).substitute(None, **header_args)) + + return "\n\n".join(sections) + + # Private methods. + + def _generate_enum_mapping(self): + if not self.assigned_enum_values(): + return [] + + lines = [] + lines.append('static const char* const enum_constant_values[] = {') + lines.extend([' "%s",' % enum_value for enum_value in self.assigned_enum_values()]) + lines.append('};') + lines.append('') + lines.append('String getEnumConstantValue(int code) {') + lines.append(' return enum_constant_values[code];') + lines.append('}') + return ['\n'.join(lines)] + + def _generate_enum_conversion_methods_for_domain(self, domain): + + def type_member_is_anonymous_enum_type(type_member): + return isinstance(type_member.type, EnumType) and type_member.type.is_anonymous + + def generate_conversion_method_body(enum_type, cpp_protocol_type): + body_lines = [] + body_lines.extend([ + 'template<>', + 'std::optional<%s> parseEnumValueFromString<%s>(const String& protocolString)' % (cpp_protocol_type, cpp_protocol_type), + '{', + ' static const size_t constantValues[] = {', + ]) + + enum_values = enum_type.enum_values() + for enum_value in enum_values: + body_lines.append(' (size_t)%s::%s,' % (cpp_protocol_type, Generator.stylized_name_for_enum_value(enum_value))) + + body_lines.extend([ + ' };', + ' for (size_t i = 0; i < %d; ++i)' % len(enum_values), + ' if (protocolString == enum_constant_values[constantValues[i]])', + ' return (%s)constantValues[i];' % cpp_protocol_type, + '', + ' return std::nullopt;', + '}', + '', + ]) + return body_lines + + type_declarations = self.type_declarations_for_domain(domain) + declaration_types = [decl.type for decl in type_declarations] + object_types = filter(lambda _type: isinstance(_type, ObjectType), declaration_types) + enum_types = filter(lambda _type: isinstance(_type, EnumType), declaration_types) + if len(object_types) + len(enum_types) == 0: + return '' + + sorted(object_types, key=methodcaller('raw_name')) + sorted(enum_types, key=methodcaller('raw_name')) + + lines = [] + lines.append("// Enums in the '%s' Domain" % domain.domain_name) + for enum_type in enum_types: + cpp_protocol_type = CppGenerator.cpp_protocol_type_for_type(enum_type) + lines.extend(generate_conversion_method_body(enum_type, cpp_protocol_type)) + + for object_type in object_types: + for enum_member in filter(type_member_is_anonymous_enum_type, object_type.members): + cpp_protocol_type = CppGenerator.cpp_protocol_type_for_type_member(enum_member, object_type.declaration()) + lines.extend(generate_conversion_method_body(enum_member.type, cpp_protocol_type)) + + if len(lines) == 1: + return '' # No real declarations to emit, just the domain comment. + + return self.wrap_with_guard_for_domain(domain, '\n'.join(lines)) + + def _generate_enum_mapping_and_conversion_methods(self, domains): + sections = [] + sections.append('namespace %s {' % self.helpers_namespace()) + sections.extend(self._generate_enum_mapping()) + enum_parser_sections = map(self._generate_enum_conversion_methods_for_domain, domains) + sections.extend(filter(lambda section: len(section) > 0, enum_parser_sections)) + if len(sections) == 1: + return [] # No declarations to emit, just the namespace. + + sections.append('} // namespace %s' % self.helpers_namespace()) + return sections + + def _generate_open_field_names(self): + lines = [] + for domain in self.domains_to_generate(): + type_declarations = self.type_declarations_for_domain(domain) + for type_declaration in filter(lambda decl: Generator.type_has_open_fields(decl.type), type_declarations): + for type_member in sorted(type_declaration.type_members, key=lambda member: member.member_name): + field_name = '::'.join(['Inspector', 'Protocol', domain.domain_name, ucfirst(type_declaration.type_name), ucfirst(type_member.member_name)]) + lines.append('const char* %s = "%s";' % (field_name, type_member.member_name)) + + return '\n'.join(lines) + + def _generate_builders_for_domain(self, domain): + sections = [] + type_declarations = self.type_declarations_for_domain(domain) + declarations_to_generate = filter(lambda decl: self.type_needs_shape_assertions(decl.type), type_declarations) + + for type_declaration in declarations_to_generate: + for type_member in type_declaration.type_members: + if isinstance(type_member.type, EnumType): + sections.append(self._generate_assertion_for_enum(type_member, type_declaration)) + + if isinstance(type_declaration.type, ObjectType): + sections.append(self._generate_assertion_for_object_declaration(type_declaration)) + if Generator.type_needs_runtime_casts(type_declaration.type): + sections.append(self._generate_runtime_cast_for_object_declaration(type_declaration)) + + return '\n\n'.join(sections) + + def _generate_runtime_cast_for_object_declaration(self, object_declaration): + args = { + 'objectType': CppGenerator.cpp_protocol_type_for_type(object_declaration.type) + } + return Template(CppTemplates.ProtocolObjectRuntimeCast).substitute(None, **args) + + def _generate_assertion_for_object_declaration(self, object_declaration): + required_members = filter(lambda member: not member.is_optional, object_declaration.type_members) + optional_members = filter(lambda member: member.is_optional, object_declaration.type_members) + should_count_properties = not Generator.type_has_open_fields(object_declaration.type) + lines = [] + + lines.append('#if !ASSERT_DISABLED') + lines.append('void BindingTraits<%s>::assertValueHasExpectedType(Inspector::InspectorValue* value)' % (CppGenerator.cpp_protocol_type_for_type(object_declaration.type))) + lines.append("""{ + ASSERT_ARG(value, value); + RefPtr<InspectorObject> object; + bool castSucceeded = value->asObject(object); + ASSERT_UNUSED(castSucceeded, castSucceeded);""") + for type_member in required_members: + args = { + 'memberName': type_member.member_name, + 'assertMethod': CppGenerator.cpp_assertion_method_for_type_member(type_member, object_declaration) + } + + lines.append(""" { + InspectorObject::iterator %(memberName)sPos = object->find(ASCIILiteral("%(memberName)s")); + ASSERT(%(memberName)sPos != object->end()); + %(assertMethod)s(%(memberName)sPos->value.get()); + }""" % args) + + if should_count_properties: + lines.append('') + lines.append(' int foundPropertiesCount = %s;' % len(required_members)) + + for type_member in optional_members: + args = { + 'memberName': type_member.member_name, + 'assertMethod': CppGenerator.cpp_assertion_method_for_type_member(type_member, object_declaration) + } + + lines.append(""" { + InspectorObject::iterator %(memberName)sPos = object->find(ASCIILiteral("%(memberName)s")); + if (%(memberName)sPos != object->end()) { + %(assertMethod)s(%(memberName)sPos->value.get());""" % args) + + if should_count_properties: + lines.append(' ++foundPropertiesCount;') + lines.append(' }') + lines.append(' }') + + if should_count_properties: + lines.append(' if (foundPropertiesCount != object->size())') + lines.append(' FATAL("Unexpected properties in object: %s\\n", object->toJSONString().ascii().data());') + lines.append('}') + lines.append('#endif // !ASSERT_DISABLED') + return '\n'.join(lines) + + def _generate_assertion_for_enum(self, enum_member, object_declaration): + lines = [] + lines.append('#if !ASSERT_DISABLED') + lines.append('void %s(Inspector::InspectorValue* value)' % CppGenerator.cpp_assertion_method_for_type_member(enum_member, object_declaration)) + lines.append('{') + lines.append(' ASSERT_ARG(value, value);') + lines.append(' String result;') + lines.append(' bool castSucceeded = value->asString(result);') + lines.append(' ASSERT(castSucceeded);') + + assert_condition = ' || '.join(['result == "%s"' % enum_value for enum_value in enum_member.type.enum_values()]) + lines.append(' ASSERT(%s);' % assert_condition) + lines.append('}') + lines.append('#endif // !ASSERT_DISABLED') + + return '\n'.join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_js_backend_commands.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_js_backend_commands.py new file mode 100755 index 000000000..555c12f89 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_js_backend_commands.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator, ucfirst +from generator_templates import GeneratorTemplates as Templates +from models import EnumType + +log = logging.getLogger('global') + + +class JSBackendCommandsGenerator(Generator): + def __init__(self, *args, **kwargs): + Generator.__init__(self, *args, **kwargs) + + def output_filename(self): + return "InspectorBackendCommands.js" + + def should_generate_domain(self, domain): + type_declarations = self.type_declarations_for_domain(domain) + domain_enum_types = filter(lambda declaration: isinstance(declaration.type, EnumType), type_declarations) + return len(self.commands_for_domain(domain)) > 0 or len(self.events_for_domain(domain)) > 0 or len(domain_enum_types) > 0 + + def domains_to_generate(self): + return filter(self.should_generate_domain, Generator.domains_to_generate(self)) + + def generate_output(self): + sections = [] + sections.append(self.generate_license()) + sections.extend(map(self.generate_domain, self.domains_to_generate())) + return "\n\n".join(sections) + + def generate_domain(self, domain): + lines = [] + args = { + 'domain': domain.domain_name + } + + lines.append('// %(domain)s.' % args) + + type_declarations = self.type_declarations_for_domain(domain) + commands = self.commands_for_domain(domain) + events = self.events_for_domain(domain) + + has_async_commands = any(map(lambda command: command.is_async, commands)) + if len(events) > 0 or has_async_commands: + lines.append('InspectorBackend.register%(domain)sDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "%(domain)s");' % args) + + for declaration in type_declarations: + if declaration.type.is_enum(): + enum_args = { + 'domain': domain.domain_name, + 'enumName': declaration.type_name, + 'enumMap': ", ".join(['%s: "%s"' % (Generator.stylized_name_for_enum_value(enum_value), enum_value) for enum_value in declaration.type.enum_values()]) + } + lines.append('InspectorBackend.registerEnum("%(domain)s.%(enumName)s", {%(enumMap)s});' % enum_args) + + def is_anonymous_enum_member(type_member): + return isinstance(type_member.type, EnumType) and type_member.type.is_anonymous + + for _member in filter(is_anonymous_enum_member, declaration.type_members): + enum_args = { + 'domain': domain.domain_name, + 'enumName': '%s%s' % (declaration.type_name, ucfirst(_member.member_name)), + 'enumMap': ", ".join(['%s: "%s"' % (Generator.stylized_name_for_enum_value(enum_value), enum_value) for enum_value in _member.type.enum_values()]) + } + lines.append('InspectorBackend.registerEnum("%(domain)s.%(enumName)s", {%(enumMap)s});' % enum_args) + + def is_anonymous_enum_param(param): + return isinstance(param.type, EnumType) and param.type.is_anonymous + + for event in events: + for param in filter(is_anonymous_enum_param, event.event_parameters): + enum_args = { + 'domain': domain.domain_name, + 'enumName': '%s%s' % (ucfirst(event.event_name), ucfirst(param.parameter_name)), + 'enumMap': ", ".join(['%s: "%s"' % (Generator.stylized_name_for_enum_value(enum_value), enum_value) for enum_value in param.type.enum_values()]) + } + lines.append('InspectorBackend.registerEnum("%(domain)s.%(enumName)s", {%(enumMap)s});' % enum_args) + + event_args = { + 'domain': domain.domain_name, + 'eventName': event.event_name, + 'params': ", ".join(['"%s"' % parameter.parameter_name for parameter in event.event_parameters]) + } + lines.append('InspectorBackend.registerEvent("%(domain)s.%(eventName)s", [%(params)s]);' % event_args) + + for command in commands: + def generate_parameter_object(parameter): + optional_string = "true" if parameter.is_optional else "false" + pairs = [] + pairs.append('"name": "%s"' % parameter.parameter_name) + pairs.append('"type": "%s"' % Generator.js_name_for_parameter_type(parameter.type)) + pairs.append('"optional": %s' % optional_string) + return "{%s}" % ", ".join(pairs) + + command_args = { + 'domain': domain.domain_name, + 'commandName': command.command_name, + 'callParams': ", ".join([generate_parameter_object(parameter) for parameter in command.call_parameters]), + 'returnParams': ", ".join(['"%s"' % parameter.parameter_name for parameter in command.return_parameters]), + } + lines.append('InspectorBackend.registerCommand("%(domain)s.%(commandName)s", [%(callParams)s], [%(returnParams)s]);' % command_args) + + if commands or events: + activate_args = { + 'domain': domain.domain_name, + 'availability': domain.availability, + } + if domain.availability: + lines.append('InspectorBackend.activateDomain("%(domain)s", "%(availability)s");' % activate_args) + else: + lines.append('InspectorBackend.activateDomain("%(domain)s");' % activate_args) + + if domain.workerSupported: + lines.append('InspectorBackend.workerSupportedDomain("%s");' % domain.domain_name) + + return "\n".join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_backend_dispatcher_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_backend_dispatcher_header.py new file mode 100755 index 000000000..0531ed53b --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_backend_dispatcher_header.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +import re +from string import Template + +from cpp_generator import CppGenerator +from generator import Generator +from models import Frameworks +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +class ObjCBackendDispatcherHeaderGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sBackendDispatchers.h' % self.protocol_name() + + def domains_to_generate(self): + return filter(self.should_generate_commands_for_domain, Generator.domains_to_generate(self)) + + def generate_output(self): + headers = [ + '<JavaScriptCore/InspectorAlternateBackendDispatchers.h>', + '<wtf/RetainPtr.h>', + ] + + header_args = { + 'includes': '\n'.join(['#include ' + header for header in headers]), + 'forwardDeclarations': self._generate_objc_forward_declarations(), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.BackendDispatcherHeaderPrelude).substitute(None, **header_args)) + sections.extend(map(self._generate_objc_handler_declarations_for_domain, domains)) + sections.append(Template(ObjCTemplates.BackendDispatcherHeaderPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_objc_forward_declarations(self): + lines = [] + for domain in self.domains_to_generate(): + if self.commands_for_domain(domain): + lines.append('@protocol %s%sDomainHandler;' % (self.objc_prefix(), domain.domain_name)) + return '\n'.join(lines) + + def _generate_objc_handler_declarations_for_domain(self, domain): + commands = self.commands_for_domain(domain) + if not commands: + return '' + + command_declarations = [] + for command in commands: + command_declarations.append(self._generate_objc_handler_declaration_for_command(command)) + + handler_args = { + 'domainName': domain.domain_name, + 'commandDeclarations': '\n'.join(command_declarations), + 'objcPrefix': self.objc_prefix(), + } + + return self.wrap_with_guard_for_domain(domain, Template(ObjCTemplates.BackendDispatcherHeaderDomainHandlerObjCDeclaration).substitute(None, **handler_args)) + + def _generate_objc_handler_declaration_for_command(self, command): + lines = [] + parameters = ['long requestId'] + for _parameter in command.call_parameters: + parameters.append('%s in_%s' % (CppGenerator.cpp_type_for_unchecked_formal_in_parameter(_parameter), _parameter.parameter_name)) + + command_args = { + 'commandName': command.command_name, + 'parameters': ', '.join(parameters), + } + lines.append(' virtual void %(commandName)s(%(parameters)s) override;' % command_args) + return '\n'.join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_backend_dispatcher_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_backend_dispatcher_implementation.py new file mode 100755 index 000000000..0b1055d24 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_backend_dispatcher_implementation.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014-2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +import re +from string import Template + +from cpp_generator import CppGenerator +from generator import Generator +from models import PrimitiveType, EnumType, AliasedType, Frameworks +from objc_generator import ObjCTypeCategory, ObjCGenerator, join_type_and_name +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +class ObjCBackendDispatcherImplementationGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sBackendDispatchers.mm' % self.protocol_name() + + def domains_to_generate(self): + return filter(self.should_generate_commands_for_domain, Generator.domains_to_generate(self)) + + def generate_output(self): + secondary_headers = [ + '"%sInternal.h"' % self.protocol_name(), + '"%sTypeConversions.h"' % self.protocol_name(), + '<JavaScriptCore/InspectorValues.h>', + ] + + header_args = { + 'primaryInclude': '"%sBackendDispatchers.h"' % self.protocol_name(), + 'secondaryIncludes': '\n'.join(['#include %s' % header for header in secondary_headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.BackendDispatcherImplementationPrelude).substitute(None, **header_args)) + sections.extend(map(self._generate_handler_implementation_for_domain, domains)) + sections.append(Template(ObjCTemplates.BackendDispatcherImplementationPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_handler_implementation_for_domain(self, domain): + commands = self.commands_for_domain(domain) + + if not commands: + return '' + + command_declarations = [] + for command in commands: + command_declarations.append(self._generate_handler_implementation_for_command(domain, command)) + + return '\n'.join(command_declarations) + + def _generate_handler_implementation_for_command(self, domain, command): + lines = [] + parameters = ['long requestId'] + for parameter in command.call_parameters: + parameters.append('%s in_%s' % (CppGenerator.cpp_type_for_unchecked_formal_in_parameter(parameter), parameter.parameter_name)) + + command_args = { + 'domainName': domain.domain_name, + 'commandName': command.command_name, + 'parameters': ', '.join(parameters), + 'successCallback': self._generate_success_block_for_command(domain, command), + 'conversions': self._generate_conversions_for_command(domain, command), + 'invocation': self._generate_invocation_for_command(domain, command), + } + + return self.wrap_with_guard_for_domain(domain, Template(ObjCTemplates.BackendDispatcherHeaderDomainHandlerImplementation).substitute(None, **command_args)) + + def _generate_success_block_for_command(self, domain, command): + lines = [] + + if command.return_parameters: + success_block_parameters = [] + for parameter in command.return_parameters: + objc_type = self.objc_type_for_param(domain, command.command_name, parameter) + var_name = ObjCGenerator.identifier_to_objc_identifier(parameter.parameter_name) + success_block_parameters.append(join_type_and_name(objc_type, var_name)) + lines.append(' id successCallback = ^(%s) {' % ', '.join(success_block_parameters)) + else: + lines.append(' id successCallback = ^{') + + if command.return_parameters: + lines.append(' Ref<InspectorObject> resultObject = InspectorObject::create();') + + required_pointer_parameters = filter(lambda parameter: not parameter.is_optional and ObjCGenerator.is_type_objc_pointer_type(parameter.type), command.return_parameters) + for parameter in required_pointer_parameters: + var_name = ObjCGenerator.identifier_to_objc_identifier(parameter.parameter_name) + lines.append(' THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(%s, @"%s");' % (var_name, var_name)) + objc_array_class = self.objc_class_for_array_type(parameter.type) + if objc_array_class and objc_array_class.startswith(self.objc_prefix()): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE_IN_ARRAY(%s, [%s class]);' % (var_name, objc_array_class)) + + optional_pointer_parameters = filter(lambda parameter: parameter.is_optional and ObjCGenerator.is_type_objc_pointer_type(parameter.type), command.return_parameters) + for parameter in optional_pointer_parameters: + var_name = ObjCGenerator.identifier_to_objc_identifier(parameter.parameter_name) + lines.append(' THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(%s, @"%s");' % (var_name, var_name)) + objc_array_class = self.objc_class_for_array_type(parameter.type) + if objc_array_class and objc_array_class.startswith(self.objc_prefix()): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE_IN_OPTIONAL_ARRAY(%s, [%s class]);' % (var_name, objc_array_class)) + + for parameter in command.return_parameters: + keyed_set_method = CppGenerator.cpp_setter_method_for_type(parameter.type) + var_name = ObjCGenerator.identifier_to_objc_identifier(parameter.parameter_name) + var_expression = '*%s' % var_name if parameter.is_optional else var_name + export_expression = self.objc_protocol_export_expression_for_variable(parameter.type, var_expression) + if not parameter.is_optional: + lines.append(' resultObject->%s(ASCIILiteral("%s"), %s);' % (keyed_set_method, parameter.parameter_name, export_expression)) + else: + lines.append(' if (%s)' % var_name) + lines.append(' resultObject->%s(ASCIILiteral("%s"), %s);' % (keyed_set_method, parameter.parameter_name, export_expression)) + lines.append(' backendDispatcher()->sendResponse(requestId, WTFMove(resultObject));') + else: + lines.append(' backendDispatcher()->sendResponse(requestId, InspectorObject::create());') + + lines.append(' };') + return '\n'.join(lines) + + def _generate_conversions_for_command(self, domain, command): + lines = [] + if command.call_parameters: + lines.append('') + + def in_param_expression(param_name, parameter): + _type = parameter.type + if isinstance(_type, AliasedType): + _type = _type.aliased_type # Fall through to enum or primitive. + if isinstance(_type, EnumType): + _type = _type.primitive_type # Fall through to primitive. + if isinstance(_type, PrimitiveType): + if _type.raw_name() in ['array', 'any', 'object']: + return '&%s' % param_name if not parameter.is_optional else param_name + return '*%s' % param_name if parameter.is_optional else param_name + return '&%s' % param_name if not parameter.is_optional else param_name + + for parameter in command.call_parameters: + in_param_name = 'in_%s' % parameter.parameter_name + objc_in_param_name = 'o_%s' % in_param_name + objc_type = self.objc_type_for_param(domain, command.command_name, parameter, False) + if isinstance(parameter.type, EnumType): + objc_type = 'std::optional<%s>' % objc_type + param_expression = in_param_expression(in_param_name, parameter) + import_expression = self.objc_protocol_import_expression_for_parameter(param_expression, domain, command.command_name, parameter) + if not parameter.is_optional: + lines.append(' %s = %s;' % (join_type_and_name(objc_type, objc_in_param_name), import_expression)) + + if isinstance(parameter.type, EnumType): + lines.append(' if (!%s) {' % objc_in_param_name) + lines.append(' backendDispatcher()->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Parameter \'%%s\' of method \'%%s\' cannot be processed", "%s", "%s.%s"));' % (parameter.parameter_name, domain.domain_name, command.command_name)) + lines.append(' return;') + lines.append(' }') + + else: + lines.append(' %s;' % join_type_and_name(objc_type, objc_in_param_name)) + lines.append(' if (%s)' % in_param_name) + lines.append(' %s = %s;' % (objc_in_param_name, import_expression)) + + if lines: + lines.append('') + return '\n'.join(lines) + + def _generate_invocation_for_command(self, domain, command): + pairs = [] + pairs.append('WithErrorCallback:errorCallback') + pairs.append('successCallback:successCallback') + for parameter in command.call_parameters: + in_param_name = 'in_%s' % parameter.parameter_name + objc_in_param_expression = 'o_%s' % in_param_name + if not parameter.is_optional: + # FIXME: we don't handle optional enum values in commands here because it isn't used anywhere yet. + # We'd need to change the delegate's signature to take std::optional for optional enum values. + if isinstance(parameter.type, EnumType): + objc_in_param_expression = '%s.value()' % objc_in_param_expression + + pairs.append('%s:%s' % (parameter.parameter_name, objc_in_param_expression)) + else: + optional_expression = '(%s ? &%s : nil)' % (in_param_name, objc_in_param_expression) + pairs.append('%s:%s' % (parameter.parameter_name, optional_expression)) + return ' [m_delegate %s%s];' % (command.command_name, ' '.join(pairs)) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_configuration_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_configuration_header.py new file mode 100755 index 000000000..a232e2ce4 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_configuration_header.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +class ObjCConfigurationHeaderGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sConfiguration.h' % self.protocol_name() + + def generate_output(self): + headers = [ + '<WebInspector/%s.h>' % self.protocol_name(), + ] + + header_args = { + 'includes': '\n'.join(['#import ' + header for header in headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.GenericHeaderPrelude).substitute(None, **header_args)) + sections.append(self._generate_configuration_interface_for_domains(domains)) + sections.append(Template(ObjCTemplates.GenericHeaderPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_configuration_interface_for_domains(self, domains): + lines = [] + lines.append('__attribute__((visibility ("default")))') + lines.append('@interface %sConfiguration : NSObject' % self.protocol_name()) + for domain in domains: + lines.extend(self._generate_properties_for_domain(domain)) + lines.append('@end') + return '\n'.join(lines) + + def _generate_properties_for_domain(self, domain): + property_args = { + 'objcPrefix': self.objc_prefix(), + 'domainName': domain.domain_name, + 'variableNamePrefix': ObjCGenerator.variable_name_prefix_for_domain(domain), + } + + lines = [] + + if self.should_generate_commands_for_domain(domain): + lines.append(Template(ObjCTemplates.ConfigurationCommandProperty).substitute(None, **property_args)) + if self.should_generate_events_for_domain(domain): + lines.append(Template(ObjCTemplates.ConfigurationEventProperty).substitute(None, **property_args)) + return lines diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_configuration_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_configuration_implementation.py new file mode 100755 index 000000000..910bcbab1 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_configuration_implementation.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +class ObjCConfigurationImplementationGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sConfiguration.mm' % self.protocol_name() + + def generate_output(self): + secondary_headers = [ + '"%sInternal.h"' % self.protocol_name(), + '"%sBackendDispatchers.h"' % self.protocol_name(), + '<JavaScriptCore/AlternateDispatchableAgent.h>', + '<JavaScriptCore/AugmentableInspectorController.h>', + '<JavaScriptCore/InspectorAlternateBackendDispatchers.h>', + '<JavaScriptCore/InspectorBackendDispatchers.h>', + ] + + header_args = { + 'primaryInclude': '"%sConfiguration.h"' % self.protocol_name(), + 'secondaryIncludes': '\n'.join(['#import %s' % header for header in secondary_headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.ImplementationPrelude).substitute(None, **header_args)) + sections.append(self._generate_configuration_implementation_for_domains(domains)) + sections.append(Template(ObjCTemplates.ImplementationPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_configuration_implementation_for_domains(self, domains): + lines = [] + lines.append('@implementation %sConfiguration' % self.protocol_name()) + lines.append('{') + lines.append(' AugmentableInspectorController* _controller;') + lines.extend(self._generate_ivars(domains)) + lines.append('}') + lines.append('') + lines.append('- (instancetype)initWithController:(AugmentableInspectorController*)controller') + lines.append('{') + lines.append(' self = [super init];') + lines.append(' if (!self)') + lines.append(' return nil;') + lines.append(' ASSERT(controller);') + lines.append(' _controller = controller;') + lines.append(' return self;') + lines.append('}') + lines.append('') + lines.extend(self._generate_dealloc(domains)) + lines.append('') + for domain in domains: + if self.should_generate_commands_for_domain(domain): + lines.append(self._generate_handler_setter_for_domain(domain)) + lines.append('') + if self.should_generate_events_for_domain(domain): + lines.append(self._generate_event_dispatcher_getter_for_domain(domain)) + lines.append('') + lines.append('@end') + return '\n'.join(lines) + + def _generate_ivars(self, domains): + lines = [] + for domain in domains: + if self.should_generate_commands_for_domain(domain): + objc_class_name = '%s%sDomainHandler' % (self.objc_prefix(), domain.domain_name) + ivar_name = '_%sHandler' % ObjCGenerator.variable_name_prefix_for_domain(domain) + lines.append(' id<%s> %s;' % (objc_class_name, ivar_name)) + if self.should_generate_events_for_domain(domain): + objc_class_name = '%s%sDomainEventDispatcher' % (self.objc_prefix(), domain.domain_name) + ivar_name = '_%sEventDispatcher' % ObjCGenerator.variable_name_prefix_for_domain(domain) + lines.append(' %s *%s;' % (objc_class_name, ivar_name)) + return lines + + def _generate_dealloc(self, domains): + lines = [] + lines.append('- (void)dealloc') + lines.append('{') + for domain in domains: + if self.should_generate_commands_for_domain(domain): + lines.append(' [_%sHandler release];' % ObjCGenerator.variable_name_prefix_for_domain(domain)) + if self.should_generate_events_for_domain(domain): + lines.append(' [_%sEventDispatcher release];' % ObjCGenerator.variable_name_prefix_for_domain(domain)) + lines.append(' [super dealloc];') + lines.append('}') + return lines + + def _generate_handler_setter_for_domain(self, domain): + setter_args = { + 'objcPrefix': self.objc_prefix(), + 'domainName': domain.domain_name, + 'variableNamePrefix': ObjCGenerator.variable_name_prefix_for_domain(domain), + } + return Template(ObjCTemplates.ConfigurationCommandPropertyImplementation).substitute(None, **setter_args) + + def _generate_event_dispatcher_getter_for_domain(self, domain): + getter_args = { + 'objcPrefix': self.objc_prefix(), + 'domainName': domain.domain_name, + 'variableNamePrefix': ObjCGenerator.variable_name_prefix_for_domain(domain), + } + return Template(ObjCTemplates.ConfigurationGetterImplementation).substitute(None, **getter_args) + + def _variable_name_prefix_for_domain(self, domain): + domain_name = domain.domain_name + if domain_name.startswith('DOM'): + return 'dom' + domain_name[3:] + if domain_name.startswith('CSS'): + return 'css' + domain_name[3:] + return domain_name[:1].lower() + domain_name[1:] diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_frontend_dispatcher_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_frontend_dispatcher_implementation.py new file mode 100755 index 000000000..722d5d392 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_frontend_dispatcher_implementation.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014-2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from cpp_generator import CppGenerator +from generator import Generator, ucfirst +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +class ObjCFrontendDispatcherImplementationGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sEventDispatchers.mm' % self.protocol_name() + + def domains_to_generate(self): + return filter(self.should_generate_events_for_domain, Generator.domains_to_generate(self)) + + def generate_output(self): + secondary_headers = [ + '"%sTypeConversions.h"' % self.protocol_name(), + '<JavaScriptCore/InspectorValues.h>', + ] + + header_args = { + 'primaryInclude': '"%sInternal.h"' % self.protocol_name(), + 'secondaryIncludes': '\n'.join(['#import %s' % header for header in secondary_headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.ImplementationPrelude).substitute(None, **header_args)) + sections.extend(map(self._generate_event_dispatcher_implementations, domains)) + sections.append(Template(ObjCTemplates.ImplementationPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_event_dispatcher_implementations(self, domain): + if not self.should_generate_events_for_domain(domain): + return '' + + lines = [] + objc_name = '%s%sDomainEventDispatcher' % (self.objc_prefix(), domain.domain_name) + lines.append('@implementation %s' % objc_name) + lines.append('{') + lines.append(' AugmentableInspectorController* _controller;') + lines.append('}') + lines.append('') + lines.append('- (instancetype)initWithController:(AugmentableInspectorController*)controller;') + lines.append('{') + lines.append(' self = [super init];') + lines.append(' if (!self)') + lines.append(' return nil;') + lines.append(' ASSERT(controller);') + lines.append(' _controller = controller;') + lines.append(' return self;') + lines.append('}') + lines.append('') + for event in self.events_for_domain(domain): + lines.append(self._generate_event(domain, event)) + lines.append('') + lines.append('@end') + return '\n'.join(lines) + + def _generate_event(self, domain, event): + lines = [] + lines.append(self._generate_event_signature(domain, event)) + lines.append('{') + lines.append(' const FrontendRouter& router = _controller->frontendRouter();') + lines.append('') + + required_pointer_parameters = filter(lambda parameter: not parameter.is_optional and ObjCGenerator.is_type_objc_pointer_type(parameter.type), event.event_parameters) + for parameter in required_pointer_parameters: + var_name = ObjCGenerator.identifier_to_objc_identifier(parameter.parameter_name) + lines.append(' THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(%s, @"%s");' % (var_name, var_name)) + objc_array_class = self.objc_class_for_array_type(parameter.type) + if objc_array_class and objc_array_class.startswith(self.objc_prefix()): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE_IN_ARRAY(%s, [%s class]);' % (var_name, objc_array_class)) + + optional_pointer_parameters = filter(lambda parameter: parameter.is_optional and ObjCGenerator.is_type_objc_pointer_type(parameter.type), event.event_parameters) + for parameter in optional_pointer_parameters: + var_name = ObjCGenerator.identifier_to_objc_identifier(parameter.parameter_name) + lines.append(' THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(%s, @"%s");' % (var_name, var_name)) + objc_array_class = self.objc_class_for_array_type(parameter.type) + if objc_array_class and objc_array_class.startswith(self.objc_prefix()): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE_IN_OPTIONAL_ARRAY(%s, [%s class]);' % (var_name, objc_array_class)) + + if required_pointer_parameters or optional_pointer_parameters: + lines.append('') + + lines.append(' Ref<InspectorObject> jsonMessage = InspectorObject::create();') + lines.append(' jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("%s.%s"));' % (domain.domain_name, event.event_name)) + if event.event_parameters: + lines.extend(self._generate_event_out_parameters(domain, event)) + lines.append(' router.sendEvent(jsonMessage->toJSONString());') + lines.append('}') + return '\n'.join(lines) + + def _generate_event_signature(self, domain, event): + if not event.event_parameters: + return '- (void)%s' % event.event_name + pairs = [] + for parameter in event.event_parameters: + param_name = parameter.parameter_name + pairs.append('%s:(%s)%s' % (param_name, self.objc_type_for_param(domain, event.event_name, parameter), param_name)) + pairs[0] = ucfirst(pairs[0]) + return '- (void)%sWith%s' % (event.event_name, ' '.join(pairs)) + + def _generate_event_out_parameters(self, domain, event): + lines = [] + lines.append(' Ref<InspectorObject> paramsObject = InspectorObject::create();') + for parameter in event.event_parameters: + keyed_set_method = CppGenerator.cpp_setter_method_for_type(parameter.type) + var_name = parameter.parameter_name + safe_var_name = '(*%s)' % var_name if parameter.is_optional else var_name + export_expression = self.objc_protocol_export_expression_for_variable(parameter.type, safe_var_name) + if not parameter.is_optional: + lines.append(' paramsObject->%s(ASCIILiteral("%s"), %s);' % (keyed_set_method, parameter.parameter_name, export_expression)) + else: + lines.append(' if (%s)' % (parameter.parameter_name)) + lines.append(' paramsObject->%s(ASCIILiteral("%s"), %s);' % (keyed_set_method, parameter.parameter_name, export_expression)) + lines.append(' jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject));') + return lines diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_header.py new file mode 100755 index 000000000..801f40a86 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_header.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator, ucfirst +from models import ObjectType, EnumType, Platforms +from objc_generator import ObjCGenerator, join_type_and_name +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +def add_newline(lines): + if lines and lines[-1] == '': + return + lines.append('') + + +class ObjCHeaderGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%s.h' % self.protocol_name() + + def generate_output(self): + headers = set([ + '<WebInspector/%sJSONObject.h>' % ObjCGenerator.OBJC_STATIC_PREFIX, + ]) + + header_args = { + 'includes': '\n'.join(['#import ' + header for header in sorted(headers)]), + } + + domains = self.domains_to_generate() + type_domains = filter(self.should_generate_types_for_domain, domains) + command_domains = filter(self.should_generate_commands_for_domain, domains) + event_domains = filter(self.should_generate_events_for_domain, domains) + + # FIXME: <https://webkit.org/b/138222> Web Inspector: Reduce unnecessary enums/types generated in ObjC Protocol Interfaces + # Currently we generate enums/types for all types in the type_domains. For the built-in + # JSC domains (Debugger, Runtime) this produces extra unused types. We only need to + # generate these types if they are referenced by the command_domains or event_domains. + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.HeaderPrelude).substitute(None, **header_args)) + sections.append('\n'.join(filter(None, map(self._generate_forward_declarations, type_domains)))) + sections.append(self._generate_enum_for_platforms()) + sections.append('\n'.join(filter(None, map(self._generate_enums, type_domains)))) + sections.append('\n'.join(filter(None, map(self._generate_types, type_domains)))) + + if self.get_generator_setting('generate_backend', False): + sections.append('\n\n'.join(filter(None, map(self._generate_command_protocols, command_domains)))) + sections.append('\n\n'.join(filter(None, map(self._generate_event_interfaces, event_domains)))) + + sections.append(Template(ObjCTemplates.HeaderPostlude).substitute(None)) + return '\n\n'.join(sections) + + def _generate_forward_declarations(self, domain): + lines = [] + for declaration in self.type_declarations_for_domain(domain): + if (isinstance(declaration.type, ObjectType)): + objc_name = self.objc_name_for_type(declaration.type) + lines.append('@class %s;' % objc_name) + return '\n'.join(lines) + + def _generate_enums(self, domain): + lines = [] + + # Type enums and member enums. + for declaration in self.type_declarations_for_domain(domain): + if isinstance(declaration.type, EnumType): + add_newline(lines) + lines.append(self._generate_anonymous_enum_for_declaration(domain, declaration)) + else: + for member in declaration.type_members: + if isinstance(member.type, EnumType) and member.type.is_anonymous: + add_newline(lines) + lines.append(self._generate_anonymous_enum_for_member(domain, declaration, member)) + + # Anonymous command enums. + for command in self.commands_for_domain(domain): + for parameter in command.call_parameters: + if isinstance(parameter.type, EnumType) and parameter.type.is_anonymous: + add_newline(lines) + lines.append(self._generate_anonymous_enum_for_parameter(domain, command.command_name, parameter)) + for parameter in command.return_parameters: + if isinstance(parameter.type, EnumType) and parameter.type.is_anonymous: + add_newline(lines) + lines.append(self._generate_anonymous_enum_for_parameter(domain, command.command_name, parameter)) + + # Anonymous event enums. + for event in self.events_for_domain(domain): + for parameter in event.event_parameters: + if isinstance(parameter.type, EnumType) and parameter.type.is_anonymous: + add_newline(lines) + lines.append(self._generate_anonymous_enum_for_parameter(domain, event.event_name, parameter)) + + return '\n'.join(lines) + + def _generate_types(self, domain): + lines = [] + # Type interfaces. + for declaration in self.type_declarations_for_domain(domain): + if isinstance(declaration.type, ObjectType): + add_newline(lines) + lines.append(self._generate_type_interface(domain, declaration)) + return '\n'.join(lines) + + def _generate_enum_for_platforms(self): + objc_enum_name = '%sPlatform' % self.objc_prefix() + enum_values = [platform.name for platform in Platforms] + return self._generate_enum(objc_enum_name, enum_values) + + def _generate_anonymous_enum_for_declaration(self, domain, declaration): + objc_enum_name = self.objc_enum_name_for_anonymous_enum_declaration(declaration) + return self._generate_enum(objc_enum_name, declaration.type.enum_values()) + + def _generate_anonymous_enum_for_member(self, domain, declaration, member): + objc_enum_name = self.objc_enum_name_for_anonymous_enum_member(declaration, member) + return self._generate_enum(objc_enum_name, member.type.enum_values()) + + def _generate_anonymous_enum_for_parameter(self, domain, event_or_command_name, parameter): + objc_enum_name = self.objc_enum_name_for_anonymous_enum_parameter(domain, event_or_command_name, parameter) + return self._generate_enum(objc_enum_name, parameter.type.enum_values()) + + def _generate_enum(self, enum_name, enum_values): + lines = [] + lines.append('typedef NS_ENUM(NSInteger, %s) {' % enum_name) + for enum_value in enum_values: + lines.append(' %s%s,' % (enum_name, Generator.stylized_name_for_enum_value(enum_value))) + lines.append('};') + return '\n'.join(lines) + + def _generate_type_interface(self, domain, declaration): + lines = [] + objc_name = self.objc_name_for_type(declaration.type) + lines.append('__attribute__((visibility ("default")))') + lines.append('@interface %s : %sJSONObject' % (objc_name, ObjCGenerator.OBJC_STATIC_PREFIX)) + + # The initializers that take a payload or inspector object are only needed by the frontend. + if self.get_generator_setting('generate_frontend', False): + lines.append('- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload;') + lines.append('- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject;') + + required_members = filter(lambda member: not member.is_optional, declaration.type_members) + optional_members = filter(lambda member: member.is_optional, declaration.type_members) + if required_members: + lines.append(self._generate_init_method_for_required_members(domain, declaration, required_members)) + for member in required_members: + lines.append('/* required */ ' + self._generate_member_property(declaration, member)) + for member in optional_members: + lines.append('/* optional */ ' + self._generate_member_property(declaration, member)) + lines.append('@end') + return '\n'.join(lines) + + def _generate_init_method_for_required_members(self, domain, declaration, required_members): + pairs = [] + for member in required_members: + objc_type = self.objc_type_for_member(declaration, member) + var_name = ObjCGenerator.identifier_to_objc_identifier(member.member_name) + pairs.append('%s:(%s)%s' % (var_name, objc_type, var_name)) + pairs[0] = ucfirst(pairs[0]) + return '- (instancetype)initWith%s;' % ' '.join(pairs) + + def _generate_member_property(self, declaration, member): + accessor_type = self.objc_accessor_type_for_member(member) + objc_type = self.objc_type_for_member(declaration, member) + return '@property (nonatomic, %s) %s;' % (accessor_type, join_type_and_name(objc_type, ObjCGenerator.identifier_to_objc_identifier(member.member_name))) + + def _generate_command_protocols(self, domain): + lines = [] + if self.commands_for_domain(domain): + objc_name = '%s%sDomainHandler' % (self.objc_prefix(), domain.domain_name) + lines.append('@protocol %s <NSObject>' % objc_name) + lines.append('@required') + for command in self.commands_for_domain(domain): + lines.append(self._generate_single_command_protocol(domain, command)) + lines.append('@end') + return '\n'.join(lines) + + def _generate_single_command_protocol(self, domain, command): + pairs = [] + pairs.append('ErrorCallback:(void(^)(NSString *error))errorCallback') + pairs.append('successCallback:(%s)successCallback' % self._callback_block_for_command(domain, command)) + for parameter in command.call_parameters: + param_name = parameter.parameter_name + pairs.append('%s:(%s)%s' % (param_name, self.objc_type_for_param(domain, command.command_name, parameter), param_name)) + return '- (void)%sWith%s;' % (command.command_name, ' '.join(pairs)) + + def _callback_block_for_command(self, domain, command): + pairs = [] + for parameter in command.return_parameters: + pairs.append(join_type_and_name(self.objc_type_for_param(domain, command.command_name, parameter), parameter.parameter_name)) + return 'void(^)(%s)' % ', '.join(pairs) + + def _generate_event_interfaces(self, domain): + lines = [] + events = self.events_for_domain(domain) + if len(events): + objc_name = '%s%sDomainEventDispatcher' % (self.objc_prefix(), domain.domain_name) + lines.append('__attribute__((visibility ("default")))') + lines.append('@interface %s : NSObject' % objc_name) + for event in events: + lines.append(self._generate_single_event_interface(domain, event)) + lines.append('@end') + return '\n'.join(lines) + + def _generate_single_event_interface(self, domain, event): + if not event.event_parameters: + return '- (void)%s;' % event.event_name + pairs = [] + for parameter in event.event_parameters: + param_name = parameter.parameter_name + pairs.append('%s:(%s)%s' % (param_name, self.objc_type_for_param(domain, event.event_name, parameter), param_name)) + pairs[0] = ucfirst(pairs[0]) + return '- (void)%sWith%s;' % (event.event_name, ' '.join(pairs)) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_internal_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_internal_header.py new file mode 100755 index 000000000..9f06ced40 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_internal_header.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator, ucfirst +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +class ObjCInternalHeaderGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sInternal.h' % self.protocol_name() + + def generate_output(self): + headers = set([ + '"%s.h"' % self.protocol_name(), + '"%sJSONObjectPrivate.h"' % self.protocol_name(), + '<JavaScriptCore/InspectorValues.h>', + '<JavaScriptCore/AugmentableInspectorController.h>', + ]) + + header_args = { + 'includes': '\n'.join(['#import ' + header for header in sorted(headers)]), + } + + event_domains = filter(self.should_generate_events_for_domain, self.domains_to_generate()) + + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.GenericHeaderPrelude).substitute(None, **header_args)) + sections.append('\n\n'.join(filter(None, map(self._generate_event_dispatcher_private_interfaces, event_domains)))) + sections.append(Template(ObjCTemplates.GenericHeaderPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_event_dispatcher_private_interfaces(self, domain): + lines = [] + if len(self.events_for_domain(domain)): + objc_name = '%s%sDomainEventDispatcher' % (self.objc_prefix(), domain.domain_name) + lines.append('@interface %s (Private)' % objc_name) + lines.append('- (instancetype)initWithController:(Inspector::AugmentableInspectorController*)controller;') + lines.append('@end') + return '\n'.join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_type_conversions_header.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_type_conversions_header.py new file mode 100755 index 000000000..ea9e6e2d7 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_type_conversions_header.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator +from models import EnumType, Frameworks, Platforms +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +def add_newline(lines): + if lines and lines[-1] == '': + return + lines.append('') + + +class ObjCProtocolTypeConversionsHeaderGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sTypeConversions.h' % self.protocol_name() + + def domains_to_generate(self): + return filter(self.should_generate_types_for_domain, Generator.domains_to_generate(self)) + + def generate_output(self): + headers = [ + '"%s.h"' % self.protocol_name(), + Generator.string_for_file_include('%sArrayConversions.h' % ObjCGenerator.OBJC_STATIC_PREFIX, Frameworks.WebInspector, self.model().framework), + ] + headers.sort() + + header_args = { + 'includes': '\n'.join(['#import ' + header for header in headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.TypeConversionsHeaderPrelude).substitute(None, **header_args)) + sections.append(Template(ObjCTemplates.TypeConversionsHeaderStandard).substitute(None)) + sections.append(self._generate_enum_conversion_for_platforms()) + sections.extend(map(self._generate_enum_conversion_functions, domains)) + sections.append(Template(ObjCTemplates.TypeConversionsHeaderPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_enum_conversion_functions(self, domain): + lines = [] + + # Type enums and member enums. + for declaration in self.type_declarations_for_domain(domain): + if isinstance(declaration.type, EnumType): + add_newline(lines) + lines.append(self._generate_anonymous_enum_conversion_for_declaration(domain, declaration)) + else: + for member in declaration.type_members: + if (isinstance(member.type, EnumType) and member.type.is_anonymous): + add_newline(lines) + lines.append(self._generate_anonymous_enum_conversion_for_member(domain, declaration, member)) + + # Anonymous command enums. + for command in self.commands_for_domain(domain): + for parameter in command.call_parameters: + if (isinstance(parameter.type, EnumType) and parameter.type.is_anonymous): + add_newline(lines) + lines.append(self._generate_anonymous_enum_conversion_for_parameter(domain, command.command_name, parameter)) + for parameter in command.return_parameters: + if (isinstance(parameter.type, EnumType) and parameter.type.is_anonymous): + add_newline(lines) + lines.append(self._generate_anonymous_enum_conversion_for_parameter(domain, command.command_name, parameter)) + + # Anonymous event enums. + for event in self.events_for_domain(domain): + for parameter in event.event_parameters: + if (isinstance(parameter.type, EnumType) and parameter.type.is_anonymous): + add_newline(lines) + lines.append(self._generate_anonymous_enum_conversion_for_parameter(domain, event.event_name, parameter)) + + return '\n'.join(lines) + + def _generate_enum_conversion_for_platforms(self): + objc_enum_name = '%sPlatform' % self.objc_prefix() + enum_values = [platform.name for platform in Platforms] + lines = [] + lines.append(self._generate_enum_objc_to_protocol_string(objc_enum_name, enum_values)) + lines.append(self._generate_enum_from_protocol_string(objc_enum_name, enum_values)) + return '\n\n'.join(lines) + + def _generate_anonymous_enum_conversion_for_declaration(self, domain, declaration): + objc_enum_name = self.objc_enum_name_for_anonymous_enum_declaration(declaration) + enum_values = declaration.type.enum_values() + lines = [] + lines.append(self._generate_enum_objc_to_protocol_string(objc_enum_name, enum_values)) + lines.append(self._generate_enum_from_protocol_string(objc_enum_name, enum_values)) + return '\n\n'.join(lines) + + def _generate_anonymous_enum_conversion_for_member(self, domain, declaration, member): + objc_enum_name = self.objc_enum_name_for_anonymous_enum_member(declaration, member) + enum_values = member.type.enum_values() + lines = [] + lines.append(self._generate_enum_objc_to_protocol_string(objc_enum_name, enum_values)) + lines.append(self._generate_enum_from_protocol_string(objc_enum_name, enum_values)) + return '\n\n'.join(lines) + + def _generate_anonymous_enum_conversion_for_parameter(self, domain, event_or_command_name, parameter): + objc_enum_name = self.objc_enum_name_for_anonymous_enum_parameter(domain, event_or_command_name, parameter) + enum_values = parameter.type.enum_values() + lines = [] + lines.append(self._generate_enum_objc_to_protocol_string(objc_enum_name, enum_values)) + lines.append(self._generate_enum_from_protocol_string(objc_enum_name, enum_values)) + return '\n\n'.join(lines) + + def _generate_enum_objc_to_protocol_string(self, objc_enum_name, enum_values): + lines = [] + lines.append('inline String toProtocolString(%s value)' % objc_enum_name) + lines.append('{') + lines.append(' switch(value) {') + for enum_value in enum_values: + lines.append(' case %s%s:' % (objc_enum_name, Generator.stylized_name_for_enum_value(enum_value))) + lines.append(' return ASCIILiteral("%s");' % enum_value) + lines.append(' }') + lines.append('}') + return '\n'.join(lines) + + def _generate_enum_from_protocol_string(self, objc_enum_name, enum_values): + lines = [] + lines.append('template<>') + lines.append('inline std::optional<%s> fromProtocolString(const String& value)' % objc_enum_name) + lines.append('{') + for enum_value in enum_values: + lines.append(' if (value == "%s")' % enum_value) + lines.append(' return %s%s;' % (objc_enum_name, Generator.stylized_name_for_enum_value(enum_value))) + lines.append(' return std::nullopt;') + lines.append('}') + return '\n'.join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_type_conversions_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_type_conversions_implementation.py new file mode 100644 index 000000000..4293e3bd8 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_type_conversions_implementation.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python +# +# Copyright (c) 2016 Apple Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator +from models import EnumType, ObjectType, ArrayType, AliasedType, PrimitiveType, Frameworks +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +def add_newline(lines): + if lines and lines[-1] == '': + return + lines.append('') + + +class ObjCProtocolTypeConversionsImplementationGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sTypeConversions.mm' % self.protocol_name() + + def domains_to_generate(self): + return filter(self.should_generate_types_for_domain, Generator.domains_to_generate(self)) + + def generate_output(self): + secondary_headers = [ + '"%s.h"' % self.protocol_name(), + '"%sTypeParser.h"' % self.protocol_name(), + Generator.string_for_file_include('%sJSONObjectPrivate.h' % ObjCGenerator.OBJC_STATIC_PREFIX, Frameworks.WebInspector, self.model().framework), + ] + secondary_headers.sort() + + header_args = { + 'primaryInclude': '"%sTypeConversions.h"' % self.protocol_name(), + 'secondaryIncludes': '\n'.join(['#import ' + header for header in secondary_headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.ImplementationPrelude).substitute(None, **header_args)) + sections.append(self._generate_type_factory_category_interface(domains)) + sections.append(self._generate_type_factory_category_implementation(domains)) + sections.append(Template(ObjCTemplates.ImplementationPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def _generate_type_factory_category_interface(self, domains): + lines = [] + for domain in domains: + lines.append('@interface %sTypeConversions (%sDomain)' % (self.protocol_name(), domain.domain_name)) + lines.append('') + + for declaration in self.type_declarations_for_domain(domain): + lines.append(self._generate_type_factory_method_declaration(domain, declaration)) + + add_newline(lines) + lines.append('@end') + + return '\n'.join(lines) + + def _generate_type_factory_method_declaration(self, domain, declaration): + resolved_type = declaration.type + if isinstance(resolved_type, AliasedType): + resolved_type = resolved_type.aliased_type + if isinstance(resolved_type, (ObjectType, ArrayType, PrimitiveType)): + objc_type = self.objc_class_for_type(resolved_type) + return '+ (void)_parse%s:(%s **)outValue fromPayload:(id)payload;' % (declaration.type.raw_name(), objc_type) + if isinstance(resolved_type, EnumType): + return '+ (void)_parse%s:(NSNumber **)outValue fromPayload:(id)payload;' % declaration.type.raw_name() + + def _generate_type_factory_category_implementation(self, domains): + lines = [] + for domain in domains: + lines.append('@implementation %sTypeConversions (%sDomain)' % (self.protocol_name(), domain.domain_name)) + lines.append('') + + for declaration in self.type_declarations_for_domain(domain): + lines.append(self._generate_type_factory_method_implementation(domain, declaration)) + add_newline(lines) + lines.append('@end') + return '\n'.join(lines) + + def _generate_type_factory_method_implementation(self, domain, declaration): + lines = [] + resolved_type = declaration.type + if isinstance(resolved_type, AliasedType): + resolved_type = resolved_type.aliased_type + + objc_class = self.objc_class_for_type(resolved_type) + if isinstance(resolved_type, (ObjectType, ArrayType, PrimitiveType)): + lines.append('+ (void)_parse%s:(%s **)outValue fromPayload:(id)payload' % (declaration.type.raw_name(), objc_class)) + if isinstance(resolved_type, EnumType): + lines.append('+ (void)_parse%s:(NSNumber **)outValue fromPayload:(id)payload' % declaration.type.raw_name()) + + lines.append('{') + if isinstance(resolved_type, EnumType): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]);') + lines.append(' std::optional<%(type)s> result = Inspector::fromProtocolString<%(type)s>(payload);' % {'type': self.objc_name_for_type(resolved_type)}) + lines.append(' THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"%s");' % declaration.type.raw_name()) + lines.append(' *outValue = @(result.value());') + elif isinstance(resolved_type, (ArrayType, PrimitiveType)): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE(payload, [%s class]);' % objc_class) + lines.append(' *outValue = (%s *)payload;' % objc_class) + elif isinstance(resolved_type, ObjectType): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]);') + lines.append(' *outValue = [[%s alloc] initWithPayload:payload];' % (objc_class)) + lines.append('}') + return '\n'.join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_types_implementation.py b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_types_implementation.py new file mode 100755 index 000000000..a319c94d7 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generate_objc_protocol_types_implementation.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + + +import logging +import string +from string import Template + +from generator import Generator, ucfirst +from models import ObjectType, EnumType, Frameworks +from objc_generator import ObjCGenerator +from objc_generator_templates import ObjCGeneratorTemplates as ObjCTemplates + +log = logging.getLogger('global') + + +def add_newline(lines): + if lines and lines[-1] == '': + return + lines.append('') + + +class ObjCProtocolTypesImplementationGenerator(ObjCGenerator): + def __init__(self, *args, **kwargs): + ObjCGenerator.__init__(self, *args, **kwargs) + + def output_filename(self): + return '%sTypes.mm' % self.protocol_name() + + def domains_to_generate(self): + return filter(self.should_generate_types_for_domain, Generator.domains_to_generate(self)) + + def generate_output(self): + secondary_headers = [ + '"%sTypeConversions.h"' % self.protocol_name(), + Generator.string_for_file_include('%sJSONObjectPrivate.h' % ObjCGenerator.OBJC_STATIC_PREFIX, Frameworks.WebInspector, self.model().framework), + '<JavaScriptCore/InspectorValues.h>', + '<wtf/Assertions.h>', + ] + + # The FooProtocolInternal.h header is only needed to declare the backend-side event dispatcher bindings. + primaryIncludeName = self.protocol_name() + if self.get_generator_setting('generate_backend', False): + primaryIncludeName += 'Internal' + + header_args = { + 'primaryInclude': '"%s.h"' % primaryIncludeName, + 'secondaryIncludes': '\n'.join(['#import %s' % header for header in secondary_headers]), + } + + domains = self.domains_to_generate() + sections = [] + sections.append(self.generate_license()) + sections.append(Template(ObjCTemplates.ImplementationPrelude).substitute(None, **header_args)) + sections.extend(map(self.generate_type_implementations, domains)) + sections.append(Template(ObjCTemplates.ImplementationPostlude).substitute(None, **header_args)) + return '\n\n'.join(sections) + + def generate_type_implementations(self, domain): + lines = [] + for declaration in self.type_declarations_for_domain(domain): + if (isinstance(declaration.type, ObjectType)): + add_newline(lines) + lines.append(self.generate_type_implementation(domain, declaration)) + return '\n'.join(lines) + + def generate_type_implementation(self, domain, declaration): + lines = [] + lines.append('@implementation %s' % self.objc_name_for_type(declaration.type)) + # The initializer that takes a payload is only needed by the frontend. + if self.get_generator_setting('generate_frontend', False): + lines.append('') + lines.append(self._generate_init_method_for_payload(domain, declaration)) + lines.append(self._generate_init_method_for_json_object(domain, declaration)) + required_members = filter(lambda member: not member.is_optional, declaration.type_members) + if required_members: + lines.append('') + lines.append(self._generate_init_method_for_required_members(domain, declaration, required_members)) + for member in declaration.type_members: + lines.append('') + lines.append(self._generate_setter_for_member(domain, declaration, member)) + lines.append('') + lines.append(self._generate_getter_for_member(domain, declaration, member)) + lines.append('') + lines.append('@end') + return '\n'.join(lines) + + def _generate_init_method_for_json_object(self, domain, declaration): + lines = [] + lines.append('- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject') + lines.append('{') + lines.append(' if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()]))') + lines.append(' return nil;') + lines.append('') + lines.append(' return self;') + lines.append('}') + return '\n'.join(lines) + + def _generate_init_method_for_payload(self, domain, declaration): + lines = [] + lines.append('- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload') + lines.append('{') + lines.append(' if (!(self = [super init]))') + lines.append(' return nil;') + lines.append('') + + for member in declaration.type_members: + member_name = member.member_name + + if not member.is_optional: + lines.append(' THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"%s"], @"%s");' % (member_name, member_name)) + + objc_type = self.objc_type_for_member(declaration, member) + var_name = ObjCGenerator.identifier_to_objc_identifier(member_name) + conversion_expression = self.payload_to_objc_expression_for_member(declaration, member) + if isinstance(member.type, EnumType): + lines.append(' std::optional<%s> %s = %s;' % (objc_type, var_name, conversion_expression)) + if not member.is_optional: + lines.append(' THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(%s, @"%s");' % (var_name, member_name)) + lines.append(' self.%s = %s.value();' % (var_name, var_name)) + else: + lines.append(' if (%s)' % var_name) + lines.append(' self.%s = %s.value();' % (var_name, var_name)) + else: + lines.append(' self.%s = %s;' % (var_name, conversion_expression)) + + lines.append('') + + lines.append(' return self;') + lines.append('}') + return '\n'.join(lines) + + def _generate_init_method_for_required_members(self, domain, declaration, required_members): + pairs = [] + for member in required_members: + objc_type = self.objc_type_for_member(declaration, member) + var_name = ObjCGenerator.identifier_to_objc_identifier(member.member_name) + pairs.append('%s:(%s)%s' % (var_name, objc_type, var_name)) + pairs[0] = ucfirst(pairs[0]) + lines = [] + lines.append('- (instancetype)initWith%s' % ' '.join(pairs)) + lines.append('{') + lines.append(' if (!(self = [super init]))') + lines.append(' return nil;') + lines.append('') + + required_pointer_members = filter(lambda member: ObjCGenerator.is_type_objc_pointer_type(member.type), required_members) + if required_pointer_members: + for member in required_pointer_members: + var_name = ObjCGenerator.identifier_to_objc_identifier(member.member_name) + lines.append(' THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(%s, @"%s");' % (var_name, var_name)) + objc_array_class = self.objc_class_for_array_type(member.type) + if objc_array_class and objc_array_class.startswith(self.objc_prefix()): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE_IN_ARRAY(%s, [%s class]);' % (var_name, objc_array_class)) + lines.append('') + + for member in required_members: + var_name = ObjCGenerator.identifier_to_objc_identifier(member.member_name) + lines.append(' self.%s = %s;' % (var_name, var_name)) + + lines.append('') + lines.append(' return self;') + lines.append('}') + return '\n'.join(lines) + + def _generate_setter_for_member(self, domain, declaration, member): + objc_type = self.objc_type_for_member(declaration, member) + var_name = ObjCGenerator.identifier_to_objc_identifier(member.member_name) + setter_method = ObjCGenerator.objc_setter_method_for_member(declaration, member) + conversion_expression = self.objc_to_protocol_expression_for_member(declaration, member, var_name) + lines = [] + lines.append('- (void)set%s:(%s)%s' % (ucfirst(var_name), objc_type, var_name)) + lines.append('{') + objc_array_class = self.objc_class_for_array_type(member.type) + if objc_array_class and objc_array_class.startswith(self.objc_prefix()): + lines.append(' THROW_EXCEPTION_FOR_BAD_TYPE_IN_ARRAY(%s, [%s class]);' % (var_name, objc_array_class)) + lines.append(' [super %s:%s forKey:@"%s"];' % (setter_method, conversion_expression, member.member_name)) + lines.append('}') + return '\n'.join(lines) + + def _generate_getter_for_member(self, domain, declaration, member): + objc_type = self.objc_type_for_member(declaration, member) + var_name = ObjCGenerator.identifier_to_objc_identifier(member.member_name) + getter_method = ObjCGenerator.objc_getter_method_for_member(declaration, member) + basic_expression = '[super %s:@"%s"]' % (getter_method, member.member_name) + conversion_expression = self.protocol_to_objc_expression_for_member(declaration, member, basic_expression) + lines = [] + lines.append('- (%s)%s' % (objc_type, var_name)) + lines.append('{') + lines.append(' return %s;' % conversion_expression) + lines.append('}') + return '\n'.join(lines) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generator.py b/Source/JavaScriptCore/inspector/scripts/codegen/generator.py new file mode 100755 index 000000000..2d33b94ea --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generator.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +import logging +import os.path +import re +from string import Template + +from generator_templates import GeneratorTemplates as Templates +from models import PrimitiveType, ObjectType, ArrayType, EnumType, AliasedType, Frameworks, Platforms + +log = logging.getLogger('global') + + +def ucfirst(str): + return str[:1].upper() + str[1:] + +_ALWAYS_SPECIALCASED_ENUM_VALUE_SUBSTRINGS = set(['API', 'CSS', 'DOM', 'HTML', 'JIT', 'XHR', 'XML', 'IOS', 'MacOS']) +_ALWAYS_SPECIALCASED_ENUM_VALUE_LOOKUP_TABLE = dict([(s.upper(), s) for s in _ALWAYS_SPECIALCASED_ENUM_VALUE_SUBSTRINGS]) + +# These objects are built manually by creating and setting InspectorValues. +# Before sending these over the protocol, their shapes are checked against the specification. +# So, any types referenced by these types require debug-only assertions that check values. +# Calculating necessary assertions is annoying, and adds a lot of complexity to the generator. + +# FIXME: This should be converted into a property in JSON. +_TYPES_NEEDING_RUNTIME_CASTS = set([ + "Runtime.ObjectPreview", + "Runtime.RemoteObject", + "Runtime.PropertyDescriptor", + "Runtime.InternalPropertyDescriptor", + "Runtime.CollectionEntry", + "Debugger.FunctionDetails", + "Debugger.CallFrame", + "Canvas.TraceLog", + "Canvas.ResourceInfo", + "Canvas.ResourceState", + # This should be a temporary hack. TimelineEvent should be created via generated C++ API. + "Timeline.TimelineEvent", + # For testing purposes only. + "Test.TypeNeedingCast" +]) + +# FIXME: This should be converted into a property in JSON. +_TYPES_WITH_OPEN_FIELDS = set([ + "Timeline.TimelineEvent", + # InspectorStyleSheet not only creates this property but wants to read it and modify it. + "CSS.CSSProperty", + # InspectorNetworkAgent needs to update mime-type. + "Network.Response", + # For testing purposes only. + "Test.OpenParameterBundle" +]) + + +class Generator: + def __init__(self, model, platform, input_filepath): + self._model = model + self._platform = platform + self._input_filepath = input_filepath + self._settings = {} + + def model(self): + return self._model + + def platform(self): + return self._platform + + def set_generator_setting(self, key, value): + self._settings[key] = value + + def can_generate_platform(self, model_platform): + return model_platform is Platforms.Generic or self._platform is Platforms.All or model_platform is self._platform + + def type_declarations_for_domain(self, domain): + return [type_declaration for type_declaration in domain.all_type_declarations() if self.can_generate_platform(type_declaration.platform)] + + def commands_for_domain(self, domain): + return [command for command in domain.all_commands() if self.can_generate_platform(command.platform)] + + def events_for_domain(self, domain): + return [event for event in domain.all_events() if self.can_generate_platform(event.platform)] + + # The goofy name is to disambiguate generator settings from framework settings. + def get_generator_setting(self, key, default=None): + return self._settings.get(key, default) + + def generate_license(self): + return Template(Templates.CopyrightBlock).substitute(None, inputFilename=os.path.basename(self._input_filepath)) + + # These methods are overridden by subclasses. + def non_supplemental_domains(self): + return filter(lambda domain: not domain.is_supplemental, self.model().domains) + + def domains_to_generate(self): + return self.non_supplemental_domains() + + def generate_output(self): + pass + + def output_filename(self): + pass + + def encoding_for_enum_value(self, enum_value): + if not hasattr(self, "_assigned_enum_values"): + self._traverse_and_assign_enum_values() + + return self._enum_value_encodings[enum_value] + + def assigned_enum_values(self): + if not hasattr(self, "_assigned_enum_values"): + self._traverse_and_assign_enum_values() + + return self._assigned_enum_values[:] # Slice. + + @staticmethod + def type_needs_runtime_casts(_type): + return _type.qualified_name() in _TYPES_NEEDING_RUNTIME_CASTS + + @staticmethod + def type_has_open_fields(_type): + return _type.qualified_name() in _TYPES_WITH_OPEN_FIELDS + + def type_needs_shape_assertions(self, _type): + if not hasattr(self, "_types_needing_shape_assertions"): + self.calculate_types_requiring_shape_assertions(self.model().domains) + + return _type in self._types_needing_shape_assertions + + # To restrict the domains over which we compute types needing assertions, call this method + # before generating any output with the desired domains parameter. The computed + # set of types will not be automatically regenerated on subsequent calls to + # Generator.types_needing_shape_assertions(). + def calculate_types_requiring_shape_assertions(self, domains): + domain_names = map(lambda domain: domain.domain_name, domains) + log.debug("> Calculating types that need shape assertions (eligible domains: %s)" % ", ".join(domain_names)) + + # Mutates the passed-in set; this simplifies checks to prevent infinite recursion. + def gather_transitively_referenced_types(_type, gathered_types): + if _type in gathered_types: + return + + if isinstance(_type, ObjectType): + log.debug("> Adding type %s to list of types needing shape assertions." % _type.qualified_name()) + gathered_types.add(_type) + for type_member in _type.members: + gather_transitively_referenced_types(type_member.type, gathered_types) + elif isinstance(_type, EnumType): + log.debug("> Adding type %s to list of types needing shape assertions." % _type.qualified_name()) + gathered_types.add(_type) + elif isinstance(_type, AliasedType): + gather_transitively_referenced_types(_type.aliased_type, gathered_types) + elif isinstance(_type, ArrayType): + gather_transitively_referenced_types(_type.element_type, gathered_types) + + found_types = set() + for domain in domains: + for declaration in self.type_declarations_for_domain(domain): + if declaration.type.qualified_name() in _TYPES_NEEDING_RUNTIME_CASTS: + log.debug("> Gathering types referenced by %s to generate shape assertions." % declaration.type.qualified_name()) + gather_transitively_referenced_types(declaration.type, found_types) + + self._types_needing_shape_assertions = found_types + + # Private helper instance methods. + def _traverse_and_assign_enum_values(self): + self._enum_value_encodings = {} + self._assigned_enum_values = [] + all_types = [] + + domains = self.non_supplemental_domains() + + for domain in domains: + for type_declaration in self.type_declarations_for_domain(domain): + all_types.append(type_declaration.type) + for type_member in type_declaration.type_members: + all_types.append(type_member.type) + + for domain in domains: + for event in self.events_for_domain(domain): + all_types.extend([parameter.type for parameter in event.event_parameters]) + + for domain in domains: + for command in self.commands_for_domain(domain): + all_types.extend([parameter.type for parameter in command.call_parameters]) + all_types.extend([parameter.type for parameter in command.return_parameters]) + + for _type in all_types: + if not isinstance(_type, EnumType): + continue + map(self._assign_encoding_for_enum_value, _type.enum_values()) + + def _assign_encoding_for_enum_value(self, enum_value): + if enum_value in self._enum_value_encodings: + return + + self._enum_value_encodings[enum_value] = len(self._assigned_enum_values) + self._assigned_enum_values.append(enum_value) + + # Miscellaneous text manipulation routines. + def wrap_with_guard_for_domain(self, domain, text): + if self.model().framework is Frameworks.WebInspector: + return text + guard = domain.feature_guard + if guard: + return Generator.wrap_with_guard(guard, text) + return text + + @staticmethod + def wrap_with_guard(guard, text): + return '\n'.join([ + '#if %s' % guard, + text, + '#endif // %s' % guard, + ]) + + @staticmethod + def stylized_name_for_enum_value(enum_value): + regex = '(%s)' % "|".join(_ALWAYS_SPECIALCASED_ENUM_VALUE_SUBSTRINGS) + + def replaceCallback(match): + return _ALWAYS_SPECIALCASED_ENUM_VALUE_LOOKUP_TABLE[match.group(1).upper()] + + # Split on hyphen, introduce camelcase, and force uppercasing of acronyms. + subwords = map(ucfirst, enum_value.split('-')) + return re.sub(re.compile(regex, re.IGNORECASE), replaceCallback, "".join(subwords)) + + @staticmethod + def js_name_for_parameter_type(_type): + _type = _type + if isinstance(_type, AliasedType): + _type = _type.aliased_type # Fall through. + if isinstance(_type, EnumType): + _type = _type.primitive_type # Fall through. + + if isinstance(_type, (ArrayType, ObjectType)): + return 'object' + if isinstance(_type, PrimitiveType): + if _type.qualified_name() in ['object', 'any']: + return 'object' + elif _type.qualified_name() in ['integer', 'number']: + return 'number' + else: + return _type.qualified_name() + + @staticmethod + def string_for_file_include(filename, file_framework, target_framework): + if file_framework is target_framework: + return '"%s"' % filename + else: + return '<%s/%s>' % (file_framework.name, filename) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/generator_templates.py b/Source/JavaScriptCore/inspector/scripts/codegen/generator_templates.py new file mode 100644 index 000000000..891681ffd --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/generator_templates.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +# Generator templates, which can be filled with string.Template. +# Following are classes that fill the templates from the typechecked model. + + +class GeneratorTemplates: + CopyrightBlock = ( + """/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from ${inputFilename} +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py""") diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/models.py b/Source/JavaScriptCore/inspector/scripts/codegen/models.py new file mode 100755 index 000000000..b286a5c40 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/models.py @@ -0,0 +1,680 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +import logging +import collections + +log = logging.getLogger('global') + + +def ucfirst(str): + return str[:1].upper() + str[1:] + + +def find_duplicates(l): + return [key for key, count in collections.Counter(l).items() if count > 1] + + +_FRAMEWORK_CONFIG_MAP = { + "Global": { + }, + "JavaScriptCore": { + "cpp_protocol_group": "Inspector", + "export_macro": "JS_EXPORT_PRIVATE", + "alternate_dispatchers": True, + }, + "WebKit": { + "cpp_protocol_group": "Automation", + "objc_protocol_group": "WD", + "objc_prefix": "WD", + }, + "WebInspector": { + "objc_protocol_group": "RWI", + "objc_prefix": "RWI", + }, + # Used for code generator tests. + "Test": { + "alternate_dispatchers": True, + "cpp_protocol_group": "Test", + "objc_protocol_group": "Test", + "objc_prefix": "Test", + } +} + + +class ParseException(Exception): + pass + + +class TypecheckException(Exception): + pass + + +class Framework: + def __init__(self, name): + self._settings = _FRAMEWORK_CONFIG_MAP[name] + self.name = name + + def setting(self, key, default=''): + return self._settings.get(key, default) + + @staticmethod + def fromString(frameworkString): + if frameworkString == "Global": + return Frameworks.Global + + if frameworkString == "JavaScriptCore": + return Frameworks.JavaScriptCore + + if frameworkString == "WebKit": + return Frameworks.WebKit + + if frameworkString == "WebInspector": + return Frameworks.WebInspector + + if frameworkString == "Test": + return Frameworks.Test + + raise ParseException("Unknown framework: %s" % frameworkString) + + +class Frameworks: + Global = Framework("Global") + JavaScriptCore = Framework("JavaScriptCore") + WebKit = Framework("WebKit") + WebInspector = Framework("WebInspector") + Test = Framework("Test") + + +class Platform: + def __init__(self, name): + self.name = name + + @staticmethod + def fromString(platformString): + platformString = platformString.lower() + if platformString == "ios": + return Platforms.iOS + + if platformString == "macos": + return Platforms.macOS + + if platformString == "all": + return Platforms.All + + if platformString == "generic" or not platformString: + return Platforms.Generic + + raise ParseException("Unknown platform: %s" % platformString) + + +class Platforms: + All = Platform("all") + Generic = Platform("generic") + iOS = Platform("ios") + macOS = Platform("macos") + + # Allow iteration over all platforms. See <http://stackoverflow.com/questions/5434400/>. + class __metaclass__(type): + def __iter__(self): + for attr in dir(Platforms): + if not attr.startswith("__"): + yield getattr(Platforms, attr) + +class TypeReference: + def __init__(self, type_kind, referenced_type_name, enum_values, array_items): + self.type_kind = type_kind + self.referenced_type_name = referenced_type_name + self.enum_values = enum_values + if array_items is None: + self.array_type_ref = None + else: + self.array_type_ref = TypeReference(array_items.get('type'), array_items.get('$ref'), array_items.get('enum'), array_items.get('items')) + + if type_kind is not None and referenced_type_name is not None: + raise ParseException("Type reference cannot have both 'type' and '$ref' keys.") + + all_primitive_types = ["integer", "number", "string", "boolean", "enum", "object", "array", "any"] + if type_kind is not None and type_kind not in all_primitive_types: + raise ParseException("Type reference '%s' is not a primitive type. Allowed values: %s" % (type_kind, ', '.join(all_primitive_types))) + + if type_kind == "array" and array_items is None: + raise ParseException("Type reference with type 'array' must have key 'items' to define array element type.") + + if enum_values is not None and len(enum_values) == 0: + raise ParseException("Type reference with enum values must have at least one enum value.") + + def referenced_name(self): + if self.referenced_type_name is not None: + return self.referenced_type_name + else: + return self.type_kind # one of all_primitive_types + + +class Type: + def __init__(self): + pass + + def __eq__(self, other): + return self.qualified_name() == other.qualified_name() + + def __hash__(self): + return self.qualified_name().__hash__() + + def raw_name(self): + return self._name + + # These methods should be overridden by subclasses. + def is_enum(self): + return False + + def type_domain(self): + pass + + def qualified_name(self): + pass + + # This is used to resolve nested types after instances are created. + def resolve_type_references(self, protocol): + pass + + +class PrimitiveType(Type): + def __init__(self, name): + self._name = name + + def __repr__(self): + return 'PrimitiveType[%s]' % self.qualified_name() + + def type_domain(self): + return None + + def qualified_name(self): + return self.raw_name() + + +class AliasedType(Type): + def __init__(self, declaration, domain, aliased_type_ref): + self._name = declaration.type_name + self._declaration = declaration + self._domain = domain + self._aliased_type_ref = aliased_type_ref + self.aliased_type = None + + def __repr__(self): + if self.aliased_type is not None: + return 'AliasedType[%s -> %r]' % (self.qualified_name(), self.aliased_type) + else: + return 'AliasedType[%s -> (unresolved)]' % self.qualified_name() + + def is_enum(self): + return self.aliased_type.is_enum() + + def type_domain(self): + return self._domain + + def qualified_name(self): + return ".".join([self.type_domain().domain_name, self.raw_name()]) + + def resolve_type_references(self, protocol): + if self.aliased_type is not None: + return + + self.aliased_type = protocol.lookup_type_reference(self._aliased_type_ref, self.type_domain()) + log.debug("< Resolved type reference for aliased type in %s: %s" % (self.qualified_name(), self.aliased_type.qualified_name())) + + +class EnumType(Type): + def __init__(self, declaration, domain, values, primitive_type_ref, is_anonymous=False): + self._name = "(anonymous)" if declaration is None else declaration.type_name + self._declaration = declaration + self._domain = domain + self._values = values + self._primitive_type_ref = primitive_type_ref + self.primitive_type = None + self.is_anonymous = is_anonymous + + def __repr__(self): + return 'EnumType[value_type=%s; values=%s]' % (self.qualified_name(), ', '.join(map(str, self.enum_values()))) + + def is_enum(self): + return True + + def enum_values(self): + return self._values + + def type_domain(self): + return self._domain + + def declaration(self): + return self._declaration + + def qualified_name(self): + return ".".join([self.type_domain().domain_name, self.raw_name()]) + + def resolve_type_references(self, protocol): + if self.primitive_type is not None: + return + + self.primitive_type = protocol.lookup_type_reference(self._primitive_type_ref, Domains.GLOBAL) + log.debug("< Resolved type reference for enum type in %s: %s" % (self.qualified_name(), self.primitive_type.qualified_name())) + log.debug("<< enum values: %s" % self.enum_values()) + + +class ArrayType(Type): + def __init__(self, declaration, element_type_ref, domain): + self._name = None if declaration is None else declaration.type_name + self._declaration = declaration + self._domain = domain + self._element_type_ref = element_type_ref + self.element_type = None + + def __repr__(self): + if self.element_type is not None: + return 'ArrayType[element_type=%r]' % self.element_type + else: + return 'ArrayType[element_type=(unresolved)]' + + def declaration(self): + return self._declaration + + def type_domain(self): + return self._domain + + def qualified_name(self): + return ".".join(["array", self.element_type.qualified_name()]) + + def resolve_type_references(self, protocol): + if self.element_type is not None: + return + + self.element_type = protocol.lookup_type_reference(self._element_type_ref, self.type_domain()) + log.debug("< Resolved type reference for element type in %s: %s" % (self.qualified_name(), self.element_type.qualified_name())) + + +class ObjectType(Type): + def __init__(self, declaration, domain): + self._name = declaration.type_name + self._declaration = declaration + self._domain = domain + self.members = declaration.type_members + + def __repr__(self): + return 'ObjectType[%s]' % self.qualified_name() + + def declaration(self): + return self._declaration + + def type_domain(self): + return self._domain + + def qualified_name(self): + return ".".join([self.type_domain().domain_name, self.raw_name()]) + + +def check_for_required_properties(props, obj, what): + for prop in props: + if prop not in obj: + raise ParseException("When parsing %s, required property missing: %s" % (what, prop)) + + +class Protocol: + def __init__(self, framework_name): + self.domains = [] + self.types_by_name = {} + self.framework = Framework.fromString(framework_name) + + def parse_specification(self, json, isSupplemental): + log.debug("parse toplevel") + + if isinstance(json, dict) and 'domains' in json: + json = json['domains'] + if not isinstance(json, list): + json = [json] + + for domain in json: + self.parse_domain(domain, isSupplemental) + + def parse_domain(self, json, isSupplemental): + check_for_required_properties(['domain'], json, "domain") + log.debug("parse domain " + json['domain']) + + types = [] + commands = [] + events = [] + + if 'types' in json: + if not isinstance(json['types'], list): + raise ParseException("Malformed domain specification: types is not an array") + types.extend([self.parse_type_declaration(declaration) for declaration in json['types']]) + + if 'commands' in json: + if not isinstance(json['commands'], list): + raise ParseException("Malformed domain specification: commands is not an array") + commands.extend([self.parse_command(command) for command in json['commands']]) + + if 'events' in json: + if not isinstance(json['events'], list): + raise ParseException("Malformed domain specification: events is not an array") + events.extend([self.parse_event(event) for event in json['events']]) + + if 'availability' in json: + if not commands and not events: + raise ParseException("Malformed domain specification: availability should only be included if there are commands or events.") + allowed_activation_strings = set(['web']) + if json['availability'] not in allowed_activation_strings: + raise ParseException('Malformed domain specification: availability is an unsupported string. Was: "%s", Allowed values: %s' % (json['availability'], ', '.join(allowed_activation_strings))) + + if 'workerSupported' in json: + if not isinstance(json['workerSupported'], bool): + raise ParseException('Malformed domain specification: workerSupported is not a boolean. Was: "%s"' % json['availability']) + + self.domains.append(Domain(json['domain'], json.get('description', ''), json.get('featureGuard'), json.get('availability'), json.get('workerSupported', False), isSupplemental, types, commands, events)) + + def parse_type_declaration(self, json): + check_for_required_properties(['id', 'type'], json, "type") + log.debug("parse type %s" % json['id']) + + type_members = [] + + if 'properties' in json: + if not isinstance(json['properties'], list): + raise ParseException("Malformed type specification: properties is not an array") + type_members.extend([self.parse_type_member(member) for member in json['properties']]) + + duplicate_names = find_duplicates([member.member_name for member in type_members]) + if len(duplicate_names) > 0: + raise ParseException("Malformed domain specification: type declaration for %s has duplicate member names" % json['id']) + + type_ref = TypeReference(json['type'], json.get('$ref'), json.get('enum'), json.get('items')) + platform = Platform.fromString(json.get('platform', 'generic')) + return TypeDeclaration(json['id'], type_ref, json.get("description", ""), platform, type_members) + + def parse_type_member(self, json): + check_for_required_properties(['name'], json, "type member") + log.debug("parse type member %s" % json['name']) + + type_ref = TypeReference(json.get('type'), json.get('$ref'), json.get('enum'), json.get('items')) + return TypeMember(json['name'], type_ref, json.get('optional', False), json.get('description', "")) + + def parse_command(self, json): + check_for_required_properties(['name'], json, "command") + log.debug("parse command %s" % json['name']) + + call_parameters = [] + return_parameters = [] + + if 'parameters' in json: + if not isinstance(json['parameters'], list): + raise ParseException("Malformed command specification: parameters is not an array") + call_parameters.extend([self.parse_call_or_return_parameter(parameter) for parameter in json['parameters']]) + + duplicate_names = find_duplicates([param.parameter_name for param in call_parameters]) + if len(duplicate_names) > 0: + raise ParseException("Malformed domain specification: call parameter list for command %s has duplicate parameter names" % json['name']) + + if 'returns' in json: + if not isinstance(json['returns'], list): + raise ParseException("Malformed command specification: returns is not an array") + return_parameters.extend([self.parse_call_or_return_parameter(parameter) for parameter in json['returns']]) + + duplicate_names = find_duplicates([param.parameter_name for param in return_parameters]) + if len(duplicate_names) > 0: + raise ParseException("Malformed domain specification: return parameter list for command %s has duplicate parameter names" % json['name']) + + platform = Platform.fromString(json.get('platform', 'generic')) + return Command(json['name'], call_parameters, return_parameters, json.get('description', ""), platform, json.get('async', False)) + + def parse_event(self, json): + check_for_required_properties(['name'], json, "event") + log.debug("parse event %s" % json['name']) + + event_parameters = [] + + if 'parameters' in json: + if not isinstance(json['parameters'], list): + raise ParseException("Malformed event specification: parameters is not an array") + event_parameters.extend([self.parse_call_or_return_parameter(parameter) for parameter in json['parameters']]) + + duplicate_names = find_duplicates([param.parameter_name for param in event_parameters]) + if len(duplicate_names) > 0: + raise ParseException("Malformed domain specification: parameter list for event %s has duplicate parameter names" % json['name']) + + platform = Platform.fromString(json.get('platform', 'generic')) + return Event(json['name'], event_parameters, json.get('description', ""), platform) + + def parse_call_or_return_parameter(self, json): + check_for_required_properties(['name'], json, "parameter") + log.debug("parse parameter %s" % json['name']) + + type_ref = TypeReference(json.get('type'), json.get('$ref'), json.get('enum'), json.get('items')) + return Parameter(json['name'], type_ref, json.get('optional', False), json.get('description', "")) + + def resolve_types(self): + qualified_declared_type_names = set(['boolean', 'string', 'integer', 'number', 'enum', 'array', 'object', 'any']) + + self.types_by_name['string'] = PrimitiveType('string') + for _primitive_type in ['boolean', 'integer', 'number']: + self.types_by_name[_primitive_type] = PrimitiveType(_primitive_type) + for _object_type in ['any', 'object']: + self.types_by_name[_object_type] = PrimitiveType(_object_type) + + # Gather qualified type names from type declarations in each domain. + for domain in self.domains: + for declaration in domain.all_type_declarations(): + # Basic sanity checking. + if declaration.type_ref.referenced_type_name is not None: + raise TypecheckException("Type declarations must name a base type, not a type reference.") + + # Find duplicate qualified type names. + qualified_type_name = ".".join([domain.domain_name, declaration.type_name]) + if qualified_type_name in qualified_declared_type_names: + raise TypecheckException("Duplicate type declaration: %s" % qualified_type_name) + + qualified_declared_type_names.add(qualified_type_name) + + type_instance = None + + kind = declaration.type_ref.type_kind + if declaration.type_ref.enum_values is not None: + primitive_type_ref = TypeReference(declaration.type_ref.type_kind, None, None, None) + type_instance = EnumType(declaration, domain, declaration.type_ref.enum_values, primitive_type_ref) + elif kind == "array": + type_instance = ArrayType(declaration, declaration.type_ref.array_type_ref, domain) + elif kind == "object": + type_instance = ObjectType(declaration, domain) + else: + type_instance = AliasedType(declaration, domain, declaration.type_ref) + + log.debug("< Created fresh type %r for declaration %s" % (type_instance, qualified_type_name)) + self.types_by_name[qualified_type_name] = type_instance + + # Resolve all type references recursively. + for domain in self.domains: + domain.resolve_type_references(self) + + def lookup_type_for_declaration(self, declaration, domain): + # This will only match a type defined in the same domain, where prefixes aren't required. + qualified_name = ".".join([domain.domain_name, declaration.type_name]) + if qualified_name in self.types_by_name: + found_type = self.types_by_name[qualified_name] + found_type.resolve_type_references(self) + return found_type + + raise TypecheckException("Lookup failed for type declaration: %s (referenced from domain: %s)" % (declaration.type_name, domain.domain_name)) + + def lookup_type_reference(self, type_ref, domain): + # If reference is to an anonymous array type, create a fresh instance. + if type_ref.type_kind == "array": + type_instance = ArrayType(None, type_ref.array_type_ref, domain) + type_instance.resolve_type_references(self) + log.debug("< Created fresh type instance for anonymous array type: %s" % type_instance.qualified_name()) + return type_instance + + # If reference is to an anonymous enum type, create a fresh instance. + if type_ref.enum_values is not None: + # We need to create a type reference without enum values as the enum's nested type. + primitive_type_ref = TypeReference(type_ref.type_kind, None, None, None) + type_instance = EnumType(None, domain, type_ref.enum_values, primitive_type_ref, True) + type_instance.resolve_type_references(self) + log.debug("< Created fresh type instance for anonymous enum type: %s" % type_instance.qualified_name()) + return type_instance + + # This will match when referencing a type defined in the same domain, where prefixes aren't required. + qualified_name = ".".join([domain.domain_name, type_ref.referenced_name()]) + if qualified_name in self.types_by_name: + found_type = self.types_by_name[qualified_name] + found_type.resolve_type_references(self) + log.debug("< Lookup succeeded for unqualified type: %s" % found_type.qualified_name()) + return found_type + + # This will match primitive types and fully-qualified types from a different domain. + if type_ref.referenced_name() in self.types_by_name: + found_type = self.types_by_name[type_ref.referenced_name()] + found_type.resolve_type_references(self) + log.debug("< Lookup succeeded for primitive or qualified type: %s" % found_type.qualified_name()) + return found_type + + raise TypecheckException("Lookup failed for type reference: %s (referenced from domain: %s)" % (type_ref.referenced_name(), domain.domain_name)) + + +class Domain: + def __init__(self, domain_name, description, feature_guard, availability, workerSupported, isSupplemental, type_declarations, commands, events): + self.domain_name = domain_name + self.description = description + self.feature_guard = feature_guard + self.availability = availability + self.workerSupported = workerSupported + self.is_supplemental = isSupplemental + self._type_declarations = type_declarations + self._commands = commands + self._events = events + + def all_type_declarations(self): + return self._type_declarations + + def all_commands(self): + return self._commands + + def all_events(self): + return self._events + + def resolve_type_references(self, protocol): + log.debug("> Resolving type declarations for domain: %s" % self.domain_name) + for declaration in self._type_declarations: + declaration.resolve_type_references(protocol, self) + + log.debug("> Resolving types in commands for domain: %s" % self.domain_name) + for command in self._commands: + command.resolve_type_references(protocol, self) + + log.debug("> Resolving types in events for domain: %s" % self.domain_name) + for event in self._events: + event.resolve_type_references(protocol, self) + + +class Domains: + GLOBAL = Domain("", "The global domain, in which primitive types are implicitly declared.", None, None, True, False, [], [], []) + + +class TypeDeclaration: + def __init__(self, type_name, type_ref, description, platform, type_members): + self.type_name = type_name + self.type_ref = type_ref + self.description = description + self.platform = platform + self.type_members = type_members + + if self.type_name != ucfirst(self.type_name): + raise ParseException("Types must begin with an uppercase character.") + + def resolve_type_references(self, protocol, domain): + log.debug(">> Resolving type references for type declaration: %s" % self.type_name) + self.type = protocol.lookup_type_for_declaration(self, domain) + for member in self.type_members: + member.resolve_type_references(protocol, domain) + + +class TypeMember: + def __init__(self, member_name, type_ref, is_optional, description): + self.member_name = member_name + self.type_ref = type_ref + self.is_optional = is_optional + self.description = description + + if not isinstance(self.is_optional, bool): + raise ParseException("The 'optional' flag for a type member must be a boolean literal.") + + def resolve_type_references(self, protocol, domain): + log.debug(">>> Resolving type references for type member: %s" % self.member_name) + self.type = protocol.lookup_type_reference(self.type_ref, domain) + + +class Parameter: + def __init__(self, parameter_name, type_ref, is_optional, description): + self.parameter_name = parameter_name + self.type_ref = type_ref + self.is_optional = is_optional + self.description = description + + if not isinstance(self.is_optional, bool): + raise ParseException("The 'optional' flag for a parameter must be a boolean literal.") + + def resolve_type_references(self, protocol, domain): + log.debug(">>> Resolving type references for parameter: %s" % self.parameter_name) + self.type = protocol.lookup_type_reference(self.type_ref, domain) + + +class Command: + def __init__(self, command_name, call_parameters, return_parameters, description, platform, is_async): + self.command_name = command_name + self.call_parameters = call_parameters + self.return_parameters = return_parameters + self.description = description + self.platform = platform + self.is_async = is_async + + def resolve_type_references(self, protocol, domain): + log.debug(">> Resolving type references for call parameters in command: %s" % self.command_name) + for parameter in self.call_parameters: + parameter.resolve_type_references(protocol, domain) + + log.debug(">> Resolving type references for return parameters in command: %s" % self.command_name) + for parameter in self.return_parameters: + parameter.resolve_type_references(protocol, domain) + + +class Event: + def __init__(self, event_name, event_parameters, description, platform): + self.event_name = event_name + self.event_parameters = event_parameters + self.description = description + self.platform = platform + + def resolve_type_references(self, protocol, domain): + log.debug(">> Resolving type references for parameters in event: %s" % self.event_name) + for parameter in self.event_parameters: + parameter.resolve_type_references(protocol, domain) diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/objc_generator.py b/Source/JavaScriptCore/inspector/scripts/codegen/objc_generator.py new file mode 100755 index 000000000..21e179148 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/objc_generator.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +import logging +from generator import Generator, ucfirst +from models import PrimitiveType, ObjectType, ArrayType, EnumType, AliasedType, Frameworks + +log = logging.getLogger('global') + + +def join_type_and_name(type_str, name_str): + if type_str.endswith('*'): + return type_str + name_str + return type_str + ' ' + name_str + + +def strip_block_comment_markers(str): + return str.replace('/*', '').replace('*/', '') + + +def remove_duplicate_from_str(str, possible_duplicate): + return str.replace(possible_duplicate + possible_duplicate, possible_duplicate) + + +_OBJC_IDENTIFIER_RENAME_MAP = { + 'this': 'thisObject', # Debugger.CallFrame.this + 'description': 'stringRepresentation', # Runtime.RemoteObject.description + 'id': 'identifier', # Page.Frame.id, Runtime.ExecutionContextDescription.id, Debugger.BreakpointAction.id +} + +_OBJC_IDENTIFIER_REVERSE_RENAME_MAP = dict((v, k) for k, v in _OBJC_IDENTIFIER_RENAME_MAP.iteritems()) + + +class ObjCTypeCategory: + Simple = 0 + String = 1 + Object = 2 + Array = 3 + + @staticmethod + def category_for_type(_type): + if (isinstance(_type, PrimitiveType)): + if _type.raw_name() is 'string': + return ObjCTypeCategory.String + if _type.raw_name() in ['object', 'any']: + return ObjCTypeCategory.Object + if _type.raw_name() is 'array': + return ObjCTypeCategory.Array + return ObjCTypeCategory.Simple + if (isinstance(_type, ObjectType)): + return ObjCTypeCategory.Object + if (isinstance(_type, ArrayType)): + return ObjCTypeCategory.Array + if (isinstance(_type, AliasedType)): + return ObjCTypeCategory.category_for_type(_type.aliased_type) + if (isinstance(_type, EnumType)): + return ObjCTypeCategory.category_for_type(_type.primitive_type) + return None + +# Almost all Objective-C class names require the use of a prefix that depends on the +# target framework's 'objc_prefix' setting. So, most helpers are instance methods. + +class ObjCGenerator(Generator): + # Do not use a dynamic prefix for RWIProtocolJSONObject since it's used as a common + # base class and needs a consistent Objective-C prefix to be in a reusable framework. + OBJC_HELPER_PREFIX = 'RWI' + OBJC_SHARED_PREFIX = 'Protocol' + OBJC_STATIC_PREFIX = '%s%s' % (OBJC_HELPER_PREFIX, OBJC_SHARED_PREFIX) + + def __init__(self, *args, **kwargs): + Generator.__init__(self, *args, **kwargs) + + # The 'protocol name' is used to prefix filenames for a protocol group (a set of domains generated together). + def protocol_name(self): + protocol_group = self.model().framework.setting('objc_protocol_group', '') + return '%s%s' % (protocol_group, ObjCGenerator.OBJC_SHARED_PREFIX) + + # The 'ObjC prefix' is used to prefix Objective-C class names and enums with a + # framework-specific prefix. It is separate from filename prefixes. + def objc_prefix(self): + framework_prefix = self.model().framework.setting('objc_prefix', None) + if not framework_prefix: + return '' + else: + return '%s%s' % (framework_prefix, ObjCGenerator.OBJC_SHARED_PREFIX) + + # Adjust identifier names that collide with ObjC keywords. + + @staticmethod + def identifier_to_objc_identifier(name): + return _OBJC_IDENTIFIER_RENAME_MAP.get(name, name) + + @staticmethod + def objc_identifier_to_identifier(name): + return _OBJC_IDENTIFIER_REVERSE_RENAME_MAP.get(name, name) + + # Generate ObjC types, command handlers, and event dispatchers for a subset of domains. + + DOMAINS_TO_GENERATE = ['CSS', 'DOM', 'DOMStorage', 'Network', 'Page', 'Automation', 'GenericTypes'] + + def should_generate_types_for_domain(self, domain): + if not len(self.type_declarations_for_domain(domain)): + return False + + if self.model().framework is Frameworks.Test: + return True + + whitelist = set(ObjCGenerator.DOMAINS_TO_GENERATE) + whitelist.update(set(['Console', 'Debugger', 'Runtime'])) + return domain.domain_name in whitelist + + def should_generate_commands_for_domain(self, domain): + if not len(self.commands_for_domain(domain)): + return False + + if self.model().framework is Frameworks.Test: + return True + + whitelist = set(ObjCGenerator.DOMAINS_TO_GENERATE) + return domain.domain_name in whitelist + + def should_generate_events_for_domain(self, domain): + if not len(self.events_for_domain(domain)): + return False + + if self.model().framework is Frameworks.Test: + return True + + whitelist = set(ObjCGenerator.DOMAINS_TO_GENERATE) + whitelist.add('Console') + return domain.domain_name in whitelist + + # ObjC enum and type names. + + def objc_name_for_type(self, type): + name = type.qualified_name().replace('.', '') + name = remove_duplicate_from_str(name, type.type_domain().domain_name) + return '%s%s' % (self.objc_prefix(), name) + + def objc_enum_name_for_anonymous_enum_declaration(self, declaration): + domain_name = declaration.type.type_domain().domain_name + name = '%s%s' % (domain_name, declaration.type.raw_name()) + name = remove_duplicate_from_str(name, domain_name) + return '%s%s' % (self.objc_prefix(), name) + + def objc_enum_name_for_anonymous_enum_member(self, declaration, member): + domain_name = member.type.type_domain().domain_name + name = '%s%s%s' % (domain_name, declaration.type.raw_name(), ucfirst(member.member_name)) + name = remove_duplicate_from_str(name, domain_name) + return '%s%s' % (self.objc_prefix(), name) + + def objc_enum_name_for_anonymous_enum_parameter(self, domain, event_or_command_name, parameter): + domain_name = domain.domain_name + name = '%s%s%s' % (domain_name, ucfirst(event_or_command_name), ucfirst(parameter.parameter_name)) + name = remove_duplicate_from_str(name, domain_name) + return '%s%s' % (self.objc_prefix(), name) + + def objc_enum_name_for_non_anonymous_enum(self, _type): + domain_name = _type.type_domain().domain_name + name = _type.qualified_name().replace('.', '') + name = remove_duplicate_from_str(name, domain_name) + return '%s%s' % (self.objc_prefix(), name) + + # Miscellaneous name handling. + + @staticmethod + def variable_name_prefix_for_domain(domain): + domain_name = domain.domain_name + if domain_name.startswith('DOM'): + return 'dom' + domain_name[3:] + if domain_name.startswith('CSS'): + return 'css' + domain_name[3:] + return domain_name[:1].lower() + domain_name[1:] + + # Type basics. + + @staticmethod + def objc_accessor_type_for_raw_name(raw_name): + if raw_name in ['string', 'array']: + return 'copy' + if raw_name in ['integer', 'number', 'boolean']: + return 'assign' + if raw_name in ['any', 'object']: + return 'retain' + return None + + @staticmethod + def objc_type_for_raw_name(raw_name): + if raw_name is 'string': + return 'NSString *' + if raw_name is 'array': + return 'NSArray *' + if raw_name is 'integer': + return 'int' + if raw_name is 'number': + return 'double' + if raw_name is 'boolean': + return 'BOOL' + if raw_name in ['any', 'object']: + return '%sJSONObject *' % ObjCGenerator.OBJC_STATIC_PREFIX + return None + + @staticmethod + def objc_class_for_raw_name(raw_name): + if raw_name is 'string': + return 'NSString' + if raw_name is 'array': + return 'NSArray' + if raw_name in ['integer', 'number', 'boolean']: + return 'NSNumber' + if raw_name in ['any', 'object']: + return '%sJSONObject' % ObjCGenerator.OBJC_STATIC_PREFIX + return None + + # FIXME: Can these protocol_type functions be removed in favor of C++ generators functions? + + @staticmethod + def protocol_type_for_raw_name(raw_name): + if raw_name is 'string': + return 'String' + if raw_name is 'integer': + return 'int' + if raw_name is 'number': + return 'double' + if raw_name is 'boolean': + return 'bool' + if raw_name in ['any', 'object']: + return 'InspectorObject' + return None + + @staticmethod + def protocol_type_for_type(_type): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + return ObjCGenerator.protocol_type_for_raw_name(_type.raw_name()) + if (isinstance(_type, EnumType)): + return ObjCGenerator.protocol_type_for_type(_type.primitive_type) + if (isinstance(_type, ObjectType)): + return 'Inspector::Protocol::%s::%s' % (_type.type_domain().domain_name, _type.raw_name()) + if (isinstance(_type, ArrayType)): + sub_type = ObjCGenerator.protocol_type_for_type(_type.element_type) + return 'Inspector::Protocol::Array<%s>' % sub_type + return None + + @staticmethod + def is_type_objc_pointer_type(_type): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + return _type.raw_name() in ['string', 'array', 'any', 'object'] + if (isinstance(_type, EnumType)): + return False + if (isinstance(_type, ObjectType)): + return True + if (isinstance(_type, ArrayType)): + return True + return None + + def objc_class_for_type(self, _type): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + return ObjCGenerator.objc_class_for_raw_name(_type.raw_name()) + if (isinstance(_type, EnumType)): + return ObjCGenerator.objc_class_for_raw_name(_type.primitive_type.raw_name()) + if (isinstance(_type, ObjectType)): + return self.objc_name_for_type(_type) + if (isinstance(_type, ArrayType)): + sub_type = strip_block_comment_markers(self.objc_class_for_type(_type.element_type)) + return 'NSArray/*<%s>*/' % sub_type + return None + + def objc_class_for_array_type(self, _type): + if isinstance(_type, AliasedType): + _type = _type.aliased_type + if isinstance(_type, ArrayType): + return self.objc_class_for_type(_type.element_type) + return None + + def objc_accessor_type_for_member(self, member): + return self.objc_accessor_type_for_member_internal(member.type) + + def objc_accessor_type_for_member_internal(self, _type): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + return self.objc_accessor_type_for_raw_name(_type.raw_name()) + if (isinstance(_type, EnumType)): + return 'assign' + if (isinstance(_type, ObjectType)): + return 'retain' + if (isinstance(_type, ArrayType)): + return 'copy' + return None + + def objc_type_for_member(self, declaration, member): + return self.objc_type_for_member_internal(member.type, declaration, member) + + def objc_type_for_member_internal(self, _type, declaration, member): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + return self.objc_type_for_raw_name(_type.raw_name()) + if (isinstance(_type, EnumType)): + if (_type.is_anonymous): + return self.objc_enum_name_for_anonymous_enum_member(declaration, member) + return self.objc_enum_name_for_non_anonymous_enum(_type) + if (isinstance(_type, ObjectType)): + return self.objc_name_for_type(_type) + ' *' + if (isinstance(_type, ArrayType)): + sub_type = strip_block_comment_markers(self.objc_class_for_type(_type.element_type)) + return 'NSArray/*<%s>*/ *' % sub_type + return None + + def objc_type_for_param(self, domain, event_or_command_name, parameter, respect_optional=True): + objc_type = self.objc_type_for_param_internal(parameter.type, domain, event_or_command_name, parameter) + if respect_optional and parameter.is_optional: + if objc_type.endswith('*'): + return objc_type + '*' + return objc_type + ' *' + return objc_type + + def objc_type_for_param_internal(self, _type, domain, event_or_command_name, parameter): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + return self.objc_type_for_raw_name(_type.raw_name()) + if (isinstance(_type, EnumType)): + if _type.is_anonymous: + return self.objc_enum_name_for_anonymous_enum_parameter(domain, event_or_command_name, parameter) + return self.objc_enum_name_for_non_anonymous_enum(_type) + if (isinstance(_type, ObjectType)): + return self.objc_name_for_type(_type) + ' *' + if (isinstance(_type, ArrayType)): + sub_type = strip_block_comment_markers(self.objc_class_for_type(_type.element_type)) + return 'NSArray/*<%s>*/ *' % sub_type + return None + + # ObjC <-> Protocol conversion for commands and events. + # - convert a command call parameter received from Protocol to ObjC for handler + # - convert a command return parameter in callback block from ObjC to Protocol to send + # - convert an event parameter from ObjC API to Protocol to send + + def objc_protocol_export_expression_for_variable(self, var_type, var_name): + category = ObjCTypeCategory.category_for_type(var_type) + if category in [ObjCTypeCategory.Simple, ObjCTypeCategory.String]: + if isinstance(var_type, EnumType): + return 'toProtocolString(%s)' % var_name + return var_name + if category is ObjCTypeCategory.Object: + return '[%s toInspectorObject]' % var_name + if category is ObjCTypeCategory.Array: + protocol_type = ObjCGenerator.protocol_type_for_type(var_type.element_type) + objc_class = self.objc_class_for_type(var_type.element_type) + if protocol_type == 'Inspector::Protocol::Array<String>': + return 'inspectorStringArrayArray(%s)' % var_name + if protocol_type is 'String' and objc_class is 'NSString': + return 'inspectorStringArray(%s)' % var_name + if protocol_type is 'int' and objc_class is 'NSNumber': + return 'inspectorIntegerArray(%s)' % var_name + if protocol_type is 'double' and objc_class is 'NSNumber': + return 'inspectorDoubleArray(%s)' % var_name + return 'inspectorObjectArray(%s)' % var_name + + def objc_protocol_import_expression_for_member(self, name, declaration, member): + if isinstance(member.type, EnumType): + if member.type.is_anonymous: + return 'fromProtocolString<%s>(%s)' % (self.objc_enum_name_for_anonymous_enum_member(declaration, member), name) + return 'fromProtocolString<%s>(%s)' % (self.objc_enum_name_for_non_anonymous_enum(member.type), name) + return self.objc_protocol_import_expression_for_variable(member.type, name) + + def objc_protocol_import_expression_for_parameter(self, name, domain, event_or_command_name, parameter): + if isinstance(parameter.type, EnumType): + if parameter.type.is_anonymous: + return 'fromProtocolString<%s>(%s)' % (self.objc_enum_name_for_anonymous_enum_parameter(domain, event_or_command_name, parameter), name) + return 'fromProtocolString<%s>(%s)' % (self.objc_enum_name_for_non_anonymous_enum(parameter.type), name) + return self.objc_protocol_import_expression_for_variable(parameter.type, name) + + def objc_protocol_import_expression_for_variable(self, var_type, var_name): + category = ObjCTypeCategory.category_for_type(var_type) + if category in [ObjCTypeCategory.Simple, ObjCTypeCategory.String]: + return var_name + if category is ObjCTypeCategory.Object: + objc_class = self.objc_class_for_type(var_type) + return '[[[%s alloc] initWithInspectorObject:%s] autorelease]' % (objc_class, var_name) + if category is ObjCTypeCategory.Array: + objc_class = self.objc_class_for_type(var_type.element_type) + if objc_class is 'NSString': + return 'objcStringArray(%s)' % var_name + if objc_class is 'NSNumber': # FIXME: Integer or Double? + return 'objcIntegerArray(%s)' % var_name + return 'objcArray<%s>(%s)' % (objc_class, var_name) + + # ObjC <-> JSON object conversion for types getters/setters. + # - convert a member setter from ObjC API to JSON object setter + # - convert a member getter from JSON object to ObjC API + + def objc_to_protocol_expression_for_member(self, declaration, member, sub_expression): + category = ObjCTypeCategory.category_for_type(member.type) + if category in [ObjCTypeCategory.Simple, ObjCTypeCategory.String]: + if isinstance(member.type, EnumType): + return 'toProtocolString(%s)' % sub_expression + return sub_expression + if category is ObjCTypeCategory.Object: + return sub_expression + if category is ObjCTypeCategory.Array: + objc_class = self.objc_class_for_type(member.type.element_type) + if objc_class is 'NSString': + return 'inspectorStringArray(%s)' % sub_expression + if objc_class is 'NSNumber': + protocol_type = ObjCGenerator.protocol_type_for_type(member.type.element_type) + if protocol_type is 'double': + return 'inspectorDoubleArray(%s)' % sub_expression + return 'inspectorIntegerArray(%s)' % sub_expression + return 'inspectorObjectArray(%s)' % sub_expression + + def protocol_to_objc_expression_for_member(self, declaration, member, sub_expression): + category = ObjCTypeCategory.category_for_type(member.type) + if category in [ObjCTypeCategory.Simple, ObjCTypeCategory.String]: + if isinstance(member.type, EnumType): + if member.type.is_anonymous: + return 'fromProtocolString<%s>(%s).value()' % (self.objc_enum_name_for_anonymous_enum_member(declaration, member), sub_expression) + return 'fromProtocolString<%s>(%s).value()' % (self.objc_enum_name_for_non_anonymous_enum(member.type), sub_expression) + return sub_expression + if category is ObjCTypeCategory.Object: + objc_class = self.objc_class_for_type(member.type) + return '[[%s alloc] initWithInspectorObject:[%s toInspectorObject].get()]' % (objc_class, sub_expression) + if category is ObjCTypeCategory.Array: + protocol_type = ObjCGenerator.protocol_type_for_type(member.type.element_type) + objc_class = self.objc_class_for_type(member.type.element_type) + if objc_class is 'NSString': + return 'objcStringArray(%s)' % sub_expression + if objc_class is 'NSNumber': + protocol_type = ObjCGenerator.protocol_type_for_type(member.type.element_type) + if protocol_type is 'double': + return 'objcDoubleArray(%s)' % sub_expression + return 'objcIntegerArray(%s)' % sub_expression + return 'objcArray<%s>(%s)' % (objc_class, sub_expression) + + def payload_to_objc_expression_for_member(self, declaration, member): + _type = member.type + if isinstance(_type, AliasedType): + _type = _type.aliased_type + if isinstance(_type, PrimitiveType): + sub_expression = 'payload[@"%s"]' % member.member_name + raw_name = _type.raw_name() + if raw_name is 'boolean': + return '[%s boolValue]' % sub_expression + if raw_name is 'integer': + return '[%s integerValue]' % sub_expression + if raw_name is 'number': + return '[%s doubleValue]' % sub_expression + if raw_name in ['any', 'object', 'array', 'string']: + return sub_expression # The setter will check the incoming value. + return None + if isinstance(member.type, EnumType): + sub_expression = 'payload[@"%s"]' % member.member_name + if member.type.is_anonymous: + return 'fromProtocolString<%s>(%s)' % (self.objc_enum_name_for_anonymous_enum_member(declaration, member), sub_expression) + else: + return 'fromProtocolString<%s>(%s)' % (self.objc_enum_name_for_non_anonymous_enum(member.type), sub_expression) + if isinstance(_type, ObjectType): + objc_class = self.objc_class_for_type(member.type) + return '[[%s alloc] initWithPayload:payload[@"%s"]]' % (objc_class, member.member_name) + if isinstance(_type, ArrayType): + objc_class = self.objc_class_for_type(member.type.element_type) + return 'objcArrayFromPayload<%s>(payload[@"%s"])' % (objc_class, member.member_name) + + # JSON object setter/getter selectors for types. + + @staticmethod + def objc_setter_method_for_member(declaration, member): + return ObjCGenerator.objc_setter_method_for_member_internal(member.type, declaration, member) + + @staticmethod + def objc_setter_method_for_member_internal(_type, declaration, member): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + raw_name = _type.raw_name() + if raw_name is 'boolean': + return 'setBool' + if raw_name is 'integer': + return 'setInteger' + if raw_name is 'number': + return 'setDouble' + if raw_name is 'string': + return 'setString' + if raw_name in ['any', 'object']: + return 'setObject' + if raw_name is 'array': + return 'setInspectorArray' + return None + if (isinstance(_type, EnumType)): + return 'setString' + if (isinstance(_type, ObjectType)): + return 'setObject' + if (isinstance(_type, ArrayType)): + return 'setInspectorArray' + return None + + @staticmethod + def objc_getter_method_for_member(declaration, member): + return ObjCGenerator.objc_getter_method_for_member_internal(member.type, declaration, member) + + @staticmethod + def objc_getter_method_for_member_internal(_type, declaration, member): + if (isinstance(_type, AliasedType)): + _type = _type.aliased_type + if (isinstance(_type, PrimitiveType)): + raw_name = _type.raw_name() + if raw_name is 'boolean': + return 'boolForKey' + if raw_name is 'integer': + return 'integerForKey' + if raw_name is 'number': + return 'doubleForKey' + if raw_name is 'string': + return 'stringForKey' + if raw_name in ['any', 'object']: + return 'objectForKey' + if raw_name is 'array': + return 'inspectorArrayForKey' + return None + if (isinstance(_type, EnumType)): + return 'stringForKey' + if (isinstance(_type, ObjectType)): + return 'objectForKey' + if (isinstance(_type, ArrayType)): + return 'inspectorArrayForKey' + return None diff --git a/Source/JavaScriptCore/inspector/scripts/codegen/objc_generator_templates.py b/Source/JavaScriptCore/inspector/scripts/codegen/objc_generator_templates.py new file mode 100755 index 000000000..1c30c40d4 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/codegen/objc_generator_templates.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +# Generator templates, which can be filled with string.Template. +# Following are classes that fill the templates from the typechecked model. + +class ObjCGeneratorTemplates: + + HeaderPrelude = ( + """#import <Foundation/Foundation.h> + +${includes} +""") + + HeaderPostlude = ( + """""") + + TypeConversionsHeaderPrelude = ( + """${includes} + +namespace Inspector {""") + + TypeConversionsHeaderPostlude = ( + """} // namespace Inspector +""") + + GenericHeaderPrelude = ( + """${includes}""") + + GenericHeaderPostlude = ( + """""") + + TypeConversionsHeaderStandard = ( + """template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value);""") + + BackendDispatcherHeaderPrelude = ( + """${includes} + +${forwardDeclarations} + +namespace Inspector { +""") + + BackendDispatcherHeaderPostlude = ( + """} // namespace Inspector +""") + + BackendDispatcherImplementationPrelude = ( + """#import "config.h" +#import ${primaryInclude} + +${secondaryIncludes} + +namespace Inspector {""") + + BackendDispatcherImplementationPostlude = ( + """} // namespace Inspector +""") + + ImplementationPrelude = ( + """#import ${primaryInclude} + +${secondaryIncludes} + +using namespace Inspector;""") + + ImplementationPostlude = ( + """""") + + BackendDispatcherHeaderDomainHandlerInterfaceDeclaration = ( + """class Alternate${domainName}BackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~Alternate${domainName}BackendDispatcher() { } +${commandDeclarations} +};""") + + BackendDispatcherHeaderDomainHandlerObjCDeclaration = ( + """class ObjCInspector${domainName}BackendDispatcher final : public Alternate${domainName}BackendDispatcher { +public: + ObjCInspector${domainName}BackendDispatcher(id<${objcPrefix}${domainName}DomainHandler> handler) { m_delegate = handler; } +${commandDeclarations} +private: + RetainPtr<id<${objcPrefix}${domainName}DomainHandler>> m_delegate; +};""") + + BackendDispatcherHeaderDomainHandlerImplementation = ( + """void ObjCInspector${domainName}BackendDispatcher::${commandName}(${parameters}) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + +${successCallback} +${conversions} +${invocation} +} +""") + + ConfigurationCommandProperty = ( + """@property (nonatomic, retain, setter=set${domainName}Handler:) id<${objcPrefix}${domainName}DomainHandler> ${variableNamePrefix}Handler;""") + + ConfigurationEventProperty = ( + """@property (nonatomic, readonly) ${objcPrefix}${domainName}DomainEventDispatcher *${variableNamePrefix}EventDispatcher;""") + + ConfigurationCommandPropertyImplementation = ( + """- (void)set${domainName}Handler:(id<${objcPrefix}${domainName}DomainHandler>)handler +{ + if (handler == _${variableNamePrefix}Handler) + return; + + [_${variableNamePrefix}Handler release]; + _${variableNamePrefix}Handler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspector${domainName}BackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<${domainName}BackendDispatcher, Alternate${domainName}BackendDispatcher>>(ASCIILiteral("${domainName}"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<${objcPrefix}${domainName}DomainHandler>)${variableNamePrefix}Handler +{ + return _${variableNamePrefix}Handler; +}""") + + ConfigurationGetterImplementation = ( + """- (${objcPrefix}${domainName}DomainEventDispatcher *)${variableNamePrefix}EventDispatcher +{ + if (!_${variableNamePrefix}EventDispatcher) + _${variableNamePrefix}EventDispatcher = [[${objcPrefix}${domainName}DomainEventDispatcher alloc] initWithController:_controller]; + return _${variableNamePrefix}EventDispatcher; +}""") diff --git a/Source/JavaScriptCore/inspector/scripts/cssmin.py b/Source/JavaScriptCore/inspector/scripts/cssmin.py deleted file mode 100644 index a0640eb28..000000000 --- a/Source/JavaScriptCore/inspector/scripts/cssmin.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/python - -# Copyright (C) 2013 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. - -import re - -def cssminify(css): - rules = ( - (r"\/\*.*?\*\/", ""), # delete comments - (r"\n", ""), # delete new lines - (r"\s+", " "), # change multiple spaces to one space - (r"\s?([;:{},+>])\s?", r"\1"), # delete space where it is not needed - (r";}", "}") # change ';}' to '}' because the semicolon is not needed - ) - - css = css.replace("\r\n", "\n") - for rule in rules: - css = re.compile(rule[0], re.MULTILINE | re.UNICODE | re.DOTALL).sub(rule[1], css) - return css - -if __name__ == "__main__": - import sys - sys.stdout.write(cssminify(sys.stdin.read())) diff --git a/Source/JavaScriptCore/inspector/scripts/generate-combined-inspector-json.py b/Source/JavaScriptCore/inspector/scripts/generate-combined-inspector-json.py deleted file mode 100755 index db163bfe4..000000000 --- a/Source/JavaScriptCore/inspector/scripts/generate-combined-inspector-json.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/python - -# Copyright (C) 2013 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. - -import glob -import json -import os -import sys - -if len(sys.argv) < 2: - print("usage: %s [json files or directory of json files ...]" % os.path.basename(sys.argv[0])) - sys.exit(1) - -files = [] -for arg in sys.argv[1:]: - if not os.access(arg, os.F_OK): - raise Exception("File \"%s\" not found" % arg) - elif os.path.isdir(arg): - files.extend(glob.glob(os.path.join(arg, "*.json"))) - else: - files.append(arg) -files.sort() - -# To keep as close to the original JSON formatting as possible, just -# dump each JSON input file unmodified into an array of "domains". -# Validate each file is valid JSON and that there is a "domain" key. - -first = True -print("{\"domains\":[") -for file in files: - if first: - first = False - else: - print(",") - - string = open(file).read() - - try: - dictionary = json.loads(string) - if not "domain" in dictionary: - raise Exception("File \"%s\" does not contains a \"domain\" key." % file) - except ValueError: - sys.stderr.write("File \"%s\" does not contain valid JSON:\n" % file) - raise - - print(string.rstrip()) -print("]}") diff --git a/Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py b/Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py new file mode 100755 index 000000000..e39a604fc --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014, 2016 Apple Inc. All rights reserved. +# Copyright (c) 2014 University of Washington. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + +# This script generates JS, Objective C, and C++ bindings for the inspector protocol. +# Generators for individual files are located in the codegen/ directory. + +import os.path +import re +import sys +import string +from string import Template +import optparse +import logging + +try: + import json +except ImportError: + import simplejson as json + +logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.ERROR) +log = logging.getLogger('global') + +try: + from codegen import * + +# When copying generator files to JavaScriptCore's private headers on Mac, +# the codegen/ module directory is flattened. So, import directly. +except ImportError, e: + # log.error(e) # Uncomment this to debug early import errors. + import models + from models import * + from generator import * + from cpp_generator import * + from objc_generator import * + + from generate_cpp_alternate_backend_dispatcher_header import * + from generate_cpp_backend_dispatcher_header import * + from generate_cpp_backend_dispatcher_implementation import * + from generate_cpp_frontend_dispatcher_header import * + from generate_cpp_frontend_dispatcher_implementation import * + from generate_cpp_protocol_types_header import * + from generate_cpp_protocol_types_implementation import * + from generate_js_backend_commands import * + from generate_objc_backend_dispatcher_header import * + from generate_objc_backend_dispatcher_implementation import * + from generate_objc_configuration_header import * + from generate_objc_configuration_implementation import * + from generate_objc_frontend_dispatcher_implementation import * + from generate_objc_header import * + from generate_objc_internal_header import * + from generate_objc_protocol_type_conversions_header import * + from generate_objc_protocol_type_conversions_implementation import * + from generate_objc_protocol_types_implementation import * + + +# A writer that only updates file if it actually changed. +class IncrementalFileWriter: + def __init__(self, filepath, force_output): + self._filepath = filepath + self._output = "" + self.force_output = force_output + + def write(self, text): + self._output += text + + def close(self): + text_changed = True + self._output = self._output.rstrip() + "\n" + + try: + if self.force_output: + raise + + read_file = open(self._filepath, "r") + old_text = read_file.read() + read_file.close() + text_changed = old_text != self._output + except: + # Ignore, just overwrite by default + pass + + if text_changed or self.force_output: + out_file = open(self._filepath, "w") + out_file.write(self._output) + out_file.close() + + +def generate_from_specification(primary_specification_filepath=None, + supplemental_specification_filepaths=[], + concatenate_output=False, + output_dirpath=None, + force_output=False, + framework_name="", + platform_name="", + generate_frontend=True, + generate_backend=True): + + def load_specification(protocol, filepath, isSupplemental=False): + try: + with open(filepath, "r") as input_file: + parsed_json = json.load(input_file) + protocol.parse_specification(parsed_json, isSupplemental) + except ValueError as e: + raise Exception("Error parsing valid JSON in file: " + filepath + "\nParse error: " + str(e)) + + platform = Platform.fromString(platform_name) + protocol = models.Protocol(framework_name) + for specification in supplemental_specification_filepaths: + load_specification(protocol, specification, isSupplemental=True) + load_specification(protocol, primary_specification_filepath, isSupplemental=False) + + protocol.resolve_types() + + generator_arguments = [protocol, platform, primary_specification_filepath] + generators = [] + + if protocol.framework is Frameworks.Test: + generators.append(JSBackendCommandsGenerator(*generator_arguments)) + generators.append(CppAlternateBackendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(CppBackendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(CppBackendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(CppFrontendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(CppFrontendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(CppProtocolTypesHeaderGenerator(*generator_arguments)) + generators.append(CppProtocolTypesImplementationGenerator(*generator_arguments)) + generators.append(ObjCBackendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(ObjCBackendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(ObjCConfigurationHeaderGenerator(*generator_arguments)) + generators.append(ObjCConfigurationImplementationGenerator(*generator_arguments)) + generators.append(ObjCFrontendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(ObjCHeaderGenerator(*generator_arguments)) + generators.append(ObjCInternalHeaderGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypeConversionsHeaderGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypeConversionsImplementationGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypesImplementationGenerator(*generator_arguments)) + + elif protocol.framework is Frameworks.JavaScriptCore: + generators.append(JSBackendCommandsGenerator(*generator_arguments)) + generators.append(CppAlternateBackendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(CppBackendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(CppBackendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(CppFrontendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(CppFrontendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(CppProtocolTypesHeaderGenerator(*generator_arguments)) + generators.append(CppProtocolTypesImplementationGenerator(*generator_arguments)) + + elif protocol.framework is Frameworks.WebKit and generate_backend: + generators.append(CppBackendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(CppBackendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(CppProtocolTypesHeaderGenerator(*generator_arguments)) + generators.append(CppProtocolTypesImplementationGenerator(*generator_arguments)) + + elif protocol.framework is Frameworks.WebKit and generate_frontend: + generators.append(ObjCHeaderGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypeConversionsHeaderGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypeConversionsImplementationGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypesImplementationGenerator(*generator_arguments)) + + elif protocol.framework is Frameworks.WebInspector: + generators.append(ObjCBackendDispatcherHeaderGenerator(*generator_arguments)) + generators.append(ObjCBackendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(ObjCConfigurationHeaderGenerator(*generator_arguments)) + generators.append(ObjCConfigurationImplementationGenerator(*generator_arguments)) + generators.append(ObjCFrontendDispatcherImplementationGenerator(*generator_arguments)) + generators.append(ObjCHeaderGenerator(*generator_arguments)) + generators.append(ObjCInternalHeaderGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypeConversionsHeaderGenerator(*generator_arguments)) + generators.append(ObjCProtocolTypesImplementationGenerator(*generator_arguments)) + + single_output_file_contents = [] + + for generator in generators: + # Only some generators care whether frontend or backend was specified, but it is + # set on all of them to avoid adding more constructor arguments or thinking too hard. + if generate_backend: + generator.set_generator_setting('generate_backend', True) + if generate_frontend: + generator.set_generator_setting('generate_frontend', True) + + output = generator.generate_output() + if concatenate_output: + single_output_file_contents.append('### Begin File: %s' % generator.output_filename()) + single_output_file_contents.append(output) + single_output_file_contents.append('### End File: %s' % generator.output_filename()) + single_output_file_contents.append('') + else: + output_file = IncrementalFileWriter(os.path.join(output_dirpath, generator.output_filename()), force_output) + output_file.write(output) + output_file.close() + + if concatenate_output: + filename = os.path.join(os.path.basename(primary_specification_filepath) + '-result') + output_file = IncrementalFileWriter(os.path.join(output_dirpath, filename), force_output) + output_file.write('\n'.join(single_output_file_contents)) + output_file.close() + + +if __name__ == '__main__': + allowed_framework_names = ['JavaScriptCore', 'WebInspector', 'WebKit', 'Test'] + allowed_platform_names = ['iOS', 'macOS', 'all', 'generic'] + cli_parser = optparse.OptionParser(usage="usage: %prog [options] PrimaryProtocol.json [SupplementalProtocol.json ...]") + cli_parser.add_option("-o", "--outputDir", help="Directory where generated files should be written.") + cli_parser.add_option("--framework", type="choice", choices=allowed_framework_names, help="The framework that the primary specification belongs to.") + cli_parser.add_option("--force", action="store_true", help="Force output of generated scripts, even if nothing changed.") + cli_parser.add_option("-v", "--debug", action="store_true", help="Log extra output for debugging the generator itself.") + cli_parser.add_option("-t", "--test", action="store_true", help="Enable test mode. Use unique output filenames created by prepending the input filename.") + cli_parser.add_option("--frontend", action="store_true", help="Generate code for the frontend-side of the protocol only.") + cli_parser.add_option("--backend", action="store_true", help="Generate code for the backend-side of the protocol only.") + cli_parser.add_option("--platform", default="generic", help="The platform of the backend being generated. For example, we compile WebKit2 for either macOS or iOS. This value is case-insensitive. Allowed values: %s" % ", ".join(allowed_platform_names)) + options = None + + arg_options, arg_values = cli_parser.parse_args() + if (len(arg_values) < 1): + raise ParseException("At least one plain argument expected") + + if not arg_options.outputDir: + raise ParseException("Missing output directory") + + if arg_options.debug: + log.setLevel(logging.DEBUG) + + generate_backend = arg_options.backend; + generate_frontend = arg_options.frontend; + # Default to generating both the frontend and backend if neither is specified. + if not generate_backend and not generate_frontend: + generate_backend = True + generate_frontend = True + + options = { + 'primary_specification_filepath': arg_values[0], + 'supplemental_specification_filepaths': arg_values[1:], + 'output_dirpath': arg_options.outputDir, + 'concatenate_output': arg_options.test, + 'framework_name': arg_options.framework, + 'platform_name': arg_options.platform, + 'force_output': arg_options.force, + 'generate_backend': generate_backend, + 'generate_frontend': generate_frontend, + } + + try: + generate_from_specification(**options) + except (ParseException, TypecheckException) as e: + if arg_options.test: + log.error(e.message) + else: + raise # Force the build to fail. diff --git a/Source/JavaScriptCore/inspector/scripts/inline-and-minify-stylesheets-and-scripts.py b/Source/JavaScriptCore/inspector/scripts/inline-and-minify-stylesheets-and-scripts.py deleted file mode 100755 index 89200c84e..000000000 --- a/Source/JavaScriptCore/inspector/scripts/inline-and-minify-stylesheets-and-scripts.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (C) 2013 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. - -# This script inlines and minifies external stylesheets and scripts. -# - <link href="..." rel="stylesheet"> => <style>...</style> -# - <script src="..."> => <script>...</script> - -import cssmin -import jsmin -import os.path -import re -import sys - - -def main(argv): - - if len(argv) < 2: - print('usage: %s inputFile outputFile' % argv[0]) - return 1 - - inputFileName = argv[1] - outputFileName = argv[2] - importsDir = os.path.dirname(inputFileName) - - inputFile = open(inputFileName, 'r') - inputContent = inputFile.read() - inputFile.close() - - def inline(match, minifier, prefix, postfix): - importFileName = match.group(1) - fullPath = os.path.join(importsDir, importFileName) - if not os.access(fullPath, os.F_OK): - raise Exception('File %s referenced in %s not found' % (importFileName, inputFileName)) - importFile = open(fullPath, 'r') - importContent = minifier(importFile.read()) - importFile.close() - return '%s%s%s' % (prefix, importContent, postfix) - - def inlineStylesheet(match): - return inline(match, cssmin.cssminify, "<style>", "</style>") - - def inlineScript(match): - return inline(match, jsmin.jsmin, "<script>", "</script>") - - outputContent = re.sub(r'<link rel="stylesheet" href=[\'"]([^\'"]+)[\'"]>', inlineStylesheet, inputContent) - outputContent = re.sub(r'<script src=[\'"]([^\'"]+)[\'"]></script>', inlineScript, outputContent) - - outputFile = open(outputFileName, 'w') - outputFile.write(outputContent) - outputFile.close() - - # Touch output file directory to make sure that Xcode will copy - # modified resource files. - if sys.platform == 'darwin': - outputDirName = os.path.dirname(outputFileName) - os.utime(outputDirName, None) - -if __name__ == '__main__': - sys.exit(main(sys.argv)) diff --git a/Source/JavaScriptCore/inspector/scripts/jsmin.py b/Source/JavaScriptCore/inspector/scripts/jsmin.py deleted file mode 100644 index 83d2a50ac..000000000 --- a/Source/JavaScriptCore/inspector/scripts/jsmin.py +++ /dev/null @@ -1,238 +0,0 @@ -# This code is original from jsmin by Douglas Crockford, it was translated to -# Python by Baruch Even. It was rewritten by Dave St.Germain for speed. -# -# The MIT License (MIT) -# -# Copyright (c) 2013 Dave St.Germain -# -# 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. - - -import sys -is_3 = sys.version_info >= (3, 0) -if is_3: - import io -else: - import StringIO - try: - import cStringIO - except ImportError: - cStringIO = None - - -__all__ = ['jsmin', 'JavascriptMinify'] -__version__ = '2.0.9' - - -def jsmin(js): - """ - returns a minified version of the javascript string - """ - if not is_3: - if cStringIO and not isinstance(js, unicode): - # strings can use cStringIO for a 3x performance - # improvement, but unicode (in python2) cannot - klass = cStringIO.StringIO - else: - klass = StringIO.StringIO - else: - klass = io.StringIO - ins = klass(js) - outs = klass() - JavascriptMinify(ins, outs).minify() - return outs.getvalue() - - -class JavascriptMinify(object): - """ - Minify an input stream of javascript, writing - to an output stream - """ - - def __init__(self, instream=None, outstream=None): - self.ins = instream - self.outs = outstream - - def minify(self, instream=None, outstream=None): - if instream and outstream: - self.ins, self.outs = instream, outstream - - self.is_return = False - self.return_buf = '' - - def write(char): - # all of this is to support literal regular expressions. - # sigh - if char in 'return': - self.return_buf += char - self.is_return = self.return_buf == 'return' - self.outs.write(char) - if self.is_return: - self.return_buf = '' - - read = self.ins.read - - space_strings = "abcdefghijklmnopqrstuvwxyz"\ - "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$\\" - starters, enders = '{[(+-', '}])+-"\'' - newlinestart_strings = starters + space_strings - newlineend_strings = enders + space_strings - do_newline = False - do_space = False - escape_slash_count = 0 - doing_single_comment = False - previous_before_comment = '' - doing_multi_comment = False - in_re = False - in_quote = '' - quote_buf = [] - - previous = read(1) - if previous == '\\': - escape_slash_count += 1 - next1 = read(1) - if previous == '/': - if next1 == '/': - doing_single_comment = True - elif next1 == '*': - doing_multi_comment = True - previous = next1 - next1 = read(1) - else: - write(previous) - elif not previous: - return - elif previous >= '!': - if previous in "'\"": - in_quote = previous - write(previous) - previous_non_space = previous - else: - previous_non_space = ' ' - if not next1: - return - - while 1: - next2 = read(1) - if not next2: - last = next1.strip() - if not (doing_single_comment or doing_multi_comment)\ - and last not in ('', '/'): - if in_quote: - write(''.join(quote_buf)) - write(last) - break - if doing_multi_comment: - if next1 == '*' and next2 == '/': - doing_multi_comment = False - next2 = read(1) - elif doing_single_comment: - if next1 in '\r\n': - doing_single_comment = False - while next2 in '\r\n': - next2 = read(1) - if not next2: - break - if previous_before_comment in ')}]': - do_newline = True - elif previous_before_comment in space_strings: - write('\n') - elif in_quote: - quote_buf.append(next1) - - if next1 == in_quote: - numslashes = 0 - for c in reversed(quote_buf[:-1]): - if c != '\\': - break - else: - numslashes += 1 - if numslashes % 2 == 0: - in_quote = '' - write(''.join(quote_buf)) - elif next1 in '\r\n': - if previous_non_space in newlineend_strings \ - or previous_non_space > '~': - while 1: - if next2 < '!': - next2 = read(1) - if not next2: - break - else: - if next2 in newlinestart_strings \ - or next2 > '~' or next2 == '/': - do_newline = True - break - elif next1 < '!' and not in_re: - if (previous_non_space in space_strings \ - or previous_non_space > '~') \ - and (next2 in space_strings or next2 > '~'): - do_space = True - elif previous_non_space in '-+' and next2 == previous_non_space: - # protect against + ++ or - -- sequences - do_space = True - elif self.is_return and next2 == '/': - # returning a regex... - write(' ') - elif next1 == '/': - if do_space: - write(' ') - if in_re: - if previous != '\\' or (not escape_slash_count % 2) or next2 in 'gimy': - in_re = False - write('/') - elif next2 == '/': - doing_single_comment = True - previous_before_comment = previous_non_space - elif next2 == '*': - doing_multi_comment = True - previous = next1 - next1 = next2 - next2 = read(1) - else: - in_re = previous_non_space in '(,=:[?!&|' or self.is_return # literal regular expression - write('/') - else: - if do_space: - do_space = False - write(' ') - if do_newline: - write('\n') - do_newline = False - - write(next1) - if not in_re and next1 in "'\"": - in_quote = next1 - quote_buf = [] - - previous = next1 - next1 = next2 - - if previous >= '!': - previous_non_space = previous - - if previous == '\\': - escape_slash_count += 1 - else: - escape_slash_count = 0 - -if __name__ == '__main__': - minifier = JavascriptMinify(sys.stdin, sys.stdout) - minifier.minify() - sys.stdout.write('\n') diff --git a/Source/JavaScriptCore/inspector/scripts/tests/all/definitions-with-mac-platform.json b/Source/JavaScriptCore/inspector/scripts/tests/all/definitions-with-mac-platform.json new file mode 100644 index 000000000..817f135ee --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/all/definitions-with-mac-platform.json @@ -0,0 +1,28 @@ +{ + "domain": "Network", + "types": [ + { + "id": "NetworkError", + "type": "object", + "platform": "macos", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + } + ], + "commands": [ + { + "name": "loadResource", + "platform": "macos", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + } + ], + "events": [ + { + "name": "resourceLoaded", + "platform": "macos", + "description": "A resource was loaded." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/all/expected/definitions-with-mac-platform.json-result b/Source/JavaScriptCore/inspector/scripts/tests/all/expected/definitions-with-mac-platform.json-result new file mode 100644 index 000000000..170d57c0a --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/all/expected/definitions-with-mac-platform.json-result @@ -0,0 +1,1203 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Network. +InspectorBackend.registerNetworkDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Network"); +InspectorBackend.registerEvent("Network.resourceLoaded", []); +InspectorBackend.registerCommand("Network.loadResource", [], []); +InspectorBackend.activateDomain("Network"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +class AlternateNetworkBackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateNetworkBackendDispatcher() { } + virtual void loadResource(long callId) = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +class AlternateNetworkBackendDispatcher; +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +class NetworkBackendDispatcherHandler { +public: + virtual void loadResource(ErrorString&) = 0; +protected: + virtual ~NetworkBackendDispatcherHandler(); +}; + +class NetworkBackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<NetworkBackendDispatcher> create(BackendDispatcher&, NetworkBackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void loadResource(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateNetworkBackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateNetworkBackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + NetworkBackendDispatcher(BackendDispatcher&, NetworkBackendDispatcherHandler*); + NetworkBackendDispatcherHandler* m_agent { nullptr }; +}; + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +NetworkBackendDispatcherHandler::~NetworkBackendDispatcherHandler() { } + +Ref<NetworkBackendDispatcher> NetworkBackendDispatcher::create(BackendDispatcher& backendDispatcher, NetworkBackendDispatcherHandler* agent) +{ + return adoptRef(*new NetworkBackendDispatcher(backendDispatcher, agent)); +} + +NetworkBackendDispatcher::NetworkBackendDispatcher(BackendDispatcher& backendDispatcher, NetworkBackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("Network"), this); +} + +void NetworkBackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<NetworkBackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "loadResource") + loadResource(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "Network", '.', method, "' was not found")); +} + +void NetworkBackendDispatcher::loadResource(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +class NetworkFrontendDispatcher { +public: + NetworkFrontendDispatcher(FrontendRouter& frontendRouter) : m_frontendRouter(frontendRouter) { } + void resourceLoaded(); +private: + FrontendRouter& m_frontendRouter; +}; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +void NetworkFrontendDispatcher::resourceLoaded() +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Network.resourceLoaded")); + + m_frontendRouter.sendEvent(jsonMessage->toJSONString()); +} + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Network { +class NetworkError; +} // Network +// End of forward declarations. + + + + +namespace Network { +class NetworkError : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + MessageSet = 1 << 0, + CodeSet = 1 << 1, + AllFieldsSet = (MessageSet | CodeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*NetworkError*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class NetworkError; + public: + + Builder<STATE | MessageSet>& setMessage(const String& value) + { + COMPILE_ASSERT(!(STATE & MessageSet), property_message_already_set); + m_result->setString(ASCIILiteral("message"), value); + return castState<MessageSet>(); + } + + Builder<STATE | CodeSet>& setCode(int value) + { + COMPILE_ASSERT(!(STATE & CodeSet), property_code_already_set); + m_result->setInteger(ASCIILiteral("code"), value); + return castState<CodeSet>(); + } + + Ref<NetworkError> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(NetworkError) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<NetworkError>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<NetworkError> result = NetworkError::create() + * .setMessage(...) + * .setCode(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +} // Network + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolNetworkDomainHandler; + +namespace Inspector { + + +class ObjCInspectorNetworkBackendDispatcher final : public AlternateNetworkBackendDispatcher { +public: + ObjCInspectorNetworkBackendDispatcher(id<TestProtocolNetworkDomainHandler> handler) { m_delegate = handler; } + virtual void loadResource(long requestId) override; +private: + RetainPtr<id<TestProtocolNetworkDomainHandler>> m_delegate; +}; + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +void ObjCInspectorNetworkBackendDispatcher::loadResource(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResourceWithErrorCallback:errorCallback successCallback:successCallback]; +} + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setNetworkHandler:) id<TestProtocolNetworkDomainHandler> networkHandler; +@property (nonatomic, readonly) TestProtocolNetworkDomainEventDispatcher *networkEventDispatcher; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolNetworkDomainHandler> _networkHandler; + TestProtocolNetworkDomainEventDispatcher *_networkEventDispatcher; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_networkHandler release]; + [_networkEventDispatcher release]; + [super dealloc]; +} + +- (void)setNetworkHandler:(id<TestProtocolNetworkDomainHandler>)handler +{ + if (handler == _networkHandler) + return; + + [_networkHandler release]; + _networkHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorNetworkBackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<NetworkBackendDispatcher, AlternateNetworkBackendDispatcher>>(ASCIILiteral("Network"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolNetworkDomainHandler>)networkHandler +{ + return _networkHandler; +} + +- (TestProtocolNetworkDomainEventDispatcher *)networkEventDispatcher +{ + if (!_networkEventDispatcher) + _networkEventDispatcher = [[TestProtocolNetworkDomainEventDispatcher alloc] initWithController:_controller]; + return _networkEventDispatcher; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + +@implementation TestProtocolNetworkDomainEventDispatcher +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller; +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)resourceLoaded +{ + const FrontendRouter& router = _controller->frontendRouter(); + + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Network.resourceLoaded")); + router.sendEvent(jsonMessage->toJSONString()); +} + +@end + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolNetworkError; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + +__attribute__((visibility ("default"))) +@interface TestProtocolNetworkError : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithMessage:(NSString *)message code:(int)code; +/* required */ @property (nonatomic, copy) NSString *message; +/* required */ @property (nonatomic, assign) int code; +@end + +@protocol TestProtocolNetworkDomainHandler <NSObject> +@required +- (void)loadResourceWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolNetworkDomainEventDispatcher : NSObject +- (void)resourceLoaded; +@end + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + +@interface TestProtocolNetworkDomainEventDispatcher (Private) +- (instancetype)initWithController:(Inspector::AugmentableInspectorController*)controller; +@end + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (NetworkDomain) + ++ (void)_parseNetworkError:(TestProtocolNetworkError **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (NetworkDomain) + ++ (void)_parseNetworkError:(TestProtocolNetworkError **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolNetworkError alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolNetworkError + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"message"], @"message"); + self.message = payload[@"message"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"code"], @"code"); + self.code = [payload[@"code"] integerValue]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithMessage:(NSString *)message code:(int)code +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(message, @"message"); + + self.message = message; + self.code = code; + + return self; +} + +- (void)setMessage:(NSString *)message +{ + [super setString:message forKey:@"message"]; +} + +- (NSString *)message +{ + return [super stringForKey:@"message"]; +} + +- (void)setCode:(int)code +{ + [super setInteger:code forKey:@"code"]; +} + +- (int)code +{ + return [super integerForKey:@"code"]; +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/commands-with-async-attribute.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/commands-with-async-attribute.json new file mode 100644 index 000000000..11262e889 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/commands-with-async-attribute.json @@ -0,0 +1,109 @@ +{ + "domain": "Database", + "types": [ + { + "id": "DatabaseId", + "type": "integer", + "description": "Unique identifier of Database object." + }, + { + "id": "PrimaryColors", + "type": "string", + "enum": ["red", "green", "blue"] + }, + { + "id": "ColorList", + "type": "array", + "items": { "$ref": "PrimaryColors" } + }, + { + "id": "Error", + "type": "object", + "description": "Database error.", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + } + ], + "commands": [ + { + "name": "executeSQLSyncOptionalReturnValues", + "parameters": [ + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "query", "type": "string" } + ], + "returns": [ + { "name": "columnNames", "type": "array", "optional": true, "items": { "type": "string" } }, + { "name": "notes", "type": "string", "optional": true }, + { "name": "timestamp", "type": "number", "optional": true }, + { "name": "values", "type": "object", "optional": true }, + { "name": "payload", "type": "any", "optional": true }, + { "name": "databaseId", "$ref": "DatabaseId", "optional": true }, + { "name": "sqlError", "$ref": "Error", "optional": true }, + { "name": "screenColor", "$ref": "PrimaryColors", "optional": true }, + { "name": "alternateColors", "$ref": "ColorList", "optional": true }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"], "optional": true } + ] + }, + { + "name": "executeSQLAsyncOptionalReturnValues", + "async": true, + "parameters": [ + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "query", "type": "string" } + ], + "returns": [ + { "name": "columnNames", "type": "array", "optional": true, "items": { "type": "string" } }, + { "name": "notes", "type": "string", "optional": true }, + { "name": "timestamp", "type": "number", "optional": true }, + { "name": "values", "type": "object", "optional": true }, + { "name": "payload", "type": "any", "optional": true }, + { "name": "databaseId", "$ref": "DatabaseId", "optional": true }, + { "name": "sqlError", "$ref": "Error", "optional": true }, + { "name": "screenColor", "$ref": "PrimaryColors", "optional": true }, + { "name": "alternateColors", "$ref": "ColorList", "optional": true }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"], "optional": true } + ] + }, + { + "name": "executeSQLSync", + "parameters": [ + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "query", "type": "string" } + ], + "returns": [ + { "name": "columnNames", "type": "array", "items": { "type": "string" } }, + { "name": "notes", "type": "string" }, + { "name": "timestamp", "type": "number" }, + { "name": "values", "type": "object" }, + { "name": "payload", "type": "any" }, + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "sqlError", "$ref": "Error" }, + { "name": "alternateColors", "$ref": "ColorList" }, + { "name": "screenColor", "$ref": "PrimaryColors" }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"] } + ] + }, + { + "name": "executeSQLAsync", + "async": true, + "parameters": [ + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "query", "type": "string" } + ], + "returns": [ + { "name": "columnNames", "type": "array", "items": { "type": "string" } }, + { "name": "notes", "type": "string" }, + { "name": "timestamp", "type": "number" }, + { "name": "values", "type": "object" }, + { "name": "payload", "type": "any" }, + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "sqlError", "$ref": "Error" }, + { "name": "screenColor", "$ref": "PrimaryColors" }, + { "name": "alternateColors", "$ref": "ColorList" }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"] } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/commands-with-optional-call-return-parameters.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/commands-with-optional-call-return-parameters.json new file mode 100644 index 000000000..361d57d82 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/commands-with-optional-call-return-parameters.json @@ -0,0 +1,85 @@ +{ + "domain": "Database", + "types": [ + { + "id": "DatabaseId", + "type": "integer", + "description": "Unique identifier of Database object." + }, + { + "id": "PrimaryColors", + "type": "string", + "enum": ["red", "green", "blue"] + }, + { + "id": "ColorList", + "type": "array", + "items": { "$ref": "PrimaryColors" } + }, + { + "id": "Error", + "type": "object", + "description": "Database error.", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + } + ], + "commands": [ + { + "name": "executeAllOptionalParameters", + "parameters": [ + { "name": "columnNames", "type": "array", "optional": true, "items": { "type": "string" } }, + { "name": "notes", "type": "string", "optional": true }, + { "name": "timestamp", "type": "number", "optional": true }, + { "name": "values", "type": "object", "optional": true }, + { "name": "payload", "type": "any", "optional": true }, + { "name": "databaseId", "$ref": "DatabaseId", "optional": true }, + { "name": "sqlError", "$ref": "Error", "optional": true }, + { "name": "screenColor", "$ref": "PrimaryColors", "optional": true }, + { "name": "alternateColors", "$ref": "ColorList", "optional": true }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"], "optional": true } + ], + "returns": [ + { "name": "columnNames", "type": "array", "optional": true, "items": { "type": "string" } }, + { "name": "notes", "type": "string", "optional": true }, + { "name": "timestamp", "type": "number", "optional": true }, + { "name": "values", "type": "object", "optional": true }, + { "name": "payload", "type": "any", "optional": true }, + { "name": "databaseId", "$ref": "DatabaseId", "optional": true }, + { "name": "sqlError", "$ref": "Error", "optional": true }, + { "name": "screenColor", "$ref": "PrimaryColors", "optional": true }, + { "name": "alternateColors", "$ref": "ColorList", "optional": true }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"], "optional": true } + ] + }, + { + "name": "executeNoOptionalParameters", + "parameters": [ + { "name": "columnNames", "type": "array", "items": { "type": "string" } }, + { "name": "notes", "type": "string" }, + { "name": "timestamp", "type": "number" }, + { "name": "values", "type": "object" }, + { "name": "payload", "type": "any" }, + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "sqlError", "$ref": "Error" }, + { "name": "screenColor", "$ref": "PrimaryColors" }, + { "name": "alternateColors", "$ref": "ColorList" }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"] } + ], + "returns": [ + { "name": "columnNames", "type": "array", "items": { "type": "string" } }, + { "name": "notes", "type": "string" }, + { "name": "timestamp", "type": "number" }, + { "name": "values", "type": "object" }, + { "name": "payload", "type": "any" }, + { "name": "databaseId", "$ref": "DatabaseId" }, + { "name": "sqlError", "$ref": "Error" }, + { "name": "screenColor", "$ref": "PrimaryColors" }, + { "name": "alternateColors", "$ref": "ColorList" }, + { "name": "printColor", "type": "string", "enum": ["cyan", "magenta", "yellow", "black"] } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/definitions-with-mac-platform.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/definitions-with-mac-platform.json new file mode 100644 index 000000000..817f135ee --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/definitions-with-mac-platform.json @@ -0,0 +1,28 @@ +{ + "domain": "Network", + "types": [ + { + "id": "NetworkError", + "type": "object", + "platform": "macos", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + } + ], + "commands": [ + { + "name": "loadResource", + "platform": "macos", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + } + ], + "events": [ + { + "name": "resourceLoaded", + "platform": "macos", + "description": "A resource was loaded." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/domain-availability.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/domain-availability.json new file mode 100644 index 000000000..5939996e3 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/domain-availability.json @@ -0,0 +1,11 @@ +[ +{ + "domain": "DomainA", + "availability": "web", + "commands": [{"name": "enable"}] +}, +{ + "domain": "DomainB", + "commands": [{"name": "enable"}] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/domains-with-varying-command-sizes.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/domains-with-varying-command-sizes.json new file mode 100644 index 000000000..94a8ecb17 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/domains-with-varying-command-sizes.json @@ -0,0 +1,54 @@ +[ +{ + "domain": "Network1", + "commands": [ + { + "name": "loadResource1", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + } + ] +}, +{ + "domain": "Network2", + "types": [ + { + "id": "LoaderId", + "type": "string", + "description": "Unique loader identifier." + } + ] +}, +{ + "domain": "Network3", + "commands": [ + { + "name": "loadResource1", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + }, + { + "name": "loadResource2", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + }, + { + "name": "loadResource3", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + }, + { + "name": "loadResource4", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + }, + { + "name": "loadResource5", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + }, + { + "name": "loadResource6", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + }, + { + "name": "loadResource7", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/enum-values.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/enum-values.json new file mode 100644 index 000000000..cdad61df7 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/enum-values.json @@ -0,0 +1,35 @@ +{"domains":[ +{ + "domain": "TypeDomain", + "types": [ + { + "id": "TypeDomainEnum", + "type": "string", + "enum": ["shared", "red", "green", "blue"] + } + ] +}, +{ + "domain": "CommandDomain", + "commands": [ + { + "name": "commandWithEnumReturnValue", + "parameters": [], + "returns": [ + { "name": "returnValue", "type": "string", "enum": ["shared", "cyan", "magenta", "yellow"] } + ] + } + ] +}, +{ + "domain": "EventDomain", + "events": [ + { + "name": "eventWithEnumParameter", + "parameters": [ + { "name": "parameter", "type": "string", "enum": ["shared", "black", "white"] } + ] + } + ] +} +]} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/events-with-optional-parameters.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/events-with-optional-parameters.json new file mode 100644 index 000000000..cabbf10b8 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/events-with-optional-parameters.json @@ -0,0 +1,59 @@ +{ + "domain": "Database", + "types": [ + { + "id": "DatabaseId", + "type": "string", + "description": "Unique identifier of Database object." + }, + { + "id": "PrimaryColors", + "type": "string", + "values": ["red", "green", "blue"] + }, + { + "id": "ColorList", + "type": "array", + "items": { "$ref": "PrimaryColors" } + }, + { + "id": "Error", + "type": "object", + "description": "Database error.", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + } + ], + "events": [ + { + "name": "didExecuteOptionalParameters", + "parameters": [ + { "name": "columnNames", "type": "array", "optional": true, "items": { "type": "string" } }, + { "name": "notes", "type": "string", "optional": true }, + { "name": "timestamp", "type": "number", "optional": true }, + { "name": "values", "type": "object", "optional": true }, + { "name": "payload", "type": "any", "optional": true }, + { "name": "sqlError", "$ref": "Error", "optional": true }, + { "name": "screenColor", "$ref": "PrimaryColors", "optional": true }, + { "name": "alternateColors", "$ref": "ColorList", "optional": true }, + { "name": "printColor", "type": "string", "values": ["cyan", "magenta", "yellow", "black"], "optional": true } + ] + }, + { + "name": "didExecuteNoOptionalParameters", + "parameters": [ + { "name": "columnNames", "type": "array", "items": { "type": "string" } }, + { "name": "notes", "type": "string" }, + { "name": "timestamp", "type": "number" }, + { "name": "values", "type": "object" }, + { "name": "payload", "type": "any" }, + { "name": "sqlError", "$ref": "Error" }, + { "name": "screenColor", "$ref": "PrimaryColors" }, + { "name": "alternateColors", "$ref": "ColorList" }, + { "name": "printColor", "type": "string", "values": ["cyan", "magenta", "yellow", "black"] } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/commands-with-async-attribute.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/commands-with-async-attribute.json-result new file mode 100644 index 000000000..ef9a2488d --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/commands-with-async-attribute.json-result @@ -0,0 +1,1780 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Database. +InspectorBackend.registerDatabaseDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Database"); +InspectorBackend.registerEnum("Database.PrimaryColors", {Red: "red", Green: "green", Blue: "blue"}); +InspectorBackend.registerCommand("Database.executeSQLSyncOptionalReturnValues", [{"name": "databaseId", "type": "number", "optional": false}, {"name": "query", "type": "string", "optional": false}], ["columnNames", "notes", "timestamp", "values", "payload", "databaseId", "sqlError", "screenColor", "alternateColors", "printColor"]); +InspectorBackend.registerCommand("Database.executeSQLAsyncOptionalReturnValues", [{"name": "databaseId", "type": "number", "optional": false}, {"name": "query", "type": "string", "optional": false}], ["columnNames", "notes", "timestamp", "values", "payload", "databaseId", "sqlError", "screenColor", "alternateColors", "printColor"]); +InspectorBackend.registerCommand("Database.executeSQLSync", [{"name": "databaseId", "type": "number", "optional": false}, {"name": "query", "type": "string", "optional": false}], ["columnNames", "notes", "timestamp", "values", "payload", "databaseId", "sqlError", "alternateColors", "screenColor", "printColor"]); +InspectorBackend.registerCommand("Database.executeSQLAsync", [{"name": "databaseId", "type": "number", "optional": false}, {"name": "query", "type": "string", "optional": false}], ["columnNames", "notes", "timestamp", "values", "payload", "databaseId", "sqlError", "screenColor", "alternateColors", "printColor"]); +InspectorBackend.activateDomain("Database"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +class AlternateDatabaseBackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateDatabaseBackendDispatcher() { } + virtual void executeSQLSyncOptionalReturnValues(long callId, int in_databaseId, const String& in_query) = 0; + virtual void executeSQLAsyncOptionalReturnValues(long callId, int in_databaseId, const String& in_query) = 0; + virtual void executeSQLSync(long callId, int in_databaseId, const String& in_query) = 0; + virtual void executeSQLAsync(long callId, int in_databaseId, const String& in_query) = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +class AlternateDatabaseBackendDispatcher; +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +class DatabaseBackendDispatcherHandler { +public: + // Named after parameter 'printColor' while generating command/event executeSQLSyncOptionalReturnValues. + enum class PrintColor { + Cyan = 3, + Magenta = 4, + Yellow = 5, + Black = 6, + }; // enum class PrintColor + virtual void executeSQLSyncOptionalReturnValues(ErrorString&, int in_databaseId, const String& in_query, RefPtr<Inspector::Protocol::Array<String>>& opt_out_columnNames, Inspector::Protocol::OptOutput<String>* opt_out_notes, Inspector::Protocol::OptOutput<double>* opt_out_timestamp, Inspector::Protocol::OptOutput<Inspector::InspectorObject>* opt_out_values, Inspector::Protocol::OptOutput<Inspector::InspectorValue>* opt_out_payload, Inspector::Protocol::OptOutput<int>* opt_out_databaseId, RefPtr<Inspector::Protocol::Database::Error>& opt_out_sqlError, Inspector::Protocol::Database::PrimaryColors* opt_out_screenColor, RefPtr<Inspector::Protocol::Database::ColorList>& opt_out_alternateColors, DatabaseBackendDispatcherHandler::PrintColor* opt_out_printColor) = 0; + class ExecuteSQLAsyncOptionalReturnValuesCallback : public BackendDispatcher::CallbackBase { + public: + ExecuteSQLAsyncOptionalReturnValuesCallback(Ref<BackendDispatcher>&&, int id); + void sendSuccess(RefPtr<Inspector::Protocol::Array<String>>&& columnNames, Inspector::Protocol::OptOutput<String>* notes, Inspector::Protocol::OptOutput<double>* timestamp, Inspector::Protocol::OptOutput<Inspector::InspectorObject>* values, Inspector::Protocol::OptOutput<Inspector::InspectorValue>* payload, Inspector::Protocol::OptOutput<int>* databaseId, RefPtr<Inspector::Protocol::Database::Error>&& sqlError, Inspector::Protocol::OptOutput<String>* screenColor, RefPtr<Inspector::Protocol::Database::ColorList>&& alternateColors, Inspector::Protocol::OptOutput<String>* printColor); + }; + virtual void executeSQLAsyncOptionalReturnValues(ErrorString&, int in_databaseId, const String& in_query, Ref<ExecuteSQLAsyncOptionalReturnValuesCallback>&& callback) = 0; + virtual void executeSQLSync(ErrorString&, int in_databaseId, const String& in_query, RefPtr<Inspector::Protocol::Array<String>>& out_columnNames, String* out_notes, double* out_timestamp, Inspector::InspectorObject* out_values, Inspector::InspectorValue* out_payload, int* out_databaseId, RefPtr<Inspector::Protocol::Database::Error>& out_sqlError, RefPtr<Inspector::Protocol::Database::ColorList>& out_alternateColors, Inspector::Protocol::Database::PrimaryColors* out_screenColor, DatabaseBackendDispatcherHandler::PrintColor* out_printColor) = 0; + class ExecuteSQLAsyncCallback : public BackendDispatcher::CallbackBase { + public: + ExecuteSQLAsyncCallback(Ref<BackendDispatcher>&&, int id); + void sendSuccess(RefPtr<Inspector::Protocol::Array<String>>&& columnNames, const String& notes, double timestamp, Inspector::InspectorObject values, Inspector::InspectorValue payload, int databaseId, RefPtr<Inspector::Protocol::Database::Error>&& sqlError, const String& screenColor, RefPtr<Inspector::Protocol::Database::ColorList>&& alternateColors, const String& printColor); + }; + virtual void executeSQLAsync(ErrorString&, int in_databaseId, const String& in_query, Ref<ExecuteSQLAsyncCallback>&& callback) = 0; +protected: + virtual ~DatabaseBackendDispatcherHandler(); +}; + +class DatabaseBackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<DatabaseBackendDispatcher> create(BackendDispatcher&, DatabaseBackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void executeSQLSyncOptionalReturnValues(long requestId, RefPtr<InspectorObject>&& parameters); + void executeSQLAsyncOptionalReturnValues(long requestId, RefPtr<InspectorObject>&& parameters); + void executeSQLSync(long requestId, RefPtr<InspectorObject>&& parameters); + void executeSQLAsync(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateDatabaseBackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateDatabaseBackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + DatabaseBackendDispatcher(BackendDispatcher&, DatabaseBackendDispatcherHandler*); + DatabaseBackendDispatcherHandler* m_agent { nullptr }; +}; + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +DatabaseBackendDispatcherHandler::~DatabaseBackendDispatcherHandler() { } + +Ref<DatabaseBackendDispatcher> DatabaseBackendDispatcher::create(BackendDispatcher& backendDispatcher, DatabaseBackendDispatcherHandler* agent) +{ + return adoptRef(*new DatabaseBackendDispatcher(backendDispatcher, agent)); +} + +DatabaseBackendDispatcher::DatabaseBackendDispatcher(BackendDispatcher& backendDispatcher, DatabaseBackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("Database"), this); +} + +void DatabaseBackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<DatabaseBackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "executeSQLSyncOptionalReturnValues") + executeSQLSyncOptionalReturnValues(requestId, WTFMove(parameters)); + else if (method == "executeSQLAsyncOptionalReturnValues") + executeSQLAsyncOptionalReturnValues(requestId, WTFMove(parameters)); + else if (method == "executeSQLSync") + executeSQLSync(requestId, WTFMove(parameters)); + else if (method == "executeSQLAsync") + executeSQLAsync(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "Database", '.', method, "' was not found")); +} + +void DatabaseBackendDispatcher::executeSQLSyncOptionalReturnValues(long requestId, RefPtr<InspectorObject>&& parameters) +{ + int in_databaseId = m_backendDispatcher->getInteger(parameters.get(), ASCIILiteral("databaseId"), nullptr); + String in_query = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("query"), nullptr); + if (m_backendDispatcher->hasProtocolErrors()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Some arguments of method '%s' can't be processed", "Database.executeSQLSyncOptionalReturnValues")); + return; + } + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->executeSQLSyncOptionalReturnValues(requestId, in_databaseId, in_query); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + RefPtr<Inspector::Protocol::Array<String>> out_columnNames; + Inspector::Protocol::OptOutput<String> out_notes; + Inspector::Protocol::OptOutput<double> out_timestamp; + Inspector::Protocol::OptOutput<Inspector::InspectorObject> out_values; + Inspector::Protocol::OptOutput<Inspector::InspectorValue> out_payload; + Inspector::Protocol::OptOutput<Inspector::Protocol::Database::DatabaseId> out_databaseId; + RefPtr<Inspector::Protocol::Database::Error> out_sqlError; + Inspector::Protocol::Database::PrimaryColors out_screenColor; + RefPtr<Inspector::Protocol::Database::ColorList> out_alternateColors; + DatabaseBackendDispatcherHandler::PrintColor out_printColor; + m_agent->executeSQLSyncOptionalReturnValues(error, in_databaseId, in_query, out_columnNames, &out_notes, &out_timestamp, out_values, &out_payload, &out_databaseId, out_sqlError, &out_screenColor, out_alternateColors, &out_printColor); + + if (!error.length()) { + if (out_columnNames) + result->setArray(ASCIILiteral("columnNames"), out_columnNames); + if (out_notes.isAssigned()) + result->setString(ASCIILiteral("notes"), out_notes.getValue()); + if (out_timestamp.isAssigned()) + result->setDouble(ASCIILiteral("timestamp"), out_timestamp.getValue()); + if (out_values.isAssigned()) + result->setObject(ASCIILiteral("values"), out_values.getValue()); + if (out_payload.isAssigned()) + result->setValue(ASCIILiteral("payload"), out_payload.getValue()); + if (out_databaseId.isAssigned()) + result->setInteger(ASCIILiteral("databaseId"), out_databaseId.getValue()); + if (out_sqlError) + result->setObject(ASCIILiteral("sqlError"), out_sqlError); + if (out_screenColor.isAssigned()) + result->setString(ASCIILiteral("screenColor"), out_screenColor.getValue()); + if (out_alternateColors) + result->setArray(ASCIILiteral("alternateColors"), out_alternateColors); + if (out_printColor.isAssigned()) + result->setString(ASCIILiteral("printColor"), out_printColor.getValue()); + } + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +DatabaseBackendDispatcherHandler::ExecuteSQLAsyncOptionalReturnValuesCallback::ExecuteSQLAsyncOptionalReturnValuesCallback(Ref<BackendDispatcher>&& backendDispatcher, int id) : BackendDispatcher::CallbackBase(WTFMove(backendDispatcher), id) { } + +void DatabaseBackendDispatcherHandler::ExecuteSQLAsyncOptionalReturnValuesCallback::sendSuccess(RefPtr<Inspector::Protocol::Array<String>>&& columnNames, Inspector::Protocol::OptOutput<String>* notes, Inspector::Protocol::OptOutput<double>* timestamp, Inspector::Protocol::OptOutput<Inspector::InspectorObject>* values, Inspector::Protocol::OptOutput<Inspector::InspectorValue>* payload, Inspector::Protocol::OptOutput<int>* databaseId, RefPtr<Inspector::Protocol::Database::Error>&& sqlError, Inspector::Protocol::OptOutput<String>* screenColor, RefPtr<Inspector::Protocol::Database::ColorList>&& alternateColors, Inspector::Protocol::OptOutput<String>* printColor) +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + if (columnNames) + jsonMessage->setArray(ASCIILiteral("columnNames"), columnNames); + if (notes.isAssigned()) + jsonMessage->setString(ASCIILiteral("notes"), notes.getValue()); + if (timestamp.isAssigned()) + jsonMessage->setDouble(ASCIILiteral("timestamp"), timestamp.getValue()); + if (values.isAssigned()) + jsonMessage->setObject(ASCIILiteral("values"), values.getValue()); + if (payload.isAssigned()) + jsonMessage->setValue(ASCIILiteral("payload"), payload.getValue()); + if (databaseId.isAssigned()) + jsonMessage->setInteger(ASCIILiteral("databaseId"), databaseId.getValue()); + if (sqlError) + jsonMessage->setObject(ASCIILiteral("sqlError"), sqlError); + if (screenColor.isAssigned()) + jsonMessage->setString(ASCIILiteral("screenColor"), screenColor.getValue()); + if (alternateColors) + jsonMessage->setArray(ASCIILiteral("alternateColors"), alternateColors); + if (printColor.isAssigned()) + jsonMessage->setString(ASCIILiteral("printColor"), printColor.getValue()); + CallbackBase::sendSuccess(WTFMove(jsonMessage)); +} + +void DatabaseBackendDispatcher::executeSQLAsyncOptionalReturnValues(long requestId, RefPtr<InspectorObject>&& parameters) +{ + int in_databaseId = m_backendDispatcher->getInteger(parameters.get(), ASCIILiteral("databaseId"), nullptr); + String in_query = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("query"), nullptr); + if (m_backendDispatcher->hasProtocolErrors()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Some arguments of method '%s' can't be processed", "Database.executeSQLAsyncOptionalReturnValues")); + return; + } + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->executeSQLAsyncOptionalReturnValues(requestId, in_databaseId, in_query); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + Ref<DatabaseBackendDispatcherHandler::ExecuteSQLAsyncOptionalReturnValuesCallback> callback = adoptRef(*new DatabaseBackendDispatcherHandler::ExecuteSQLAsyncOptionalReturnValuesCallback(m_backendDispatcher.copyRef(), requestId)); + m_agent->executeSQLAsyncOptionalReturnValues(error, in_databaseId, in_query, callback.copyRef()); + + if (error.length()) { + callback->disable(); + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, error); + return; + } +} + +void DatabaseBackendDispatcher::executeSQLSync(long requestId, RefPtr<InspectorObject>&& parameters) +{ + int in_databaseId = m_backendDispatcher->getInteger(parameters.get(), ASCIILiteral("databaseId"), nullptr); + String in_query = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("query"), nullptr); + if (m_backendDispatcher->hasProtocolErrors()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Some arguments of method '%s' can't be processed", "Database.executeSQLSync")); + return; + } + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->executeSQLSync(requestId, in_databaseId, in_query); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + RefPtr<Inspector::Protocol::Array<String>> out_columnNames; + String out_notes; + double out_timestamp; + Inspector::InspectorObject out_values; + Inspector::InspectorValue out_payload; + Inspector::Protocol::Database::DatabaseId out_databaseId; + RefPtr<Inspector::Protocol::Database::Error> out_sqlError; + RefPtr<Inspector::Protocol::Database::ColorList> out_alternateColors; + Inspector::Protocol::Database::PrimaryColors out_screenColor; + DatabaseBackendDispatcherHandler::PrintColor out_printColor; + m_agent->executeSQLSync(error, in_databaseId, in_query, out_columnNames, &out_notes, &out_timestamp, out_values, &out_payload, &out_databaseId, out_sqlError, out_alternateColors, &out_screenColor, &out_printColor); + + if (!error.length()) { + result->setArray(ASCIILiteral("columnNames"), out_columnNames); + result->setString(ASCIILiteral("notes"), out_notes); + result->setDouble(ASCIILiteral("timestamp"), out_timestamp); + result->setObject(ASCIILiteral("values"), out_values); + result->setValue(ASCIILiteral("payload"), out_payload); + result->setInteger(ASCIILiteral("databaseId"), out_databaseId); + result->setObject(ASCIILiteral("sqlError"), out_sqlError); + result->setArray(ASCIILiteral("alternateColors"), out_alternateColors); + result->setString(ASCIILiteral("screenColor"), Inspector::Protocol::TestHelpers::getEnumConstantValue(out_screenColor)); + result->setString(ASCIILiteral("printColor"), Inspector::Protocol::TestHelpers::getEnumConstantValue(out_printColor)); + } + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +DatabaseBackendDispatcherHandler::ExecuteSQLAsyncCallback::ExecuteSQLAsyncCallback(Ref<BackendDispatcher>&& backendDispatcher, int id) : BackendDispatcher::CallbackBase(WTFMove(backendDispatcher), id) { } + +void DatabaseBackendDispatcherHandler::ExecuteSQLAsyncCallback::sendSuccess(RefPtr<Inspector::Protocol::Array<String>>&& columnNames, const String& notes, double timestamp, Inspector::InspectorObject values, Inspector::InspectorValue payload, int databaseId, RefPtr<Inspector::Protocol::Database::Error>&& sqlError, const String& screenColor, RefPtr<Inspector::Protocol::Database::ColorList>&& alternateColors, const String& printColor) +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setArray(ASCIILiteral("columnNames"), columnNames); + jsonMessage->setString(ASCIILiteral("notes"), notes); + jsonMessage->setDouble(ASCIILiteral("timestamp"), timestamp); + jsonMessage->setObject(ASCIILiteral("values"), values); + jsonMessage->setValue(ASCIILiteral("payload"), payload); + jsonMessage->setInteger(ASCIILiteral("databaseId"), databaseId); + jsonMessage->setObject(ASCIILiteral("sqlError"), sqlError); + jsonMessage->setString(ASCIILiteral("screenColor"), Inspector::Protocol::TestHelpers::getEnumConstantValue(screenColor)); + jsonMessage->setArray(ASCIILiteral("alternateColors"), alternateColors); + jsonMessage->setString(ASCIILiteral("printColor"), Inspector::Protocol::TestHelpers::getEnumConstantValue(printColor)); + CallbackBase::sendSuccess(WTFMove(jsonMessage)); +} + +void DatabaseBackendDispatcher::executeSQLAsync(long requestId, RefPtr<InspectorObject>&& parameters) +{ + int in_databaseId = m_backendDispatcher->getInteger(parameters.get(), ASCIILiteral("databaseId"), nullptr); + String in_query = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("query"), nullptr); + if (m_backendDispatcher->hasProtocolErrors()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Some arguments of method '%s' can't be processed", "Database.executeSQLAsync")); + return; + } + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->executeSQLAsync(requestId, in_databaseId, in_query); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + Ref<DatabaseBackendDispatcherHandler::ExecuteSQLAsyncCallback> callback = adoptRef(*new DatabaseBackendDispatcherHandler::ExecuteSQLAsyncCallback(m_backendDispatcher.copyRef(), requestId)); + m_agent->executeSQLAsync(error, in_databaseId, in_query, callback.copyRef()); + + if (error.length()) { + callback->disable(); + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, error); + return; + } +} + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Database { +class Error; +enum class PrimaryColors; +} // Database +// End of forward declarations. + + +// Typedefs. +namespace Database { +/* Unique identifier of Database object. */ +typedef int DatabaseId; +typedef Inspector::Protocol::Array<Inspector::Protocol::Database::PrimaryColors> ColorList; +} // Database +// End of typedefs. + +namespace TestHelpers { + +String getEnumConstantValue(int code); + +template<typename T> String getEnumConstantValue(T enumValue) +{ + return getEnumConstantValue(static_cast<int>(enumValue)); +} + +} // namespace TestHelpers + +namespace Database { +/* */ +enum class PrimaryColors { + Red = 0, + Green = 1, + Blue = 2, +}; // enum class PrimaryColors +/* Database error. */ +class Error : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + MessageSet = 1 << 0, + CodeSet = 1 << 1, + AllFieldsSet = (MessageSet | CodeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*Error*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class Error; + public: + + Builder<STATE | MessageSet>& setMessage(const String& value) + { + COMPILE_ASSERT(!(STATE & MessageSet), property_message_already_set); + m_result->setString(ASCIILiteral("message"), value); + return castState<MessageSet>(); + } + + Builder<STATE | CodeSet>& setCode(int value) + { + COMPILE_ASSERT(!(STATE & CodeSet), property_code_already_set); + m_result->setInteger(ASCIILiteral("code"), value); + return castState<CodeSet>(); + } + + Ref<Error> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(Error) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<Error>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<Error> result = Error::create() + * .setMessage(...) + * .setCode(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +} // Database + + + +namespace TestHelpers { + +template<typename ProtocolEnumType> +std::optional<ProtocolEnumType> parseEnumValueFromString(const String&); + +// Enums in the 'Database' Domain +template<> +std::optional<Inspector::Protocol::Database::PrimaryColors> parseEnumValueFromString<Inspector::Protocol::Database::PrimaryColors>(const String&); + +} // namespace TestHelpers + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + +namespace TestHelpers { + +static const char* const enum_constant_values[] = { + "red", + "green", + "blue", + "cyan", + "magenta", + "yellow", + "black", +}; + +String getEnumConstantValue(int code) { + return enum_constant_values[code]; +} + +// Enums in the 'Database' Domain +template<> +std::optional<Inspector::Protocol::Database::PrimaryColors> parseEnumValueFromString<Inspector::Protocol::Database::PrimaryColors>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Database::PrimaryColors::Red, + (size_t)Inspector::Protocol::Database::PrimaryColors::Green, + (size_t)Inspector::Protocol::Database::PrimaryColors::Blue, + }; + for (size_t i = 0; i < 3; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Database::PrimaryColors)constantValues[i]; + + return std::nullopt; +} + + +} // namespace TestHelpers + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolDatabaseDomainHandler; + +namespace Inspector { + + +class ObjCInspectorDatabaseBackendDispatcher final : public AlternateDatabaseBackendDispatcher { +public: + ObjCInspectorDatabaseBackendDispatcher(id<TestProtocolDatabaseDomainHandler> handler) { m_delegate = handler; } + virtual void executeSQLSyncOptionalReturnValues(long requestId, int in_databaseId, const String& in_query) override; + virtual void executeSQLAsyncOptionalReturnValues(long requestId, int in_databaseId, const String& in_query) override; + virtual void executeSQLSync(long requestId, int in_databaseId, const String& in_query) override; + virtual void executeSQLAsync(long requestId, int in_databaseId, const String& in_query) override; +private: + RetainPtr<id<TestProtocolDatabaseDomainHandler>> m_delegate; +}; + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +void ObjCInspectorDatabaseBackendDispatcher::executeSQLSyncOptionalReturnValues(long requestId, int in_databaseId, const String& in_query) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^(NSArray/*<NSString>*/ **columnNames, NSString **notes, double *timestamp, RWIProtocolJSONObject **values, RWIProtocolJSONObject **payload, int *databaseId, TestProtocolDatabaseError **sqlError, TestProtocolDatabasePrimaryColors *screenColor, NSArray/*<NSString>*/ **alternateColors, TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColor *printColor) { + Ref<InspectorObject> resultObject = InspectorObject::create(); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(alternateColors, @"alternateColors"); + if (columnNames) + resultObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray(*columnNames)); + if (notes) + resultObject->setString(ASCIILiteral("notes"), *notes); + if (timestamp) + resultObject->setDouble(ASCIILiteral("timestamp"), *timestamp); + if (values) + resultObject->setObject(ASCIILiteral("values"), [*values toInspectorObject]); + if (payload) + resultObject->setValue(ASCIILiteral("payload"), [*payload toInspectorObject]); + if (databaseId) + resultObject->setInteger(ASCIILiteral("databaseId"), *databaseId); + if (sqlError) + resultObject->setObject(ASCIILiteral("sqlError"), [*sqlError toInspectorObject]); + if (screenColor) + resultObject->setString(ASCIILiteral("screenColor"), toProtocolString(*screenColor)); + if (alternateColors) + resultObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray(*alternateColors)); + if (printColor) + resultObject->setString(ASCIILiteral("printColor"), toProtocolString(*printColor)); + backendDispatcher()->sendResponse(requestId, WTFMove(resultObject)); + }; + + int o_in_databaseId = in_databaseId; + NSString *o_in_query = in_query; + + [m_delegate executeSQLSyncOptionalReturnValuesWithErrorCallback:errorCallback successCallback:successCallback databaseId:o_in_databaseId query:o_in_query]; +} + +void ObjCInspectorDatabaseBackendDispatcher::executeSQLAsyncOptionalReturnValues(long requestId, int in_databaseId, const String& in_query) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^(NSArray/*<NSString>*/ **columnNames, NSString **notes, double *timestamp, RWIProtocolJSONObject **values, RWIProtocolJSONObject **payload, int *databaseId, TestProtocolDatabaseError **sqlError, TestProtocolDatabasePrimaryColors *screenColor, NSArray/*<NSString>*/ **alternateColors, TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColor *printColor) { + Ref<InspectorObject> resultObject = InspectorObject::create(); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(alternateColors, @"alternateColors"); + if (columnNames) + resultObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray(*columnNames)); + if (notes) + resultObject->setString(ASCIILiteral("notes"), *notes); + if (timestamp) + resultObject->setDouble(ASCIILiteral("timestamp"), *timestamp); + if (values) + resultObject->setObject(ASCIILiteral("values"), [*values toInspectorObject]); + if (payload) + resultObject->setValue(ASCIILiteral("payload"), [*payload toInspectorObject]); + if (databaseId) + resultObject->setInteger(ASCIILiteral("databaseId"), *databaseId); + if (sqlError) + resultObject->setObject(ASCIILiteral("sqlError"), [*sqlError toInspectorObject]); + if (screenColor) + resultObject->setString(ASCIILiteral("screenColor"), toProtocolString(*screenColor)); + if (alternateColors) + resultObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray(*alternateColors)); + if (printColor) + resultObject->setString(ASCIILiteral("printColor"), toProtocolString(*printColor)); + backendDispatcher()->sendResponse(requestId, WTFMove(resultObject)); + }; + + int o_in_databaseId = in_databaseId; + NSString *o_in_query = in_query; + + [m_delegate executeSQLAsyncOptionalReturnValuesWithErrorCallback:errorCallback successCallback:successCallback databaseId:o_in_databaseId query:o_in_query]; +} + +void ObjCInspectorDatabaseBackendDispatcher::executeSQLSync(long requestId, int in_databaseId, const String& in_query) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^(NSArray/*<NSString>*/ *columnNames, NSString *notes, double timestamp, RWIProtocolJSONObject *values, RWIProtocolJSONObject *payload, int databaseId, TestProtocolDatabaseError *sqlError, NSArray/*<NSString>*/ *alternateColors, TestProtocolDatabasePrimaryColors screenColor, TestProtocolDatabaseExecuteSQLSyncPrintColor printColor) { + Ref<InspectorObject> resultObject = InspectorObject::create(); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(alternateColors, @"alternateColors"); + resultObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray(columnNames)); + resultObject->setString(ASCIILiteral("notes"), notes); + resultObject->setDouble(ASCIILiteral("timestamp"), timestamp); + resultObject->setObject(ASCIILiteral("values"), [values toInspectorObject]); + resultObject->setValue(ASCIILiteral("payload"), [payload toInspectorObject]); + resultObject->setInteger(ASCIILiteral("databaseId"), databaseId); + resultObject->setObject(ASCIILiteral("sqlError"), [sqlError toInspectorObject]); + resultObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray(alternateColors)); + resultObject->setString(ASCIILiteral("screenColor"), toProtocolString(screenColor)); + resultObject->setString(ASCIILiteral("printColor"), toProtocolString(printColor)); + backendDispatcher()->sendResponse(requestId, WTFMove(resultObject)); + }; + + int o_in_databaseId = in_databaseId; + NSString *o_in_query = in_query; + + [m_delegate executeSQLSyncWithErrorCallback:errorCallback successCallback:successCallback databaseId:o_in_databaseId query:o_in_query]; +} + +void ObjCInspectorDatabaseBackendDispatcher::executeSQLAsync(long requestId, int in_databaseId, const String& in_query) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^(NSArray/*<NSString>*/ *columnNames, NSString *notes, double timestamp, RWIProtocolJSONObject *values, RWIProtocolJSONObject *payload, int databaseId, TestProtocolDatabaseError *sqlError, TestProtocolDatabasePrimaryColors screenColor, NSArray/*<NSString>*/ *alternateColors, TestProtocolDatabaseExecuteSQLAsyncPrintColor printColor) { + Ref<InspectorObject> resultObject = InspectorObject::create(); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(alternateColors, @"alternateColors"); + resultObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray(columnNames)); + resultObject->setString(ASCIILiteral("notes"), notes); + resultObject->setDouble(ASCIILiteral("timestamp"), timestamp); + resultObject->setObject(ASCIILiteral("values"), [values toInspectorObject]); + resultObject->setValue(ASCIILiteral("payload"), [payload toInspectorObject]); + resultObject->setInteger(ASCIILiteral("databaseId"), databaseId); + resultObject->setObject(ASCIILiteral("sqlError"), [sqlError toInspectorObject]); + resultObject->setString(ASCIILiteral("screenColor"), toProtocolString(screenColor)); + resultObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray(alternateColors)); + resultObject->setString(ASCIILiteral("printColor"), toProtocolString(printColor)); + backendDispatcher()->sendResponse(requestId, WTFMove(resultObject)); + }; + + int o_in_databaseId = in_databaseId; + NSString *o_in_query = in_query; + + [m_delegate executeSQLAsyncWithErrorCallback:errorCallback successCallback:successCallback databaseId:o_in_databaseId query:o_in_query]; +} + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setDatabaseHandler:) id<TestProtocolDatabaseDomainHandler> databaseHandler; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolDatabaseDomainHandler> _databaseHandler; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_databaseHandler release]; + [super dealloc]; +} + +- (void)setDatabaseHandler:(id<TestProtocolDatabaseDomainHandler>)handler +{ + if (handler == _databaseHandler) + return; + + [_databaseHandler release]; + _databaseHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorDatabaseBackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<DatabaseBackendDispatcher, AlternateDatabaseBackendDispatcher>>(ASCIILiteral("Database"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolDatabaseDomainHandler>)databaseHandler +{ + return _databaseHandler; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolDatabaseError; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + +typedef NS_ENUM(NSInteger, TestProtocolDatabasePrimaryColors) { + TestProtocolDatabasePrimaryColorsRed, + TestProtocolDatabasePrimaryColorsGreen, + TestProtocolDatabasePrimaryColorsBlue, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColor) { + TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorCyan, + TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorMagenta, + TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorYellow, + TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorBlack, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColor) { + TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorCyan, + TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorMagenta, + TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorYellow, + TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorBlack, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteSQLSyncPrintColor) { + TestProtocolDatabaseExecuteSQLSyncPrintColorCyan, + TestProtocolDatabaseExecuteSQLSyncPrintColorMagenta, + TestProtocolDatabaseExecuteSQLSyncPrintColorYellow, + TestProtocolDatabaseExecuteSQLSyncPrintColorBlack, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteSQLAsyncPrintColor) { + TestProtocolDatabaseExecuteSQLAsyncPrintColorCyan, + TestProtocolDatabaseExecuteSQLAsyncPrintColorMagenta, + TestProtocolDatabaseExecuteSQLAsyncPrintColorYellow, + TestProtocolDatabaseExecuteSQLAsyncPrintColorBlack, +}; + + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseError : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithMessage:(NSString *)message code:(int)code; +/* required */ @property (nonatomic, copy) NSString *message; +/* required */ @property (nonatomic, assign) int code; +@end + +@protocol TestProtocolDatabaseDomainHandler <NSObject> +@required +- (void)executeSQLSyncOptionalReturnValuesWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)(NSArray/*<NSString>*/ **columnNames, NSString **notes, double *timestamp, RWIProtocolJSONObject **values, RWIProtocolJSONObject **payload, int *databaseId, TestProtocolDatabaseError **sqlError, TestProtocolDatabasePrimaryColors *screenColor, NSArray/*<NSString>*/ **alternateColors, TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColor *printColor))successCallback databaseId:(int)databaseId query:(NSString *)query; +- (void)executeSQLAsyncOptionalReturnValuesWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)(NSArray/*<NSString>*/ **columnNames, NSString **notes, double *timestamp, RWIProtocolJSONObject **values, RWIProtocolJSONObject **payload, int *databaseId, TestProtocolDatabaseError **sqlError, TestProtocolDatabasePrimaryColors *screenColor, NSArray/*<NSString>*/ **alternateColors, TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColor *printColor))successCallback databaseId:(int)databaseId query:(NSString *)query; +- (void)executeSQLSyncWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)(NSArray/*<NSString>*/ *columnNames, NSString *notes, double timestamp, RWIProtocolJSONObject *values, RWIProtocolJSONObject *payload, int databaseId, TestProtocolDatabaseError *sqlError, NSArray/*<NSString>*/ *alternateColors, TestProtocolDatabasePrimaryColors screenColor, TestProtocolDatabaseExecuteSQLSyncPrintColor printColor))successCallback databaseId:(int)databaseId query:(NSString *)query; +- (void)executeSQLAsyncWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)(NSArray/*<NSString>*/ *columnNames, NSString *notes, double timestamp, RWIProtocolJSONObject *values, RWIProtocolJSONObject *payload, int databaseId, TestProtocolDatabaseError *sqlError, TestProtocolDatabasePrimaryColors screenColor, NSArray/*<NSString>*/ *alternateColors, TestProtocolDatabaseExecuteSQLAsyncPrintColor printColor))successCallback databaseId:(int)databaseId query:(NSString *)query; +@end + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + +inline String toProtocolString(TestProtocolDatabasePrimaryColors value) +{ + switch(value) { + case TestProtocolDatabasePrimaryColorsRed: + return ASCIILiteral("red"); + case TestProtocolDatabasePrimaryColorsGreen: + return ASCIILiteral("green"); + case TestProtocolDatabasePrimaryColorsBlue: + return ASCIILiteral("blue"); + } +} + +template<> +inline std::optional<TestProtocolDatabasePrimaryColors> fromProtocolString(const String& value) +{ + if (value == "red") + return TestProtocolDatabasePrimaryColorsRed; + if (value == "green") + return TestProtocolDatabasePrimaryColorsGreen; + if (value == "blue") + return TestProtocolDatabasePrimaryColorsBlue; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteSQLSyncOptionalReturnValuesPrintColorBlack; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteSQLAsyncOptionalReturnValuesPrintColorBlack; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteSQLSyncPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteSQLSyncPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteSQLSyncPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteSQLSyncPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteSQLSyncPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteSQLSyncPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteSQLSyncPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteSQLSyncPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteSQLSyncPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteSQLSyncPrintColorBlack; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteSQLAsyncPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteSQLAsyncPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteSQLAsyncPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteSQLAsyncPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteSQLAsyncPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteSQLAsyncPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteSQLAsyncPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteSQLAsyncPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteSQLAsyncPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteSQLAsyncPrintColorBlack; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseDatabaseId:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parsePrimaryColors:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseColorList:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseDatabaseId:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSNumber class]); + *outValue = (NSNumber *)payload; +} + ++ (void)_parsePrimaryColors:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolDatabasePrimaryColors> result = Inspector::fromProtocolString<TestProtocolDatabasePrimaryColors>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"PrimaryColors"); + *outValue = @(result.value()); +} + ++ (void)_parseColorList:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSString>*/ class]); + *outValue = (NSArray/*<NSString>*/ *)payload; +} + ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseError alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-async-attribute.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolDatabaseError + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"message"], @"message"); + self.message = payload[@"message"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"code"], @"code"); + self.code = [payload[@"code"] integerValue]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithMessage:(NSString *)message code:(int)code +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(message, @"message"); + + self.message = message; + self.code = code; + + return self; +} + +- (void)setMessage:(NSString *)message +{ + [super setString:message forKey:@"message"]; +} + +- (NSString *)message +{ + return [super stringForKey:@"message"]; +} + +- (void)setCode:(int)code +{ + [super setInteger:code forKey:@"code"]; +} + +- (int)code +{ + return [super integerForKey:@"code"]; +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/commands-with-optional-call-return-parameters.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/commands-with-optional-call-return-parameters.json-result new file mode 100644 index 000000000..4c9e42618 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/commands-with-optional-call-return-parameters.json-result @@ -0,0 +1,1643 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Database. +InspectorBackend.registerEnum("Database.PrimaryColors", {Red: "red", Green: "green", Blue: "blue"}); +InspectorBackend.registerCommand("Database.executeAllOptionalParameters", [{"name": "columnNames", "type": "object", "optional": true}, {"name": "notes", "type": "string", "optional": true}, {"name": "timestamp", "type": "number", "optional": true}, {"name": "values", "type": "object", "optional": true}, {"name": "payload", "type": "object", "optional": true}, {"name": "databaseId", "type": "number", "optional": true}, {"name": "sqlError", "type": "object", "optional": true}, {"name": "screenColor", "type": "string", "optional": true}, {"name": "alternateColors", "type": "object", "optional": true}, {"name": "printColor", "type": "string", "optional": true}], ["columnNames", "notes", "timestamp", "values", "payload", "databaseId", "sqlError", "screenColor", "alternateColors", "printColor"]); +InspectorBackend.registerCommand("Database.executeNoOptionalParameters", [{"name": "columnNames", "type": "object", "optional": false}, {"name": "notes", "type": "string", "optional": false}, {"name": "timestamp", "type": "number", "optional": false}, {"name": "values", "type": "object", "optional": false}, {"name": "payload", "type": "object", "optional": false}, {"name": "databaseId", "type": "number", "optional": false}, {"name": "sqlError", "type": "object", "optional": false}, {"name": "screenColor", "type": "string", "optional": false}, {"name": "alternateColors", "type": "object", "optional": false}, {"name": "printColor", "type": "string", "optional": false}], ["columnNames", "notes", "timestamp", "values", "payload", "databaseId", "sqlError", "screenColor", "alternateColors", "printColor"]); +InspectorBackend.activateDomain("Database"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +class AlternateDatabaseBackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateDatabaseBackendDispatcher() { } + virtual void executeAllOptionalParameters(long callId, const Inspector::InspectorArray* in_columnNames, const String* const in_notes, const double* const in_timestamp, const Inspector::InspectorObject* in_values, const Inspector::InspectorValue* const in_payload, const int* const in_databaseId, const Inspector::InspectorObject* in_sqlError, const String* const in_screenColor, const Inspector::InspectorArray* in_alternateColors, const String* const in_printColor) = 0; + virtual void executeNoOptionalParameters(long callId, const Inspector::InspectorArray& in_columnNames, const String& in_notes, double in_timestamp, const Inspector::InspectorObject& in_values, Inspector::InspectorValue in_payload, int in_databaseId, const Inspector::InspectorObject& in_sqlError, const String& in_screenColor, const Inspector::InspectorArray& in_alternateColors, const String& in_printColor) = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +class AlternateDatabaseBackendDispatcher; +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +class DatabaseBackendDispatcherHandler { +public: + // Named after parameter 'printColor' while generating command/event executeAllOptionalParameters. + enum class PrintColor { + Cyan = 3, + Magenta = 4, + Yellow = 5, + Black = 6, + }; // enum class PrintColor + virtual void executeAllOptionalParameters(ErrorString&, const Inspector::InspectorArray* opt_in_columnNames, const String* const opt_in_notes, const double* const opt_in_timestamp, const Inspector::InspectorObject* opt_in_values, const Inspector::InspectorValue* const opt_in_payload, const int* const opt_in_databaseId, const Inspector::InspectorObject* opt_in_sqlError, const String* const opt_in_screenColor, const Inspector::InspectorArray* opt_in_alternateColors, const String* const opt_in_printColor, RefPtr<Inspector::Protocol::Array<String>>& opt_out_columnNames, Inspector::Protocol::OptOutput<String>* opt_out_notes, Inspector::Protocol::OptOutput<double>* opt_out_timestamp, Inspector::Protocol::OptOutput<Inspector::InspectorObject>* opt_out_values, Inspector::Protocol::OptOutput<Inspector::InspectorValue>* opt_out_payload, Inspector::Protocol::OptOutput<int>* opt_out_databaseId, RefPtr<Inspector::Protocol::Database::Error>& opt_out_sqlError, Inspector::Protocol::Database::PrimaryColors* opt_out_screenColor, RefPtr<Inspector::Protocol::Database::ColorList>& opt_out_alternateColors, DatabaseBackendDispatcherHandler::PrintColor* opt_out_printColor) = 0; + virtual void executeNoOptionalParameters(ErrorString&, const Inspector::InspectorArray& in_columnNames, const String& in_notes, double in_timestamp, const Inspector::InspectorObject& in_values, Inspector::InspectorValue in_payload, int in_databaseId, const Inspector::InspectorObject& in_sqlError, const String& in_screenColor, const Inspector::InspectorArray& in_alternateColors, const String& in_printColor, RefPtr<Inspector::Protocol::Array<String>>& out_columnNames, String* out_notes, double* out_timestamp, Inspector::InspectorObject* out_values, Inspector::InspectorValue* out_payload, int* out_databaseId, RefPtr<Inspector::Protocol::Database::Error>& out_sqlError, Inspector::Protocol::Database::PrimaryColors* out_screenColor, RefPtr<Inspector::Protocol::Database::ColorList>& out_alternateColors, DatabaseBackendDispatcherHandler::PrintColor* out_printColor) = 0; +protected: + virtual ~DatabaseBackendDispatcherHandler(); +}; + +class DatabaseBackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<DatabaseBackendDispatcher> create(BackendDispatcher&, DatabaseBackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void executeAllOptionalParameters(long requestId, RefPtr<InspectorObject>&& parameters); + void executeNoOptionalParameters(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateDatabaseBackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateDatabaseBackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + DatabaseBackendDispatcher(BackendDispatcher&, DatabaseBackendDispatcherHandler*); + DatabaseBackendDispatcherHandler* m_agent { nullptr }; +}; + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +DatabaseBackendDispatcherHandler::~DatabaseBackendDispatcherHandler() { } + +Ref<DatabaseBackendDispatcher> DatabaseBackendDispatcher::create(BackendDispatcher& backendDispatcher, DatabaseBackendDispatcherHandler* agent) +{ + return adoptRef(*new DatabaseBackendDispatcher(backendDispatcher, agent)); +} + +DatabaseBackendDispatcher::DatabaseBackendDispatcher(BackendDispatcher& backendDispatcher, DatabaseBackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("Database"), this); +} + +void DatabaseBackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<DatabaseBackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "executeAllOptionalParameters") + executeAllOptionalParameters(requestId, WTFMove(parameters)); + else if (method == "executeNoOptionalParameters") + executeNoOptionalParameters(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "Database", '.', method, "' was not found")); +} + +void DatabaseBackendDispatcher::executeAllOptionalParameters(long requestId, RefPtr<InspectorObject>&& parameters) +{ + bool opt_in_columnNames_valueFound = false; + RefPtr<Inspector::InspectorArray> opt_in_columnNames = m_backendDispatcher->getArray(parameters.get(), ASCIILiteral("columnNames"), &opt_in_columnNames_valueFound); + bool opt_in_notes_valueFound = false; + String opt_in_notes = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("notes"), &opt_in_notes_valueFound); + bool opt_in_timestamp_valueFound = false; + Inspector::Protocol::OptOutput<double> opt_in_timestamp = m_backendDispatcher->getDouble(parameters.get(), ASCIILiteral("timestamp"), &opt_in_timestamp_valueFound); + bool opt_in_values_valueFound = false; + RefPtr<Inspector::InspectorObject> opt_in_values = m_backendDispatcher->getObject(parameters.get(), ASCIILiteral("values"), &opt_in_values_valueFound); + bool opt_in_payload_valueFound = false; + RefPtr<Inspector::InspectorValue> opt_in_payload = m_backendDispatcher->getValue(parameters.get(), ASCIILiteral("payload"), &opt_in_payload_valueFound); + bool opt_in_databaseId_valueFound = false; + int opt_in_databaseId = m_backendDispatcher->getInteger(parameters.get(), ASCIILiteral("databaseId"), &opt_in_databaseId_valueFound); + bool opt_in_sqlError_valueFound = false; + RefPtr<Inspector::InspectorObject> opt_in_sqlError = m_backendDispatcher->getObject(parameters.get(), ASCIILiteral("sqlError"), &opt_in_sqlError_valueFound); + bool opt_in_screenColor_valueFound = false; + String opt_in_screenColor = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("screenColor"), &opt_in_screenColor_valueFound); + bool opt_in_alternateColors_valueFound = false; + RefPtr<Inspector::InspectorArray> opt_in_alternateColors = m_backendDispatcher->getArray(parameters.get(), ASCIILiteral("alternateColors"), &opt_in_alternateColors_valueFound); + bool opt_in_printColor_valueFound = false; + String opt_in_printColor = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("printColor"), &opt_in_printColor_valueFound); + if (m_backendDispatcher->hasProtocolErrors()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Some arguments of method '%s' can't be processed", "Database.executeAllOptionalParameters")); + return; + } + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->executeAllOptionalParameters(requestId, opt_in_columnNames_valueFound ? opt_in_columnNames.get() : nullptr, opt_in_notes_valueFound ? &opt_in_notes : nullptr, opt_in_timestamp_valueFound ? &opt_in_timestamp : nullptr, opt_in_values_valueFound ? opt_in_values.get() : nullptr, opt_in_payload_valueFound ? opt_in_payload.get() : nullptr, opt_in_databaseId_valueFound ? &opt_in_databaseId : nullptr, opt_in_sqlError_valueFound ? opt_in_sqlError.get() : nullptr, opt_in_screenColor_valueFound ? &opt_in_screenColor : nullptr, opt_in_alternateColors_valueFound ? opt_in_alternateColors.get() : nullptr, opt_in_printColor_valueFound ? &opt_in_printColor : nullptr); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + RefPtr<Inspector::Protocol::Array<String>> out_columnNames; + Inspector::Protocol::OptOutput<String> out_notes; + Inspector::Protocol::OptOutput<double> out_timestamp; + Inspector::Protocol::OptOutput<Inspector::InspectorObject> out_values; + Inspector::Protocol::OptOutput<Inspector::InspectorValue> out_payload; + Inspector::Protocol::OptOutput<Inspector::Protocol::Database::DatabaseId> out_databaseId; + RefPtr<Inspector::Protocol::Database::Error> out_sqlError; + Inspector::Protocol::Database::PrimaryColors out_screenColor; + RefPtr<Inspector::Protocol::Database::ColorList> out_alternateColors; + DatabaseBackendDispatcherHandler::PrintColor out_printColor; + m_agent->executeAllOptionalParameters(error, opt_in_columnNames_valueFound ? opt_in_columnNames.get() : nullptr, opt_in_notes_valueFound ? &opt_in_notes : nullptr, opt_in_timestamp_valueFound ? &opt_in_timestamp : nullptr, opt_in_values_valueFound ? opt_in_values.get() : nullptr, opt_in_payload_valueFound ? opt_in_payload.get() : nullptr, opt_in_databaseId_valueFound ? &opt_in_databaseId : nullptr, opt_in_sqlError_valueFound ? opt_in_sqlError.get() : nullptr, opt_in_screenColor_valueFound ? &opt_in_screenColor : nullptr, opt_in_alternateColors_valueFound ? opt_in_alternateColors.get() : nullptr, opt_in_printColor_valueFound ? &opt_in_printColor : nullptr, out_columnNames, &out_notes, &out_timestamp, out_values, &out_payload, &out_databaseId, out_sqlError, &out_screenColor, out_alternateColors, &out_printColor); + + if (!error.length()) { + if (out_columnNames) + result->setArray(ASCIILiteral("columnNames"), out_columnNames); + if (out_notes.isAssigned()) + result->setString(ASCIILiteral("notes"), out_notes.getValue()); + if (out_timestamp.isAssigned()) + result->setDouble(ASCIILiteral("timestamp"), out_timestamp.getValue()); + if (out_values.isAssigned()) + result->setObject(ASCIILiteral("values"), out_values.getValue()); + if (out_payload.isAssigned()) + result->setValue(ASCIILiteral("payload"), out_payload.getValue()); + if (out_databaseId.isAssigned()) + result->setInteger(ASCIILiteral("databaseId"), out_databaseId.getValue()); + if (out_sqlError) + result->setObject(ASCIILiteral("sqlError"), out_sqlError); + if (out_screenColor.isAssigned()) + result->setString(ASCIILiteral("screenColor"), out_screenColor.getValue()); + if (out_alternateColors) + result->setArray(ASCIILiteral("alternateColors"), out_alternateColors); + if (out_printColor.isAssigned()) + result->setString(ASCIILiteral("printColor"), out_printColor.getValue()); + } + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +void DatabaseBackendDispatcher::executeNoOptionalParameters(long requestId, RefPtr<InspectorObject>&& parameters) +{ + RefPtr<Inspector::InspectorArray> in_columnNames = m_backendDispatcher->getArray(parameters.get(), ASCIILiteral("columnNames"), nullptr); + String in_notes = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("notes"), nullptr); + double in_timestamp = m_backendDispatcher->getDouble(parameters.get(), ASCIILiteral("timestamp"), nullptr); + RefPtr<Inspector::InspectorObject> in_values = m_backendDispatcher->getObject(parameters.get(), ASCIILiteral("values"), nullptr); + RefPtr<Inspector::InspectorValue> in_payload = m_backendDispatcher->getValue(parameters.get(), ASCIILiteral("payload"), nullptr); + int in_databaseId = m_backendDispatcher->getInteger(parameters.get(), ASCIILiteral("databaseId"), nullptr); + RefPtr<Inspector::InspectorObject> in_sqlError = m_backendDispatcher->getObject(parameters.get(), ASCIILiteral("sqlError"), nullptr); + String in_screenColor = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("screenColor"), nullptr); + RefPtr<Inspector::InspectorArray> in_alternateColors = m_backendDispatcher->getArray(parameters.get(), ASCIILiteral("alternateColors"), nullptr); + String in_printColor = m_backendDispatcher->getString(parameters.get(), ASCIILiteral("printColor"), nullptr); + if (m_backendDispatcher->hasProtocolErrors()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Some arguments of method '%s' can't be processed", "Database.executeNoOptionalParameters")); + return; + } + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->executeNoOptionalParameters(requestId, *in_columnNames, in_notes, in_timestamp, *in_values, *in_payload, in_databaseId, *in_sqlError, in_screenColor, *in_alternateColors, in_printColor); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + RefPtr<Inspector::Protocol::Array<String>> out_columnNames; + String out_notes; + double out_timestamp; + Inspector::InspectorObject out_values; + Inspector::InspectorValue out_payload; + Inspector::Protocol::Database::DatabaseId out_databaseId; + RefPtr<Inspector::Protocol::Database::Error> out_sqlError; + Inspector::Protocol::Database::PrimaryColors out_screenColor; + RefPtr<Inspector::Protocol::Database::ColorList> out_alternateColors; + DatabaseBackendDispatcherHandler::PrintColor out_printColor; + m_agent->executeNoOptionalParameters(error, *in_columnNames, in_notes, in_timestamp, *in_values, *in_payload, in_databaseId, *in_sqlError, in_screenColor, *in_alternateColors, in_printColor, out_columnNames, &out_notes, &out_timestamp, out_values, &out_payload, &out_databaseId, out_sqlError, &out_screenColor, out_alternateColors, &out_printColor); + + if (!error.length()) { + result->setArray(ASCIILiteral("columnNames"), out_columnNames); + result->setString(ASCIILiteral("notes"), out_notes); + result->setDouble(ASCIILiteral("timestamp"), out_timestamp); + result->setObject(ASCIILiteral("values"), out_values); + result->setValue(ASCIILiteral("payload"), out_payload); + result->setInteger(ASCIILiteral("databaseId"), out_databaseId); + result->setObject(ASCIILiteral("sqlError"), out_sqlError); + result->setString(ASCIILiteral("screenColor"), Inspector::Protocol::TestHelpers::getEnumConstantValue(out_screenColor)); + result->setArray(ASCIILiteral("alternateColors"), out_alternateColors); + result->setString(ASCIILiteral("printColor"), Inspector::Protocol::TestHelpers::getEnumConstantValue(out_printColor)); + } + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Database { +class Error; +enum class PrimaryColors; +} // Database +// End of forward declarations. + + +// Typedefs. +namespace Database { +/* Unique identifier of Database object. */ +typedef int DatabaseId; +typedef Inspector::Protocol::Array<Inspector::Protocol::Database::PrimaryColors> ColorList; +} // Database +// End of typedefs. + +namespace TestHelpers { + +String getEnumConstantValue(int code); + +template<typename T> String getEnumConstantValue(T enumValue) +{ + return getEnumConstantValue(static_cast<int>(enumValue)); +} + +} // namespace TestHelpers + +namespace Database { +/* */ +enum class PrimaryColors { + Red = 0, + Green = 1, + Blue = 2, +}; // enum class PrimaryColors +/* Database error. */ +class Error : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + MessageSet = 1 << 0, + CodeSet = 1 << 1, + AllFieldsSet = (MessageSet | CodeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*Error*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class Error; + public: + + Builder<STATE | MessageSet>& setMessage(const String& value) + { + COMPILE_ASSERT(!(STATE & MessageSet), property_message_already_set); + m_result->setString(ASCIILiteral("message"), value); + return castState<MessageSet>(); + } + + Builder<STATE | CodeSet>& setCode(int value) + { + COMPILE_ASSERT(!(STATE & CodeSet), property_code_already_set); + m_result->setInteger(ASCIILiteral("code"), value); + return castState<CodeSet>(); + } + + Ref<Error> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(Error) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<Error>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<Error> result = Error::create() + * .setMessage(...) + * .setCode(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +} // Database + + + +namespace TestHelpers { + +template<typename ProtocolEnumType> +std::optional<ProtocolEnumType> parseEnumValueFromString(const String&); + +// Enums in the 'Database' Domain +template<> +std::optional<Inspector::Protocol::Database::PrimaryColors> parseEnumValueFromString<Inspector::Protocol::Database::PrimaryColors>(const String&); + +} // namespace TestHelpers + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + +namespace TestHelpers { + +static const char* const enum_constant_values[] = { + "red", + "green", + "blue", + "cyan", + "magenta", + "yellow", + "black", +}; + +String getEnumConstantValue(int code) { + return enum_constant_values[code]; +} + +// Enums in the 'Database' Domain +template<> +std::optional<Inspector::Protocol::Database::PrimaryColors> parseEnumValueFromString<Inspector::Protocol::Database::PrimaryColors>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Database::PrimaryColors::Red, + (size_t)Inspector::Protocol::Database::PrimaryColors::Green, + (size_t)Inspector::Protocol::Database::PrimaryColors::Blue, + }; + for (size_t i = 0; i < 3; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Database::PrimaryColors)constantValues[i]; + + return std::nullopt; +} + + +} // namespace TestHelpers + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolDatabaseDomainHandler; + +namespace Inspector { + + +class ObjCInspectorDatabaseBackendDispatcher final : public AlternateDatabaseBackendDispatcher { +public: + ObjCInspectorDatabaseBackendDispatcher(id<TestProtocolDatabaseDomainHandler> handler) { m_delegate = handler; } + virtual void executeAllOptionalParameters(long requestId, const Inspector::InspectorArray* in_columnNames, const String* const in_notes, const double* const in_timestamp, const Inspector::InspectorObject* in_values, const Inspector::InspectorValue* const in_payload, const int* const in_databaseId, const Inspector::InspectorObject* in_sqlError, const String* const in_screenColor, const Inspector::InspectorArray* in_alternateColors, const String* const in_printColor) override; + virtual void executeNoOptionalParameters(long requestId, const Inspector::InspectorArray& in_columnNames, const String& in_notes, double in_timestamp, const Inspector::InspectorObject& in_values, Inspector::InspectorValue in_payload, int in_databaseId, const Inspector::InspectorObject& in_sqlError, const String& in_screenColor, const Inspector::InspectorArray& in_alternateColors, const String& in_printColor) override; +private: + RetainPtr<id<TestProtocolDatabaseDomainHandler>> m_delegate; +}; + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +void ObjCInspectorDatabaseBackendDispatcher::executeAllOptionalParameters(long requestId, const Inspector::InspectorArray* in_columnNames, const String* const in_notes, const double* const in_timestamp, const Inspector::InspectorObject* in_values, const Inspector::InspectorValue* const in_payload, const int* const in_databaseId, const Inspector::InspectorObject* in_sqlError, const String* const in_screenColor, const Inspector::InspectorArray* in_alternateColors, const String* const in_printColor) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^(NSArray/*<NSString>*/ **columnNames, NSString **notes, double *timestamp, RWIProtocolJSONObject **values, RWIProtocolJSONObject **payload, int *databaseId, TestProtocolDatabaseError **sqlError, TestProtocolDatabasePrimaryColors *screenColor, NSArray/*<NSString>*/ **alternateColors, TestProtocolDatabaseExecuteAllOptionalParametersPrintColor *printColor) { + Ref<InspectorObject> resultObject = InspectorObject::create(); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(alternateColors, @"alternateColors"); + if (columnNames) + resultObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray(*columnNames)); + if (notes) + resultObject->setString(ASCIILiteral("notes"), *notes); + if (timestamp) + resultObject->setDouble(ASCIILiteral("timestamp"), *timestamp); + if (values) + resultObject->setObject(ASCIILiteral("values"), [*values toInspectorObject]); + if (payload) + resultObject->setValue(ASCIILiteral("payload"), [*payload toInspectorObject]); + if (databaseId) + resultObject->setInteger(ASCIILiteral("databaseId"), *databaseId); + if (sqlError) + resultObject->setObject(ASCIILiteral("sqlError"), [*sqlError toInspectorObject]); + if (screenColor) + resultObject->setString(ASCIILiteral("screenColor"), toProtocolString(*screenColor)); + if (alternateColors) + resultObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray(*alternateColors)); + if (printColor) + resultObject->setString(ASCIILiteral("printColor"), toProtocolString(*printColor)); + backendDispatcher()->sendResponse(requestId, WTFMove(resultObject)); + }; + + NSArray/*<NSString>*/ *o_in_columnNames; + if (in_columnNames) + o_in_columnNames = objcStringArray(in_columnNames); + NSString *o_in_notes; + if (in_notes) + o_in_notes = *in_notes; + double o_in_timestamp; + if (in_timestamp) + o_in_timestamp = *in_timestamp; + RWIProtocolJSONObject *o_in_values; + if (in_values) + o_in_values = [[[RWIProtocolJSONObject alloc] initWithInspectorObject:in_values] autorelease]; + RWIProtocolJSONObject *o_in_payload; + if (in_payload) + o_in_payload = [[[RWIProtocolJSONObject alloc] initWithInspectorObject:in_payload] autorelease]; + int o_in_databaseId; + if (in_databaseId) + o_in_databaseId = *in_databaseId; + TestProtocolDatabaseError *o_in_sqlError; + if (in_sqlError) + o_in_sqlError = [[[TestProtocolDatabaseError alloc] initWithInspectorObject:in_sqlError] autorelease]; + std::optional<TestProtocolDatabasePrimaryColors> o_in_screenColor; + if (in_screenColor) + o_in_screenColor = fromProtocolString<TestProtocolDatabasePrimaryColors>(*in_screenColor); + NSArray/*<NSString>*/ *o_in_alternateColors; + if (in_alternateColors) + o_in_alternateColors = objcStringArray(in_alternateColors); + std::optional<TestProtocolDatabaseExecuteAllOptionalParametersPrintColor> o_in_printColor; + if (in_printColor) + o_in_printColor = fromProtocolString<TestProtocolDatabaseExecuteAllOptionalParametersPrintColor>(*in_printColor); + + [m_delegate executeAllOptionalParametersWithErrorCallback:errorCallback successCallback:successCallback columnNames:(in_columnNames ? &o_in_columnNames : nil) notes:(in_notes ? &o_in_notes : nil) timestamp:(in_timestamp ? &o_in_timestamp : nil) values:(in_values ? &o_in_values : nil) payload:(in_payload ? &o_in_payload : nil) databaseId:(in_databaseId ? &o_in_databaseId : nil) sqlError:(in_sqlError ? &o_in_sqlError : nil) screenColor:(in_screenColor ? &o_in_screenColor : nil) alternateColors:(in_alternateColors ? &o_in_alternateColors : nil) printColor:(in_printColor ? &o_in_printColor : nil)]; +} + +void ObjCInspectorDatabaseBackendDispatcher::executeNoOptionalParameters(long requestId, const Inspector::InspectorArray& in_columnNames, const String& in_notes, double in_timestamp, const Inspector::InspectorObject& in_values, Inspector::InspectorValue in_payload, int in_databaseId, const Inspector::InspectorObject& in_sqlError, const String& in_screenColor, const Inspector::InspectorArray& in_alternateColors, const String& in_printColor) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^(NSArray/*<NSString>*/ *columnNames, NSString *notes, double timestamp, RWIProtocolJSONObject *values, RWIProtocolJSONObject *payload, int databaseId, TestProtocolDatabaseError *sqlError, TestProtocolDatabasePrimaryColors screenColor, NSArray/*<NSString>*/ *alternateColors, TestProtocolDatabaseExecuteNoOptionalParametersPrintColor printColor) { + Ref<InspectorObject> resultObject = InspectorObject::create(); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(alternateColors, @"alternateColors"); + resultObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray(columnNames)); + resultObject->setString(ASCIILiteral("notes"), notes); + resultObject->setDouble(ASCIILiteral("timestamp"), timestamp); + resultObject->setObject(ASCIILiteral("values"), [values toInspectorObject]); + resultObject->setValue(ASCIILiteral("payload"), [payload toInspectorObject]); + resultObject->setInteger(ASCIILiteral("databaseId"), databaseId); + resultObject->setObject(ASCIILiteral("sqlError"), [sqlError toInspectorObject]); + resultObject->setString(ASCIILiteral("screenColor"), toProtocolString(screenColor)); + resultObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray(alternateColors)); + resultObject->setString(ASCIILiteral("printColor"), toProtocolString(printColor)); + backendDispatcher()->sendResponse(requestId, WTFMove(resultObject)); + }; + + NSArray/*<NSString>*/ *o_in_columnNames = objcStringArray(&in_columnNames); + NSString *o_in_notes = in_notes; + double o_in_timestamp = in_timestamp; + RWIProtocolJSONObject *o_in_values = [[[RWIProtocolJSONObject alloc] initWithInspectorObject:&in_values] autorelease]; + RWIProtocolJSONObject *o_in_payload = [[[RWIProtocolJSONObject alloc] initWithInspectorObject:&in_payload] autorelease]; + int o_in_databaseId = in_databaseId; + TestProtocolDatabaseError *o_in_sqlError = [[[TestProtocolDatabaseError alloc] initWithInspectorObject:&in_sqlError] autorelease]; + std::optional<TestProtocolDatabasePrimaryColors> o_in_screenColor = fromProtocolString<TestProtocolDatabasePrimaryColors>(in_screenColor); + if (!o_in_screenColor) { + backendDispatcher()->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Parameter '%s' of method '%s' cannot be processed", "screenColor", "Database.executeNoOptionalParameters")); + return; + } + NSArray/*<NSString>*/ *o_in_alternateColors = objcStringArray(&in_alternateColors); + std::optional<TestProtocolDatabaseExecuteNoOptionalParametersPrintColor> o_in_printColor = fromProtocolString<TestProtocolDatabaseExecuteNoOptionalParametersPrintColor>(in_printColor); + if (!o_in_printColor) { + backendDispatcher()->reportProtocolError(BackendDispatcher::InvalidParams, String::format("Parameter '%s' of method '%s' cannot be processed", "printColor", "Database.executeNoOptionalParameters")); + return; + } + + [m_delegate executeNoOptionalParametersWithErrorCallback:errorCallback successCallback:successCallback columnNames:o_in_columnNames notes:o_in_notes timestamp:o_in_timestamp values:o_in_values payload:o_in_payload databaseId:o_in_databaseId sqlError:o_in_sqlError screenColor:o_in_screenColor.value() alternateColors:o_in_alternateColors printColor:o_in_printColor.value()]; +} + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setDatabaseHandler:) id<TestProtocolDatabaseDomainHandler> databaseHandler; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolDatabaseDomainHandler> _databaseHandler; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_databaseHandler release]; + [super dealloc]; +} + +- (void)setDatabaseHandler:(id<TestProtocolDatabaseDomainHandler>)handler +{ + if (handler == _databaseHandler) + return; + + [_databaseHandler release]; + _databaseHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorDatabaseBackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<DatabaseBackendDispatcher, AlternateDatabaseBackendDispatcher>>(ASCIILiteral("Database"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolDatabaseDomainHandler>)databaseHandler +{ + return _databaseHandler; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolDatabaseError; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + +typedef NS_ENUM(NSInteger, TestProtocolDatabasePrimaryColors) { + TestProtocolDatabasePrimaryColorsRed, + TestProtocolDatabasePrimaryColorsGreen, + TestProtocolDatabasePrimaryColorsBlue, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteAllOptionalParametersPrintColor) { + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorCyan, + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorMagenta, + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorYellow, + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorBlack, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteAllOptionalParametersPrintColor) { + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorCyan, + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorMagenta, + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorYellow, + TestProtocolDatabaseExecuteAllOptionalParametersPrintColorBlack, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteNoOptionalParametersPrintColor) { + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorCyan, + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorMagenta, + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorYellow, + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorBlack, +}; + +typedef NS_ENUM(NSInteger, TestProtocolDatabaseExecuteNoOptionalParametersPrintColor) { + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorCyan, + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorMagenta, + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorYellow, + TestProtocolDatabaseExecuteNoOptionalParametersPrintColorBlack, +}; + + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseError : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithMessage:(NSString *)message code:(int)code; +/* required */ @property (nonatomic, copy) NSString *message; +/* required */ @property (nonatomic, assign) int code; +@end + +@protocol TestProtocolDatabaseDomainHandler <NSObject> +@required +- (void)executeAllOptionalParametersWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)(NSArray/*<NSString>*/ **columnNames, NSString **notes, double *timestamp, RWIProtocolJSONObject **values, RWIProtocolJSONObject **payload, int *databaseId, TestProtocolDatabaseError **sqlError, TestProtocolDatabasePrimaryColors *screenColor, NSArray/*<NSString>*/ **alternateColors, TestProtocolDatabaseExecuteAllOptionalParametersPrintColor *printColor))successCallback columnNames:(NSArray/*<NSString>*/ **)columnNames notes:(NSString **)notes timestamp:(double *)timestamp values:(RWIProtocolJSONObject **)values payload:(RWIProtocolJSONObject **)payload databaseId:(int *)databaseId sqlError:(TestProtocolDatabaseError **)sqlError screenColor:(TestProtocolDatabasePrimaryColors *)screenColor alternateColors:(NSArray/*<NSString>*/ **)alternateColors printColor:(TestProtocolDatabaseExecuteAllOptionalParametersPrintColor *)printColor; +- (void)executeNoOptionalParametersWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)(NSArray/*<NSString>*/ *columnNames, NSString *notes, double timestamp, RWIProtocolJSONObject *values, RWIProtocolJSONObject *payload, int databaseId, TestProtocolDatabaseError *sqlError, TestProtocolDatabasePrimaryColors screenColor, NSArray/*<NSString>*/ *alternateColors, TestProtocolDatabaseExecuteNoOptionalParametersPrintColor printColor))successCallback columnNames:(NSArray/*<NSString>*/ *)columnNames notes:(NSString *)notes timestamp:(double)timestamp values:(RWIProtocolJSONObject *)values payload:(RWIProtocolJSONObject *)payload databaseId:(int)databaseId sqlError:(TestProtocolDatabaseError *)sqlError screenColor:(TestProtocolDatabasePrimaryColors)screenColor alternateColors:(NSArray/*<NSString>*/ *)alternateColors printColor:(TestProtocolDatabaseExecuteNoOptionalParametersPrintColor)printColor; +@end + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + +inline String toProtocolString(TestProtocolDatabasePrimaryColors value) +{ + switch(value) { + case TestProtocolDatabasePrimaryColorsRed: + return ASCIILiteral("red"); + case TestProtocolDatabasePrimaryColorsGreen: + return ASCIILiteral("green"); + case TestProtocolDatabasePrimaryColorsBlue: + return ASCIILiteral("blue"); + } +} + +template<> +inline std::optional<TestProtocolDatabasePrimaryColors> fromProtocolString(const String& value) +{ + if (value == "red") + return TestProtocolDatabasePrimaryColorsRed; + if (value == "green") + return TestProtocolDatabasePrimaryColorsGreen; + if (value == "blue") + return TestProtocolDatabasePrimaryColorsBlue; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteAllOptionalParametersPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteAllOptionalParametersPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorBlack; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteAllOptionalParametersPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteAllOptionalParametersPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteAllOptionalParametersPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteAllOptionalParametersPrintColorBlack; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteNoOptionalParametersPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteNoOptionalParametersPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorBlack; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolDatabaseExecuteNoOptionalParametersPrintColor value) +{ + switch(value) { + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorCyan: + return ASCIILiteral("cyan"); + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorMagenta: + return ASCIILiteral("magenta"); + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorYellow: + return ASCIILiteral("yellow"); + case TestProtocolDatabaseExecuteNoOptionalParametersPrintColorBlack: + return ASCIILiteral("black"); + } +} + +template<> +inline std::optional<TestProtocolDatabaseExecuteNoOptionalParametersPrintColor> fromProtocolString(const String& value) +{ + if (value == "cyan") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorCyan; + if (value == "magenta") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorMagenta; + if (value == "yellow") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorYellow; + if (value == "black") + return TestProtocolDatabaseExecuteNoOptionalParametersPrintColorBlack; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseDatabaseId:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parsePrimaryColors:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseColorList:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseDatabaseId:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSNumber class]); + *outValue = (NSNumber *)payload; +} + ++ (void)_parsePrimaryColors:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolDatabasePrimaryColors> result = Inspector::fromProtocolString<TestProtocolDatabasePrimaryColors>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"PrimaryColors"); + *outValue = @(result.value()); +} + ++ (void)_parseColorList:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSString>*/ class]); + *outValue = (NSArray/*<NSString>*/ *)payload; +} + ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseError alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from commands-with-optional-call-return-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolDatabaseError + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"message"], @"message"); + self.message = payload[@"message"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"code"], @"code"); + self.code = [payload[@"code"] integerValue]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithMessage:(NSString *)message code:(int)code +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(message, @"message"); + + self.message = message; + self.code = code; + + return self; +} + +- (void)setMessage:(NSString *)message +{ + [super setString:message forKey:@"message"]; +} + +- (NSString *)message +{ + return [super stringForKey:@"message"]; +} + +- (void)setCode:(int)code +{ + [super setInteger:code forKey:@"code"]; +} + +- (int)code +{ + return [super integerForKey:@"code"]; +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/definitions-with-mac-platform.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/definitions-with-mac-platform.json-result new file mode 100644 index 000000000..d9cec9c61 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/definitions-with-mac-platform.json-result @@ -0,0 +1,866 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + + + + + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + + + + + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from definitions-with-mac-platform.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/domain-availability.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/domain-availability.json-result new file mode 100644 index 000000000..0c4c30499 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/domain-availability.json-result @@ -0,0 +1,1120 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// DomainA. +InspectorBackend.registerCommand("DomainA.enable", [], []); +InspectorBackend.activateDomain("DomainA", "web"); + +// DomainB. +InspectorBackend.registerCommand("DomainB.enable", [], []); +InspectorBackend.activateDomain("DomainB"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +class AlternateDomainABackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateDomainABackendDispatcher() { } + virtual void enable(long callId) = 0; +}; +class AlternateDomainBBackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateDomainBBackendDispatcher() { } + virtual void enable(long callId) = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +class AlternateDomainABackendDispatcher; +class AlternateDomainBBackendDispatcher; +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +class DomainABackendDispatcherHandler { +public: + virtual void enable(ErrorString&) = 0; +protected: + virtual ~DomainABackendDispatcherHandler(); +}; + +class DomainBBackendDispatcherHandler { +public: + virtual void enable(ErrorString&) = 0; +protected: + virtual ~DomainBBackendDispatcherHandler(); +}; + +class DomainABackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<DomainABackendDispatcher> create(BackendDispatcher&, DomainABackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void enable(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateDomainABackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateDomainABackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + DomainABackendDispatcher(BackendDispatcher&, DomainABackendDispatcherHandler*); + DomainABackendDispatcherHandler* m_agent { nullptr }; +}; + +class DomainBBackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<DomainBBackendDispatcher> create(BackendDispatcher&, DomainBBackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void enable(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateDomainBBackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateDomainBBackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + DomainBBackendDispatcher(BackendDispatcher&, DomainBBackendDispatcherHandler*); + DomainBBackendDispatcherHandler* m_agent { nullptr }; +}; + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +DomainABackendDispatcherHandler::~DomainABackendDispatcherHandler() { } +DomainBBackendDispatcherHandler::~DomainBBackendDispatcherHandler() { } + +Ref<DomainABackendDispatcher> DomainABackendDispatcher::create(BackendDispatcher& backendDispatcher, DomainABackendDispatcherHandler* agent) +{ + return adoptRef(*new DomainABackendDispatcher(backendDispatcher, agent)); +} + +DomainABackendDispatcher::DomainABackendDispatcher(BackendDispatcher& backendDispatcher, DomainABackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("DomainA"), this); +} + +void DomainABackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<DomainABackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "enable") + enable(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "DomainA", '.', method, "' was not found")); +} + +void DomainABackendDispatcher::enable(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->enable(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->enable(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +Ref<DomainBBackendDispatcher> DomainBBackendDispatcher::create(BackendDispatcher& backendDispatcher, DomainBBackendDispatcherHandler* agent) +{ + return adoptRef(*new DomainBBackendDispatcher(backendDispatcher, agent)); +} + +DomainBBackendDispatcher::DomainBBackendDispatcher(BackendDispatcher& backendDispatcher, DomainBBackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("DomainB"), this); +} + +void DomainBBackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<DomainBBackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "enable") + enable(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "DomainB", '.', method, "' was not found")); +} + +void DomainBBackendDispatcher::enable(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->enable(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->enable(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + + + + + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolDomainADomainHandler; +@protocol TestProtocolDomainBDomainHandler; + +namespace Inspector { + + +class ObjCInspectorDomainABackendDispatcher final : public AlternateDomainABackendDispatcher { +public: + ObjCInspectorDomainABackendDispatcher(id<TestProtocolDomainADomainHandler> handler) { m_delegate = handler; } + virtual void enable(long requestId) override; +private: + RetainPtr<id<TestProtocolDomainADomainHandler>> m_delegate; +}; + +class ObjCInspectorDomainBBackendDispatcher final : public AlternateDomainBBackendDispatcher { +public: + ObjCInspectorDomainBBackendDispatcher(id<TestProtocolDomainBDomainHandler> handler) { m_delegate = handler; } + virtual void enable(long requestId) override; +private: + RetainPtr<id<TestProtocolDomainBDomainHandler>> m_delegate; +}; + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +void ObjCInspectorDomainABackendDispatcher::enable(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate enableWithErrorCallback:errorCallback successCallback:successCallback]; +} + + +void ObjCInspectorDomainBBackendDispatcher::enable(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate enableWithErrorCallback:errorCallback successCallback:successCallback]; +} + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setDomainAHandler:) id<TestProtocolDomainADomainHandler> domainAHandler; +@property (nonatomic, retain, setter=setDomainBHandler:) id<TestProtocolDomainBDomainHandler> domainBHandler; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolDomainADomainHandler> _domainAHandler; + id<TestProtocolDomainBDomainHandler> _domainBHandler; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_domainAHandler release]; + [_domainBHandler release]; + [super dealloc]; +} + +- (void)setDomainAHandler:(id<TestProtocolDomainADomainHandler>)handler +{ + if (handler == _domainAHandler) + return; + + [_domainAHandler release]; + _domainAHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorDomainABackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<DomainABackendDispatcher, AlternateDomainABackendDispatcher>>(ASCIILiteral("DomainA"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolDomainADomainHandler>)domainAHandler +{ + return _domainAHandler; +} + +- (void)setDomainBHandler:(id<TestProtocolDomainBDomainHandler>)handler +{ + if (handler == _domainBHandler) + return; + + [_domainBHandler release]; + _domainBHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorDomainBBackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<DomainBBackendDispatcher, AlternateDomainBBackendDispatcher>>(ASCIILiteral("DomainB"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolDomainBDomainHandler>)domainBHandler +{ + return _domainBHandler; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + + +@protocol TestProtocolDomainADomainHandler <NSObject> +@required +- (void)enableWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + +@protocol TestProtocolDomainBDomainHandler <NSObject> +@required +- (void)enableWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + + + + + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domain-availability.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/domains-with-varying-command-sizes.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/domains-with-varying-command-sizes.json-result new file mode 100644 index 000000000..e9afc2a18 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/domains-with-varying-command-sizes.json-result @@ -0,0 +1,1399 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Network1. +InspectorBackend.registerCommand("Network1.loadResource1", [], []); +InspectorBackend.activateDomain("Network1"); + +// Network3. +InspectorBackend.registerCommand("Network3.loadResource1", [], []); +InspectorBackend.registerCommand("Network3.loadResource2", [], []); +InspectorBackend.registerCommand("Network3.loadResource3", [], []); +InspectorBackend.registerCommand("Network3.loadResource4", [], []); +InspectorBackend.registerCommand("Network3.loadResource5", [], []); +InspectorBackend.registerCommand("Network3.loadResource6", [], []); +InspectorBackend.registerCommand("Network3.loadResource7", [], []); +InspectorBackend.activateDomain("Network3"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +class AlternateNetwork1BackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateNetwork1BackendDispatcher() { } + virtual void loadResource1(long callId) = 0; +}; +class AlternateNetwork3BackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateNetwork3BackendDispatcher() { } + virtual void loadResource1(long callId) = 0; + virtual void loadResource2(long callId) = 0; + virtual void loadResource3(long callId) = 0; + virtual void loadResource4(long callId) = 0; + virtual void loadResource5(long callId) = 0; + virtual void loadResource6(long callId) = 0; + virtual void loadResource7(long callId) = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +class AlternateNetwork1BackendDispatcher; +class AlternateNetwork3BackendDispatcher; +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +class Network1BackendDispatcherHandler { +public: + virtual void loadResource1(ErrorString&) = 0; +protected: + virtual ~Network1BackendDispatcherHandler(); +}; + +class Network3BackendDispatcherHandler { +public: + virtual void loadResource1(ErrorString&) = 0; + virtual void loadResource2(ErrorString&) = 0; + virtual void loadResource3(ErrorString&) = 0; + virtual void loadResource4(ErrorString&) = 0; + virtual void loadResource5(ErrorString&) = 0; + virtual void loadResource6(ErrorString&) = 0; + virtual void loadResource7(ErrorString&) = 0; +protected: + virtual ~Network3BackendDispatcherHandler(); +}; + +class Network1BackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<Network1BackendDispatcher> create(BackendDispatcher&, Network1BackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void loadResource1(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateNetwork1BackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateNetwork1BackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + Network1BackendDispatcher(BackendDispatcher&, Network1BackendDispatcherHandler*); + Network1BackendDispatcherHandler* m_agent { nullptr }; +}; + +class Network3BackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<Network3BackendDispatcher> create(BackendDispatcher&, Network3BackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void loadResource1(long requestId, RefPtr<InspectorObject>&& parameters); + void loadResource2(long requestId, RefPtr<InspectorObject>&& parameters); + void loadResource3(long requestId, RefPtr<InspectorObject>&& parameters); + void loadResource4(long requestId, RefPtr<InspectorObject>&& parameters); + void loadResource5(long requestId, RefPtr<InspectorObject>&& parameters); + void loadResource6(long requestId, RefPtr<InspectorObject>&& parameters); + void loadResource7(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateNetwork3BackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateNetwork3BackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + Network3BackendDispatcher(BackendDispatcher&, Network3BackendDispatcherHandler*); + Network3BackendDispatcherHandler* m_agent { nullptr }; +}; + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +Network1BackendDispatcherHandler::~Network1BackendDispatcherHandler() { } +Network3BackendDispatcherHandler::~Network3BackendDispatcherHandler() { } + +Ref<Network1BackendDispatcher> Network1BackendDispatcher::create(BackendDispatcher& backendDispatcher, Network1BackendDispatcherHandler* agent) +{ + return adoptRef(*new Network1BackendDispatcher(backendDispatcher, agent)); +} + +Network1BackendDispatcher::Network1BackendDispatcher(BackendDispatcher& backendDispatcher, Network1BackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("Network1"), this); +} + +void Network1BackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<Network1BackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "loadResource1") + loadResource1(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "Network1", '.', method, "' was not found")); +} + +void Network1BackendDispatcher::loadResource1(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource1(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource1(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +Ref<Network3BackendDispatcher> Network3BackendDispatcher::create(BackendDispatcher& backendDispatcher, Network3BackendDispatcherHandler* agent) +{ + return adoptRef(*new Network3BackendDispatcher(backendDispatcher, agent)); +} + +Network3BackendDispatcher::Network3BackendDispatcher(BackendDispatcher& backendDispatcher, Network3BackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("Network3"), this); +} + +void Network3BackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<Network3BackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + typedef void (Network3BackendDispatcher::*CallHandler)(long requestId, RefPtr<InspectorObject>&& message); + typedef HashMap<String, CallHandler> DispatchMap; + static NeverDestroyed<DispatchMap> dispatchMap; + if (dispatchMap.get().isEmpty()) { + static const struct MethodTable { + const char* name; + CallHandler handler; + } commands[] = { + { "loadResource1", &Network3BackendDispatcher::loadResource1 }, + { "loadResource2", &Network3BackendDispatcher::loadResource2 }, + { "loadResource3", &Network3BackendDispatcher::loadResource3 }, + { "loadResource4", &Network3BackendDispatcher::loadResource4 }, + { "loadResource5", &Network3BackendDispatcher::loadResource5 }, + { "loadResource6", &Network3BackendDispatcher::loadResource6 }, + { "loadResource7", &Network3BackendDispatcher::loadResource7 }, + }; + size_t length = WTF_ARRAY_LENGTH(commands); + for (size_t i = 0; i < length; ++i) + dispatchMap.get().add(commands[i].name, commands[i].handler); + } + + auto findResult = dispatchMap.get().find(method); + if (findResult == dispatchMap.get().end()) { + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "Network3", '.', method, "' was not found")); + return; + } + + ((*this).*findResult->value)(requestId, WTFMove(parameters)); +} + +void Network3BackendDispatcher::loadResource1(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource1(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource1(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +void Network3BackendDispatcher::loadResource2(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource2(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource2(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +void Network3BackendDispatcher::loadResource3(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource3(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource3(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +void Network3BackendDispatcher::loadResource4(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource4(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource4(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +void Network3BackendDispatcher::loadResource5(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource5(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource5(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +void Network3BackendDispatcher::loadResource6(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource6(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource6(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +void Network3BackendDispatcher::loadResource7(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource7(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource7(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + + + +// Typedefs. +namespace Network2 { +/* Unique loader identifier. */ +typedef String LoaderId; +} // Network2 +// End of typedefs. + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolNetwork1DomainHandler; +@protocol TestProtocolNetwork3DomainHandler; + +namespace Inspector { + + +class ObjCInspectorNetwork1BackendDispatcher final : public AlternateNetwork1BackendDispatcher { +public: + ObjCInspectorNetwork1BackendDispatcher(id<TestProtocolNetwork1DomainHandler> handler) { m_delegate = handler; } + virtual void loadResource1(long requestId) override; +private: + RetainPtr<id<TestProtocolNetwork1DomainHandler>> m_delegate; +}; + +class ObjCInspectorNetwork3BackendDispatcher final : public AlternateNetwork3BackendDispatcher { +public: + ObjCInspectorNetwork3BackendDispatcher(id<TestProtocolNetwork3DomainHandler> handler) { m_delegate = handler; } + virtual void loadResource1(long requestId) override; + virtual void loadResource2(long requestId) override; + virtual void loadResource3(long requestId) override; + virtual void loadResource4(long requestId) override; + virtual void loadResource5(long requestId) override; + virtual void loadResource6(long requestId) override; + virtual void loadResource7(long requestId) override; +private: + RetainPtr<id<TestProtocolNetwork3DomainHandler>> m_delegate; +}; + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +void ObjCInspectorNetwork1BackendDispatcher::loadResource1(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource1WithErrorCallback:errorCallback successCallback:successCallback]; +} + + +void ObjCInspectorNetwork3BackendDispatcher::loadResource1(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource1WithErrorCallback:errorCallback successCallback:successCallback]; +} + +void ObjCInspectorNetwork3BackendDispatcher::loadResource2(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource2WithErrorCallback:errorCallback successCallback:successCallback]; +} + +void ObjCInspectorNetwork3BackendDispatcher::loadResource3(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource3WithErrorCallback:errorCallback successCallback:successCallback]; +} + +void ObjCInspectorNetwork3BackendDispatcher::loadResource4(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource4WithErrorCallback:errorCallback successCallback:successCallback]; +} + +void ObjCInspectorNetwork3BackendDispatcher::loadResource5(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource5WithErrorCallback:errorCallback successCallback:successCallback]; +} + +void ObjCInspectorNetwork3BackendDispatcher::loadResource6(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource6WithErrorCallback:errorCallback successCallback:successCallback]; +} + +void ObjCInspectorNetwork3BackendDispatcher::loadResource7(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResource7WithErrorCallback:errorCallback successCallback:successCallback]; +} + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setNetwork1Handler:) id<TestProtocolNetwork1DomainHandler> network1Handler; +@property (nonatomic, retain, setter=setNetwork3Handler:) id<TestProtocolNetwork3DomainHandler> network3Handler; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolNetwork1DomainHandler> _network1Handler; + id<TestProtocolNetwork3DomainHandler> _network3Handler; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_network1Handler release]; + [_network3Handler release]; + [super dealloc]; +} + +- (void)setNetwork1Handler:(id<TestProtocolNetwork1DomainHandler>)handler +{ + if (handler == _network1Handler) + return; + + [_network1Handler release]; + _network1Handler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorNetwork1BackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<Network1BackendDispatcher, AlternateNetwork1BackendDispatcher>>(ASCIILiteral("Network1"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolNetwork1DomainHandler>)network1Handler +{ + return _network1Handler; +} + +- (void)setNetwork3Handler:(id<TestProtocolNetwork3DomainHandler>)handler +{ + if (handler == _network3Handler) + return; + + [_network3Handler release]; + _network3Handler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorNetwork3BackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<Network3BackendDispatcher, AlternateNetwork3BackendDispatcher>>(ASCIILiteral("Network3"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolNetwork3DomainHandler>)network3Handler +{ + return _network3Handler; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + + +@protocol TestProtocolNetwork1DomainHandler <NSObject> +@required +- (void)loadResource1WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + +@protocol TestProtocolNetwork3DomainHandler <NSObject> +@required +- (void)loadResource1WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +- (void)loadResource2WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +- (void)loadResource3WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +- (void)loadResource4WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +- (void)loadResource5WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +- (void)loadResource6WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +- (void)loadResource7WithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (Network2Domain) + ++ (void)_parseLoaderId:(NSString **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (Network2Domain) + ++ (void)_parseLoaderId:(NSString **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + *outValue = (NSString *)payload; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from domains-with-varying-command-sizes.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/enum-values.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/enum-values.json-result new file mode 100644 index 000000000..d2a01c84e --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/enum-values.json-result @@ -0,0 +1,1208 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// TypeDomain. +InspectorBackend.registerEnum("TypeDomain.TypeDomainEnum", {Shared: "shared", Red: "red", Green: "green", Blue: "blue"}); + +// CommandDomain. +InspectorBackend.registerCommand("CommandDomain.commandWithEnumReturnValue", [], ["returnValue"]); +InspectorBackend.activateDomain("CommandDomain"); + +// EventDomain. +InspectorBackend.registerEventDomainDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "EventDomain"); +InspectorBackend.registerEnum("EventDomain.EventWithEnumParameterParameter", {Shared: "shared", Black: "black", White: "white"}); +InspectorBackend.registerEvent("EventDomain.eventWithEnumParameter", ["parameter"]); +InspectorBackend.activateDomain("EventDomain"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +class AlternateCommandDomainBackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateCommandDomainBackendDispatcher() { } + virtual void commandWithEnumReturnValue(long callId) = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +class AlternateCommandDomainBackendDispatcher; +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +class CommandDomainBackendDispatcherHandler { +public: + // Named after parameter 'returnValue' while generating command/event commandWithEnumReturnValue. + enum class ReturnValue { + Shared = 0, + Cyan = 6, + Magenta = 7, + Yellow = 8, + }; // enum class ReturnValue + virtual void commandWithEnumReturnValue(ErrorString&, CommandDomainBackendDispatcherHandler::ReturnValue* out_returnValue) = 0; +protected: + virtual ~CommandDomainBackendDispatcherHandler(); +}; + +class CommandDomainBackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<CommandDomainBackendDispatcher> create(BackendDispatcher&, CommandDomainBackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void commandWithEnumReturnValue(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateCommandDomainBackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateCommandDomainBackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + CommandDomainBackendDispatcher(BackendDispatcher&, CommandDomainBackendDispatcherHandler*); + CommandDomainBackendDispatcherHandler* m_agent { nullptr }; +}; + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +CommandDomainBackendDispatcherHandler::~CommandDomainBackendDispatcherHandler() { } + +Ref<CommandDomainBackendDispatcher> CommandDomainBackendDispatcher::create(BackendDispatcher& backendDispatcher, CommandDomainBackendDispatcherHandler* agent) +{ + return adoptRef(*new CommandDomainBackendDispatcher(backendDispatcher, agent)); +} + +CommandDomainBackendDispatcher::CommandDomainBackendDispatcher(BackendDispatcher& backendDispatcher, CommandDomainBackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("CommandDomain"), this); +} + +void CommandDomainBackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<CommandDomainBackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "commandWithEnumReturnValue") + commandWithEnumReturnValue(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "CommandDomain", '.', method, "' was not found")); +} + +void CommandDomainBackendDispatcher::commandWithEnumReturnValue(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->commandWithEnumReturnValue(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + CommandDomainBackendDispatcherHandler::ReturnValue out_returnValue; + m_agent->commandWithEnumReturnValue(error, &out_returnValue); + + if (!error.length()) + result->setString(ASCIILiteral("returnValue"), Inspector::Protocol::TestHelpers::getEnumConstantValue(out_returnValue)); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +class EventDomainFrontendDispatcher { +public: + EventDomainFrontendDispatcher(FrontendRouter& frontendRouter) : m_frontendRouter(frontendRouter) { } + // Named after parameter 'parameter' while generating command/event eventWithEnumParameter. + enum class Parameter { + Shared = 0, + Black = 4, + White = 5, + }; // enum class Parameter + void eventWithEnumParameter(Parameter parameter); +private: + FrontendRouter& m_frontendRouter; +}; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +void EventDomainFrontendDispatcher::eventWithEnumParameter(Parameter parameter) +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("EventDomain.eventWithEnumParameter")); + Ref<InspectorObject> paramsObject = InspectorObject::create(); + paramsObject->setString(ASCIILiteral("parameter"), Inspector::Protocol::TestHelpers::getEnumConstantValue(parameter)); + jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject)); + + m_frontendRouter.sendEvent(jsonMessage->toJSONString()); +} + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace TypeDomain { +enum class TypeDomainEnum; +} // TypeDomain +// End of forward declarations. + + + + +namespace TestHelpers { + +String getEnumConstantValue(int code); + +template<typename T> String getEnumConstantValue(T enumValue) +{ + return getEnumConstantValue(static_cast<int>(enumValue)); +} + +} // namespace TestHelpers + +namespace TypeDomain { +/* */ +enum class TypeDomainEnum { + Shared = 0, + Red = 1, + Green = 2, + Blue = 3, +}; // enum class TypeDomainEnum +} // TypeDomain + + + +namespace TestHelpers { + +template<typename ProtocolEnumType> +std::optional<ProtocolEnumType> parseEnumValueFromString(const String&); + +// Enums in the 'TypeDomain' Domain +template<> +std::optional<Inspector::Protocol::TypeDomain::TypeDomainEnum> parseEnumValueFromString<Inspector::Protocol::TypeDomain::TypeDomainEnum>(const String&); + +} // namespace TestHelpers + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + +namespace TestHelpers { + +static const char* const enum_constant_values[] = { + "shared", + "red", + "green", + "blue", + "black", + "white", + "cyan", + "magenta", + "yellow", +}; + +String getEnumConstantValue(int code) { + return enum_constant_values[code]; +} + +// Enums in the 'TypeDomain' Domain +template<> +std::optional<Inspector::Protocol::TypeDomain::TypeDomainEnum> parseEnumValueFromString<Inspector::Protocol::TypeDomain::TypeDomainEnum>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::TypeDomain::TypeDomainEnum::Shared, + (size_t)Inspector::Protocol::TypeDomain::TypeDomainEnum::Red, + (size_t)Inspector::Protocol::TypeDomain::TypeDomainEnum::Green, + (size_t)Inspector::Protocol::TypeDomain::TypeDomainEnum::Blue, + }; + for (size_t i = 0; i < 4; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::TypeDomain::TypeDomainEnum)constantValues[i]; + + return std::nullopt; +} + + +} // namespace TestHelpers + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolCommandDomainDomainHandler; + +namespace Inspector { + + +class ObjCInspectorCommandDomainBackendDispatcher final : public AlternateCommandDomainBackendDispatcher { +public: + ObjCInspectorCommandDomainBackendDispatcher(id<TestProtocolCommandDomainDomainHandler> handler) { m_delegate = handler; } + virtual void commandWithEnumReturnValue(long requestId) override; +private: + RetainPtr<id<TestProtocolCommandDomainDomainHandler>> m_delegate; +}; + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +void ObjCInspectorCommandDomainBackendDispatcher::commandWithEnumReturnValue(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^(TestProtocolCommandDomainCommandWithEnumReturnValueReturnValue returnValue) { + Ref<InspectorObject> resultObject = InspectorObject::create(); + resultObject->setString(ASCIILiteral("returnValue"), toProtocolString(returnValue)); + backendDispatcher()->sendResponse(requestId, WTFMove(resultObject)); + }; + + [m_delegate commandWithEnumReturnValueWithErrorCallback:errorCallback successCallback:successCallback]; +} + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setCommandDomainHandler:) id<TestProtocolCommandDomainDomainHandler> commandDomainHandler; +@property (nonatomic, readonly) TestProtocolEventDomainDomainEventDispatcher *eventDomainEventDispatcher; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolCommandDomainDomainHandler> _commandDomainHandler; + TestProtocolEventDomainDomainEventDispatcher *_eventDomainEventDispatcher; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_commandDomainHandler release]; + [_eventDomainEventDispatcher release]; + [super dealloc]; +} + +- (void)setCommandDomainHandler:(id<TestProtocolCommandDomainDomainHandler>)handler +{ + if (handler == _commandDomainHandler) + return; + + [_commandDomainHandler release]; + _commandDomainHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorCommandDomainBackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<CommandDomainBackendDispatcher, AlternateCommandDomainBackendDispatcher>>(ASCIILiteral("CommandDomain"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolCommandDomainDomainHandler>)commandDomainHandler +{ + return _commandDomainHandler; +} + +- (TestProtocolEventDomainDomainEventDispatcher *)eventDomainEventDispatcher +{ + if (!_eventDomainEventDispatcher) + _eventDomainEventDispatcher = [[TestProtocolEventDomainDomainEventDispatcher alloc] initWithController:_controller]; + return _eventDomainEventDispatcher; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + +@implementation TestProtocolEventDomainDomainEventDispatcher +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller; +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)eventWithEnumParameterWithParameter:(TestProtocolEventDomainEventWithEnumParameterParameter)parameter +{ + const FrontendRouter& router = _controller->frontendRouter(); + + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("EventDomain.eventWithEnumParameter")); + Ref<InspectorObject> paramsObject = InspectorObject::create(); + paramsObject->setString(ASCIILiteral("parameter"), toProtocolString(parameter)); + jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject)); + router.sendEvent(jsonMessage->toJSONString()); +} + +@end + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + +typedef NS_ENUM(NSInteger, TestProtocolTypeDomainEnum) { + TestProtocolTypeDomainEnumShared, + TestProtocolTypeDomainEnumRed, + TestProtocolTypeDomainEnumGreen, + TestProtocolTypeDomainEnumBlue, +}; + + + +@protocol TestProtocolCommandDomainDomainHandler <NSObject> +@required +- (void)commandWithEnumReturnValueWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)(TestProtocolCommandDomainCommandWithEnumReturnValueReturnValue returnValue))successCallback; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolEventDomainDomainEventDispatcher : NSObject +- (void)eventWithEnumParameterWithParameter:(TestProtocolEventDomainEventWithEnumParameterParameter)parameter; +@end + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + +@interface TestProtocolEventDomainDomainEventDispatcher (Private) +- (instancetype)initWithController:(Inspector::AugmentableInspectorController*)controller; +@end + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + +inline String toProtocolString(TestProtocolTypeDomainEnum value) +{ + switch(value) { + case TestProtocolTypeDomainEnumShared: + return ASCIILiteral("shared"); + case TestProtocolTypeDomainEnumRed: + return ASCIILiteral("red"); + case TestProtocolTypeDomainEnumGreen: + return ASCIILiteral("green"); + case TestProtocolTypeDomainEnumBlue: + return ASCIILiteral("blue"); + } +} + +template<> +inline std::optional<TestProtocolTypeDomainEnum> fromProtocolString(const String& value) +{ + if (value == "shared") + return TestProtocolTypeDomainEnumShared; + if (value == "red") + return TestProtocolTypeDomainEnumRed; + if (value == "green") + return TestProtocolTypeDomainEnumGreen; + if (value == "blue") + return TestProtocolTypeDomainEnumBlue; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (TypeDomainDomain) + ++ (void)_parseTypeDomainEnum:(NSNumber **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (TypeDomainDomain) + ++ (void)_parseTypeDomainEnum:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolTypeDomainEnum> result = Inspector::fromProtocolString<TestProtocolTypeDomainEnum>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"TypeDomainEnum"); + *outValue = @(result.value()); +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from enum-values.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/events-with-optional-parameters.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/events-with-optional-parameters.json-result new file mode 100644 index 000000000..137d1827e --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/events-with-optional-parameters.json-result @@ -0,0 +1,1210 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Database. +InspectorBackend.registerDatabaseDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Database"); +InspectorBackend.registerEvent("Database.didExecuteOptionalParameters", ["columnNames", "notes", "timestamp", "values", "payload", "sqlError", "screenColor", "alternateColors", "printColor"]); +InspectorBackend.registerEvent("Database.didExecuteNoOptionalParameters", ["columnNames", "notes", "timestamp", "values", "payload", "sqlError", "screenColor", "alternateColors", "printColor"]); +InspectorBackend.activateDomain("Database"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +class DatabaseFrontendDispatcher { +public: + DatabaseFrontendDispatcher(FrontendRouter& frontendRouter) : m_frontendRouter(frontendRouter) { } + void didExecuteOptionalParameters(RefPtr<Inspector::Protocol::Array<String>> columnNames, const String* const notes, const double* const timestamp, RefPtr<Inspector::InspectorObject> values, RefPtr<Inspector::InspectorValue> payload, RefPtr<Inspector::Protocol::Database::Error> sqlError, const Inspector::Protocol::Database::PrimaryColors* const screenColor, RefPtr<Inspector::Protocol::Database::ColorList> alternateColors, const String* const printColor); + void didExecuteNoOptionalParameters(RefPtr<Inspector::Protocol::Array<String>> columnNames, const String& notes, double timestamp, RefPtr<Inspector::InspectorObject> values, RefPtr<Inspector::InspectorValue> payload, RefPtr<Inspector::Protocol::Database::Error> sqlError, const Inspector::Protocol::Database::PrimaryColors& screenColor, RefPtr<Inspector::Protocol::Database::ColorList> alternateColors, const String& printColor); +private: + FrontendRouter& m_frontendRouter; +}; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +void DatabaseFrontendDispatcher::didExecuteOptionalParameters(RefPtr<Inspector::Protocol::Array<String>> columnNames, const String* const notes, const double* const timestamp, RefPtr<Inspector::InspectorObject> values, RefPtr<Inspector::InspectorValue> payload, RefPtr<Inspector::Protocol::Database::Error> sqlError, const Inspector::Protocol::Database::PrimaryColors* const screenColor, RefPtr<Inspector::Protocol::Database::ColorList> alternateColors, const String* const printColor) +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Database.didExecuteOptionalParameters")); + Ref<InspectorObject> paramsObject = InspectorObject::create(); + if (columnNames) + paramsObject->setArray(ASCIILiteral("columnNames"), columnNames); + if (notes) + paramsObject->setString(ASCIILiteral("notes"), *notes); + if (timestamp) + paramsObject->setDouble(ASCIILiteral("timestamp"), *timestamp); + if (values) + paramsObject->setObject(ASCIILiteral("values"), values); + if (payload) + paramsObject->setValue(ASCIILiteral("payload"), *payload); + if (sqlError) + paramsObject->setObject(ASCIILiteral("sqlError"), sqlError); + if (screenColor) + paramsObject->setString(ASCIILiteral("screenColor"), *screenColor); + if (alternateColors) + paramsObject->setArray(ASCIILiteral("alternateColors"), alternateColors); + if (printColor) + paramsObject->setString(ASCIILiteral("printColor"), *printColor); + jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject)); + + m_frontendRouter.sendEvent(jsonMessage->toJSONString()); +} + +void DatabaseFrontendDispatcher::didExecuteNoOptionalParameters(RefPtr<Inspector::Protocol::Array<String>> columnNames, const String& notes, double timestamp, RefPtr<Inspector::InspectorObject> values, RefPtr<Inspector::InspectorValue> payload, RefPtr<Inspector::Protocol::Database::Error> sqlError, const Inspector::Protocol::Database::PrimaryColors& screenColor, RefPtr<Inspector::Protocol::Database::ColorList> alternateColors, const String& printColor) +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Database.didExecuteNoOptionalParameters")); + Ref<InspectorObject> paramsObject = InspectorObject::create(); + paramsObject->setArray(ASCIILiteral("columnNames"), columnNames); + paramsObject->setString(ASCIILiteral("notes"), notes); + paramsObject->setDouble(ASCIILiteral("timestamp"), timestamp); + paramsObject->setObject(ASCIILiteral("values"), values); + paramsObject->setValue(ASCIILiteral("payload"), payload); + paramsObject->setObject(ASCIILiteral("sqlError"), sqlError); + paramsObject->setString(ASCIILiteral("screenColor"), screenColor); + paramsObject->setArray(ASCIILiteral("alternateColors"), alternateColors); + paramsObject->setString(ASCIILiteral("printColor"), printColor); + jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject)); + + m_frontendRouter.sendEvent(jsonMessage->toJSONString()); +} + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Database { +class Error; +} // Database +// End of forward declarations. + + +// Typedefs. +namespace Database { +/* Unique identifier of Database object. */ +typedef String DatabaseId; +typedef String PrimaryColors; +typedef Inspector::Protocol::Array<Inspector::Protocol::Database::PrimaryColors> ColorList; +} // Database +// End of typedefs. + +namespace Database { +/* Database error. */ +class Error : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + MessageSet = 1 << 0, + CodeSet = 1 << 1, + AllFieldsSet = (MessageSet | CodeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*Error*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class Error; + public: + + Builder<STATE | MessageSet>& setMessage(const String& value) + { + COMPILE_ASSERT(!(STATE & MessageSet), property_message_already_set); + m_result->setString(ASCIILiteral("message"), value); + return castState<MessageSet>(); + } + + Builder<STATE | CodeSet>& setCode(int value) + { + COMPILE_ASSERT(!(STATE & CodeSet), property_code_already_set); + m_result->setInteger(ASCIILiteral("code"), value); + return castState<CodeSet>(); + } + + Ref<Error> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(Error) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<Error>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<Error> result = Error::create() + * .setMessage(...) + * .setCode(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +} // Database + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, readonly) TestProtocolDatabaseDomainEventDispatcher *databaseEventDispatcher; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + TestProtocolDatabaseDomainEventDispatcher *_databaseEventDispatcher; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_databaseEventDispatcher release]; + [super dealloc]; +} + +- (TestProtocolDatabaseDomainEventDispatcher *)databaseEventDispatcher +{ + if (!_databaseEventDispatcher) + _databaseEventDispatcher = [[TestProtocolDatabaseDomainEventDispatcher alloc] initWithController:_controller]; + return _databaseEventDispatcher; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + +@implementation TestProtocolDatabaseDomainEventDispatcher +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller; +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)didExecuteOptionalParametersWithColumnNames:(NSArray/*<NSString>*/ **)columnNames notes:(NSString **)notes timestamp:(double *)timestamp values:(RWIProtocolJSONObject **)values payload:(RWIProtocolJSONObject **)payload sqlError:(TestProtocolDatabaseError **)sqlError screenColor:(NSString **)screenColor alternateColors:(NSArray/*<NSString>*/ **)alternateColors printColor:(NSString **)printColor +{ + const FrontendRouter& router = _controller->frontendRouter(); + + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(screenColor, @"screenColor"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(alternateColors, @"alternateColors"); + THROW_EXCEPTION_FOR_BAD_OPTIONAL_PARAMETER(printColor, @"printColor"); + + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Database.didExecuteOptionalParameters")); + Ref<InspectorObject> paramsObject = InspectorObject::create(); + if (columnNames) + paramsObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray((*columnNames))); + if (notes) + paramsObject->setString(ASCIILiteral("notes"), (*notes)); + if (timestamp) + paramsObject->setDouble(ASCIILiteral("timestamp"), (*timestamp)); + if (values) + paramsObject->setObject(ASCIILiteral("values"), [(*values) toInspectorObject]); + if (payload) + paramsObject->setValue(ASCIILiteral("payload"), [(*payload) toInspectorObject]); + if (sqlError) + paramsObject->setObject(ASCIILiteral("sqlError"), [(*sqlError) toInspectorObject]); + if (screenColor) + paramsObject->setString(ASCIILiteral("screenColor"), (*screenColor)); + if (alternateColors) + paramsObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray((*alternateColors))); + if (printColor) + paramsObject->setString(ASCIILiteral("printColor"), (*printColor)); + jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject)); + router.sendEvent(jsonMessage->toJSONString()); +} + +- (void)didExecuteNoOptionalParametersWithColumnNames:(NSArray/*<NSString>*/ *)columnNames notes:(NSString *)notes timestamp:(double)timestamp values:(RWIProtocolJSONObject *)values payload:(RWIProtocolJSONObject *)payload sqlError:(TestProtocolDatabaseError *)sqlError screenColor:(NSString *)screenColor alternateColors:(NSArray/*<NSString>*/ *)alternateColors printColor:(NSString *)printColor +{ + const FrontendRouter& router = _controller->frontendRouter(); + + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(notes, @"notes"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(values, @"values"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(payload, @"payload"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(sqlError, @"sqlError"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(screenColor, @"screenColor"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(alternateColors, @"alternateColors"); + THROW_EXCEPTION_FOR_REQUIRED_PARAMETER(printColor, @"printColor"); + + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Database.didExecuteNoOptionalParameters")); + Ref<InspectorObject> paramsObject = InspectorObject::create(); + paramsObject->setArray(ASCIILiteral("columnNames"), inspectorStringArray(columnNames)); + paramsObject->setString(ASCIILiteral("notes"), notes); + paramsObject->setDouble(ASCIILiteral("timestamp"), timestamp); + paramsObject->setObject(ASCIILiteral("values"), [values toInspectorObject]); + paramsObject->setValue(ASCIILiteral("payload"), [payload toInspectorObject]); + paramsObject->setObject(ASCIILiteral("sqlError"), [sqlError toInspectorObject]); + paramsObject->setString(ASCIILiteral("screenColor"), screenColor); + paramsObject->setArray(ASCIILiteral("alternateColors"), inspectorStringArray(alternateColors)); + paramsObject->setString(ASCIILiteral("printColor"), printColor); + jsonMessage->setObject(ASCIILiteral("params"), WTFMove(paramsObject)); + router.sendEvent(jsonMessage->toJSONString()); +} + +@end + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolDatabaseError; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseError : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithMessage:(NSString *)message code:(int)code; +/* required */ @property (nonatomic, copy) NSString *message; +/* required */ @property (nonatomic, assign) int code; +@end + + + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseDomainEventDispatcher : NSObject +- (void)didExecuteOptionalParametersWithColumnNames:(NSArray/*<NSString>*/ **)columnNames notes:(NSString **)notes timestamp:(double *)timestamp values:(RWIProtocolJSONObject **)values payload:(RWIProtocolJSONObject **)payload sqlError:(TestProtocolDatabaseError **)sqlError screenColor:(NSString **)screenColor alternateColors:(NSArray/*<NSString>*/ **)alternateColors printColor:(NSString **)printColor; +- (void)didExecuteNoOptionalParametersWithColumnNames:(NSArray/*<NSString>*/ *)columnNames notes:(NSString *)notes timestamp:(double)timestamp values:(RWIProtocolJSONObject *)values payload:(RWIProtocolJSONObject *)payload sqlError:(TestProtocolDatabaseError *)sqlError screenColor:(NSString *)screenColor alternateColors:(NSArray/*<NSString>*/ *)alternateColors printColor:(NSString *)printColor; +@end + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + +@interface TestProtocolDatabaseDomainEventDispatcher (Private) +- (instancetype)initWithController:(Inspector::AugmentableInspectorController*)controller; +@end + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseDatabaseId:(NSString **)outValue fromPayload:(id)payload; ++ (void)_parsePrimaryColors:(NSString **)outValue fromPayload:(id)payload; ++ (void)_parseColorList:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseDatabaseId:(NSString **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + *outValue = (NSString *)payload; +} + ++ (void)_parsePrimaryColors:(NSString **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + *outValue = (NSString *)payload; +} + ++ (void)_parseColorList:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSString>*/ class]); + *outValue = (NSArray/*<NSString>*/ *)payload; +} + ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseError alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from events-with-optional-parameters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolDatabaseError + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"message"], @"message"); + self.message = payload[@"message"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"code"], @"code"); + self.code = [payload[@"code"] integerValue]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithMessage:(NSString *)message code:(int)code +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(message, @"message"); + + self.message = message; + self.code = code; + + return self; +} + +- (void)setMessage:(NSString *)message +{ + [super setString:message forKey:@"message"]; +} + +- (NSString *)message +{ + return [super stringForKey:@"message"]; +} + +- (void)setCode:(int)code +{ + [super setInteger:code forKey:@"code"]; +} + +- (int)code +{ + return [super integerForKey:@"code"]; +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-command-with-invalid-platform.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-command-with-invalid-platform.json-error new file mode 100644 index 000000000..ec636c54b --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-command-with-invalid-platform.json-error @@ -0,0 +1 @@ +ERROR: Unknown platform: invalid diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-domain-availability.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-domain-availability.json-error new file mode 100644 index 000000000..90d7195d6 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-domain-availability.json-error @@ -0,0 +1 @@ +ERROR: Malformed domain specification: availability is an unsupported string. Was: "webb", Allowed values: web diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-command-call-parameter-names.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-command-call-parameter-names.json-error new file mode 100644 index 000000000..3f756de32 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-command-call-parameter-names.json-error @@ -0,0 +1 @@ +ERROR: Malformed domain specification: call parameter list for command processPoints has duplicate parameter names diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-command-return-parameter-names.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-command-return-parameter-names.json-error new file mode 100644 index 000000000..ea148ff67 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-command-return-parameter-names.json-error @@ -0,0 +1 @@ +ERROR: Malformed domain specification: return parameter list for command processPoints has duplicate parameter names diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-event-parameter-names.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-event-parameter-names.json-error new file mode 100644 index 000000000..c71bbd21c --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-event-parameter-names.json-error @@ -0,0 +1 @@ +ERROR: Malformed domain specification: parameter list for event processedPoints has duplicate parameter names diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-type-declarations.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-type-declarations.json-error new file mode 100644 index 000000000..447cdf8e2 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-type-declarations.json-error @@ -0,0 +1 @@ +ERROR: Duplicate type declaration: Runtime.RemoteObjectId diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-type-member-names.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-type-member-names.json-error new file mode 100644 index 000000000..d5376a77a --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-duplicate-type-member-names.json-error @@ -0,0 +1 @@ +ERROR: Malformed domain specification: type declaration for Point has duplicate member names diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-enum-with-no-values.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-enum-with-no-values.json-error new file mode 100644 index 000000000..2655c2b90 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-enum-with-no-values.json-error @@ -0,0 +1 @@ +ERROR: Type reference with enum values must have at least one enum value. diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-number-typed-optional-parameter-flag.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-number-typed-optional-parameter-flag.json-error new file mode 100644 index 000000000..97b2af0e4 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-number-typed-optional-parameter-flag.json-error @@ -0,0 +1 @@ +ERROR: The 'optional' flag for a parameter must be a boolean literal. diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-number-typed-optional-type-member.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-number-typed-optional-type-member.json-error new file mode 100644 index 000000000..86df3750c --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-number-typed-optional-type-member.json-error @@ -0,0 +1 @@ +ERROR: The 'optional' flag for a type member must be a boolean literal. diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-string-typed-optional-parameter-flag.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-string-typed-optional-parameter-flag.json-error new file mode 100644 index 000000000..97b2af0e4 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-string-typed-optional-parameter-flag.json-error @@ -0,0 +1 @@ +ERROR: The 'optional' flag for a parameter must be a boolean literal. diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-string-typed-optional-type-member.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-string-typed-optional-type-member.json-error new file mode 100644 index 000000000..86df3750c --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-string-typed-optional-type-member.json-error @@ -0,0 +1 @@ +ERROR: The 'optional' flag for a type member must be a boolean literal. diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-declaration-using-type-reference.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-declaration-using-type-reference.json-error new file mode 100644 index 000000000..42f5753a4 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-declaration-using-type-reference.json-error @@ -0,0 +1 @@ +ERROR: Type reference cannot have both 'type' and '$ref' keys. diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-reference-as-primitive-type.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-reference-as-primitive-type.json-error new file mode 100644 index 000000000..d76bc1c77 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-reference-as-primitive-type.json-error @@ -0,0 +1 @@ +ERROR: Type reference 'DatabaseId' is not a primitive type. Allowed values: integer, number, string, boolean, enum, object, array, any diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-with-invalid-platform.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-with-invalid-platform.json-error new file mode 100644 index 000000000..ec636c54b --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-with-invalid-platform.json-error @@ -0,0 +1 @@ +ERROR: Unknown platform: invalid diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-with-lowercase-name.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-with-lowercase-name.json-error new file mode 100644 index 000000000..4e462250c --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-type-with-lowercase-name.json-error @@ -0,0 +1 @@ +ERROR: Types must begin with an uppercase character. diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-unknown-type-reference-in-type-declaration.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-unknown-type-reference-in-type-declaration.json-error new file mode 100644 index 000000000..2d38e6467 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-unknown-type-reference-in-type-declaration.json-error @@ -0,0 +1 @@ +ERROR: Type reference 'dragon' is not a primitive type. Allowed values: integer, number, string, boolean, enum, object, array, any diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-unknown-type-reference-in-type-member.json-error b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-unknown-type-reference-in-type-member.json-error new file mode 100644 index 000000000..faf6672cb --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/fail-on-unknown-type-reference-in-type-member.json-error @@ -0,0 +1 @@ +ERROR: Lookup failed for type reference: Color (referenced from domain: Fantasy) diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/generate-domains-with-feature-guards.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/generate-domains-with-feature-guards.json-result new file mode 100644 index 000000000..9eeb0b1c9 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/generate-domains-with-feature-guards.json-result @@ -0,0 +1,1230 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Network1. +InspectorBackend.registerCommand("Network1.loadResource", [], []); +InspectorBackend.activateDomain("Network1"); + +// Network3. +InspectorBackend.registerNetwork3Dispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Network3"); +InspectorBackend.registerEvent("Network3.resourceLoaded", []); +InspectorBackend.activateDomain("Network3"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +#if PLATFORM(WEB_COMMANDS) +class AlternateNetwork1BackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateNetwork1BackendDispatcher() { } + virtual void loadResource(long callId) = 0; +}; +#endif // PLATFORM(WEB_COMMANDS) + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#if PLATFORM(WEB_COMMANDS) +class AlternateNetwork1BackendDispatcher; +#endif // PLATFORM(WEB_COMMANDS) +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#if PLATFORM(WEB_COMMANDS) +class Network1BackendDispatcherHandler { +public: + virtual void loadResource(ErrorString&) = 0; +protected: + virtual ~Network1BackendDispatcherHandler(); +}; +#endif // PLATFORM(WEB_COMMANDS) + +#if PLATFORM(WEB_COMMANDS) +class Network1BackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<Network1BackendDispatcher> create(BackendDispatcher&, Network1BackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void loadResource(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateNetwork1BackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateNetwork1BackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + Network1BackendDispatcher(BackendDispatcher&, Network1BackendDispatcherHandler*); + Network1BackendDispatcherHandler* m_agent { nullptr }; +}; +#endif // PLATFORM(WEB_COMMANDS) + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +#if PLATFORM(WEB_COMMANDS) +Network1BackendDispatcherHandler::~Network1BackendDispatcherHandler() { } +#endif // PLATFORM(WEB_COMMANDS) + +#if PLATFORM(WEB_COMMANDS) +Ref<Network1BackendDispatcher> Network1BackendDispatcher::create(BackendDispatcher& backendDispatcher, Network1BackendDispatcherHandler* agent) +{ + return adoptRef(*new Network1BackendDispatcher(backendDispatcher, agent)); +} + +Network1BackendDispatcher::Network1BackendDispatcher(BackendDispatcher& backendDispatcher, Network1BackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("Network1"), this); +} + +void Network1BackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<Network1BackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "loadResource") + loadResource(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "Network1", '.', method, "' was not found")); +} + +void Network1BackendDispatcher::loadResource(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->loadResource(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->loadResource(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} +#endif // PLATFORM(WEB_COMMANDS) + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +#if PLATFORM(WEB_EVENTS) +class Network3FrontendDispatcher { +public: + Network3FrontendDispatcher(FrontendRouter& frontendRouter) : m_frontendRouter(frontendRouter) { } + void resourceLoaded(); +private: + FrontendRouter& m_frontendRouter; +}; +#endif // PLATFORM(WEB_EVENTS) + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +#if PLATFORM(WEB_EVENTS) +void Network3FrontendDispatcher::resourceLoaded() +{ + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Network3.resourceLoaded")); + + m_frontendRouter.sendEvent(jsonMessage->toJSONString()); +} +#endif // PLATFORM(WEB_EVENTS) + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +#if PLATFORM(WEB_TYPES) +namespace Network2 { +class NetworkError; +} // Network2 +#endif // PLATFORM(WEB_TYPES) +// End of forward declarations. + + + + +#if PLATFORM(WEB_TYPES) +namespace Network2 { +class NetworkError : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + MessageSet = 1 << 0, + CodeSet = 1 << 1, + AllFieldsSet = (MessageSet | CodeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*NetworkError*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class NetworkError; + public: + + Builder<STATE | MessageSet>& setMessage(const String& value) + { + COMPILE_ASSERT(!(STATE & MessageSet), property_message_already_set); + m_result->setString(ASCIILiteral("message"), value); + return castState<MessageSet>(); + } + + Builder<STATE | CodeSet>& setCode(int value) + { + COMPILE_ASSERT(!(STATE & CodeSet), property_code_already_set); + m_result->setInteger(ASCIILiteral("code"), value); + return castState<CodeSet>(); + } + + Ref<NetworkError> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(NetworkError) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<NetworkError>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<NetworkError> result = NetworkError::create() + * .setMessage(...) + * .setCode(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +} // Network2 +#endif // PLATFORM(WEB_TYPES) + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolNetwork1DomainHandler; + +namespace Inspector { + + +#if PLATFORM(WEB_COMMANDS) +class ObjCInspectorNetwork1BackendDispatcher final : public AlternateNetwork1BackendDispatcher { +public: + ObjCInspectorNetwork1BackendDispatcher(id<TestProtocolNetwork1DomainHandler> handler) { m_delegate = handler; } + virtual void loadResource(long requestId) override; +private: + RetainPtr<id<TestProtocolNetwork1DomainHandler>> m_delegate; +}; +#endif // PLATFORM(WEB_COMMANDS) + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +#if PLATFORM(WEB_COMMANDS) +void ObjCInspectorNetwork1BackendDispatcher::loadResource(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate loadResourceWithErrorCallback:errorCallback successCallback:successCallback]; +} + +#endif // PLATFORM(WEB_COMMANDS) + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setNetwork1Handler:) id<TestProtocolNetwork1DomainHandler> network1Handler; +@property (nonatomic, readonly) TestProtocolNetwork3DomainEventDispatcher *network3EventDispatcher; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolNetwork1DomainHandler> _network1Handler; + TestProtocolNetwork3DomainEventDispatcher *_network3EventDispatcher; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_network1Handler release]; + [_network3EventDispatcher release]; + [super dealloc]; +} + +- (void)setNetwork1Handler:(id<TestProtocolNetwork1DomainHandler>)handler +{ + if (handler == _network1Handler) + return; + + [_network1Handler release]; + _network1Handler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorNetwork1BackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<Network1BackendDispatcher, AlternateNetwork1BackendDispatcher>>(ASCIILiteral("Network1"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolNetwork1DomainHandler>)network1Handler +{ + return _network1Handler; +} + +- (TestProtocolNetwork3DomainEventDispatcher *)network3EventDispatcher +{ + if (!_network3EventDispatcher) + _network3EventDispatcher = [[TestProtocolNetwork3DomainEventDispatcher alloc] initWithController:_controller]; + return _network3EventDispatcher; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + +@implementation TestProtocolNetwork3DomainEventDispatcher +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller; +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)resourceLoaded +{ + const FrontendRouter& router = _controller->frontendRouter(); + + Ref<InspectorObject> jsonMessage = InspectorObject::create(); + jsonMessage->setString(ASCIILiteral("method"), ASCIILiteral("Network3.resourceLoaded")); + router.sendEvent(jsonMessage->toJSONString()); +} + +@end + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolNetwork2NetworkError; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + +__attribute__((visibility ("default"))) +@interface TestProtocolNetwork2NetworkError : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithMessage:(NSString *)message code:(int)code; +/* required */ @property (nonatomic, copy) NSString *message; +/* required */ @property (nonatomic, assign) int code; +@end + +@protocol TestProtocolNetwork1DomainHandler <NSObject> +@required +- (void)loadResourceWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolNetwork3DomainEventDispatcher : NSObject +- (void)resourceLoaded; +@end + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + +@interface TestProtocolNetwork3DomainEventDispatcher (Private) +- (instancetype)initWithController:(Inspector::AugmentableInspectorController*)controller; +@end + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (Network2Domain) + ++ (void)_parseNetworkError:(TestProtocolNetwork2NetworkError **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (Network2Domain) + ++ (void)_parseNetworkError:(TestProtocolNetwork2NetworkError **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolNetwork2NetworkError alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from generate-domains-with-feature-guards.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolNetwork2NetworkError + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"message"], @"message"); + self.message = payload[@"message"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"code"], @"code"); + self.code = [payload[@"code"] integerValue]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithMessage:(NSString *)message code:(int)code +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(message, @"message"); + + self.message = message; + self.code = code; + + return self; +} + +- (void)setMessage:(NSString *)message +{ + [super setString:message forKey:@"message"]; +} + +- (NSString *)message +{ + return [super stringForKey:@"message"]; +} + +- (void)setCode:(int)code +{ + [super setInteger:code forKey:@"code"]; +} + +- (int)code +{ + return [super integerForKey:@"code"]; +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/same-type-id-different-domain.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/same-type-id-different-domain.json-result new file mode 100644 index 000000000..d65129eb8 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/same-type-id-different-domain.json-result @@ -0,0 +1,910 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + + + +// Typedefs. +namespace Runtime { +/* Unique object identifier. */ +typedef String RemoteObjectId; +} // Runtime + +namespace Runtime2 { +/* Unique object identifier. */ +typedef String RemoteObjectId; +} // Runtime2 +// End of typedefs. + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseRemoteObjectId:(NSString **)outValue fromPayload:(id)payload; + +@end +@interface TestProtocolTypeConversions (Runtime2Domain) + ++ (void)_parseRemoteObjectId:(NSString **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseRemoteObjectId:(NSString **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + *outValue = (NSString *)payload; +} + +@end +@implementation TestProtocolTypeConversions (Runtime2Domain) + ++ (void)_parseRemoteObjectId:(NSString **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + *outValue = (NSString *)payload; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from same-type-id-different-domain.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + + + + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/shadowed-optional-type-setters.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/shadowed-optional-type-setters.json-result new file mode 100644 index 000000000..b7eff1b15 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/shadowed-optional-type-setters.json-result @@ -0,0 +1,1119 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Runtime { +class KeyPath; +} // Runtime +// End of forward declarations. + + + + +namespace TestHelpers { + +String getEnumConstantValue(int code); + +template<typename T> String getEnumConstantValue(T enumValue) +{ + return getEnumConstantValue(static_cast<int>(enumValue)); +} + +} // namespace TestHelpers + +namespace Runtime { +/* Key path. */ +class KeyPath : public Inspector::InspectorObjectBase { +public: + // Named after property name 'type' while generating KeyPath. + enum class Type { + Null = 0, + String = 1, + Array = 2, + }; // enum class Type + enum { + NoFieldsSet = 0, + TypeSet = 1 << 0, + AllFieldsSet = (TypeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*KeyPath*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class KeyPath; + public: + + Builder<STATE | TypeSet>& setType(Type value) + { + COMPILE_ASSERT(!(STATE & TypeSet), property_type_already_set); + m_result->setString(ASCIILiteral("type"), Inspector::Protocol::TestHelpers::getEnumConstantValue(value)); + return castState<TypeSet>(); + } + + Ref<KeyPath> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(KeyPath) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<KeyPath>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<KeyPath> result = KeyPath::create() + * .setType(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } + + void setString(const String& value) + { + InspectorObjectBase::setString(ASCIILiteral("string"), value); + } + + void setArray(RefPtr<Inspector::Protocol::Array<String>> value) + { + InspectorObjectBase::setArray(ASCIILiteral("array"), WTFMove(value)); + } +}; + +} // Runtime + + + +namespace TestHelpers { + +template<typename ProtocolEnumType> +std::optional<ProtocolEnumType> parseEnumValueFromString(const String&); + +// Enums in the 'Runtime' Domain +template<> +std::optional<Inspector::Protocol::Runtime::KeyPath::Type> parseEnumValueFromString<Inspector::Protocol::Runtime::KeyPath::Type>(const String&); + +} // namespace TestHelpers + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + +namespace TestHelpers { + +static const char* const enum_constant_values[] = { + "null", + "string", + "array", +}; + +String getEnumConstantValue(int code) { + return enum_constant_values[code]; +} + +// Enums in the 'Runtime' Domain +template<> +std::optional<Inspector::Protocol::Runtime::KeyPath::Type> parseEnumValueFromString<Inspector::Protocol::Runtime::KeyPath::Type>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Runtime::KeyPath::Type::Null, + (size_t)Inspector::Protocol::Runtime::KeyPath::Type::String, + (size_t)Inspector::Protocol::Runtime::KeyPath::Type::Array, + }; + for (size_t i = 0; i < 3; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Runtime::KeyPath::Type)constantValues[i]; + + return std::nullopt; +} + + +} // namespace TestHelpers + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolRuntimeKeyPath; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + +typedef NS_ENUM(NSInteger, TestProtocolRuntimeKeyPathType) { + TestProtocolRuntimeKeyPathTypeNull, + TestProtocolRuntimeKeyPathTypeString, + TestProtocolRuntimeKeyPathTypeArray, +}; + + +__attribute__((visibility ("default"))) +@interface TestProtocolRuntimeKeyPath : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithType:(TestProtocolRuntimeKeyPathType)type; +/* required */ @property (nonatomic, assign) TestProtocolRuntimeKeyPathType type; +/* optional */ @property (nonatomic, copy) NSString *string; +/* optional */ @property (nonatomic, copy) NSArray/*<NSString>*/ *array; +@end + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + +inline String toProtocolString(TestProtocolRuntimeKeyPathType value) +{ + switch(value) { + case TestProtocolRuntimeKeyPathTypeNull: + return ASCIILiteral("null"); + case TestProtocolRuntimeKeyPathTypeString: + return ASCIILiteral("string"); + case TestProtocolRuntimeKeyPathTypeArray: + return ASCIILiteral("array"); + } +} + +template<> +inline std::optional<TestProtocolRuntimeKeyPathType> fromProtocolString(const String& value) +{ + if (value == "null") + return TestProtocolRuntimeKeyPathTypeNull; + if (value == "string") + return TestProtocolRuntimeKeyPathTypeString; + if (value == "array") + return TestProtocolRuntimeKeyPathTypeArray; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseKeyPath:(TestProtocolRuntimeKeyPath **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseKeyPath:(TestProtocolRuntimeKeyPath **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolRuntimeKeyPath alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from shadowed-optional-type-setters.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolRuntimeKeyPath + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"type"], @"type"); + std::optional<TestProtocolRuntimeKeyPathType> type = fromProtocolString<TestProtocolRuntimeKeyPathType>(payload[@"type"]); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(type, @"type"); + self.type = type.value(); + + self.string = payload[@"string"]; + + self.array = objcArrayFromPayload<NSString>(payload[@"array"]); + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithType:(TestProtocolRuntimeKeyPathType)type +{ + if (!(self = [super init])) + return nil; + + self.type = type; + + return self; +} + +- (void)setType:(TestProtocolRuntimeKeyPathType)type +{ + [super setString:toProtocolString(type) forKey:@"type"]; +} + +- (TestProtocolRuntimeKeyPathType)type +{ + return fromProtocolString<TestProtocolRuntimeKeyPathType>([super stringForKey:@"type"]).value(); +} + +- (void)setString:(NSString *)string +{ + [super setString:string forKey:@"string"]; +} + +- (NSString *)string +{ + return [super stringForKey:@"string"]; +} + +- (void)setArray:(NSArray/*<NSString>*/ *)array +{ + [super setInspectorArray:inspectorStringArray(array) forKey:@"array"]; +} + +- (NSArray/*<NSString>*/ *)array +{ + return objcStringArray([super inspectorArrayForKey:@"array"]); +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-aliased-primitive-type.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-aliased-primitive-type.json-result new file mode 100644 index 000000000..6ece43d9c --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-aliased-primitive-type.json-result @@ -0,0 +1,887 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + + + +// Typedefs. +namespace Runtime { +/* Unique object identifier. */ +typedef int RemoteObjectId; +} // Runtime +// End of typedefs. + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseRemoteObjectId:(NSNumber **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseRemoteObjectId:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSNumber class]); + *outValue = (NSNumber *)payload; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-aliased-primitive-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-array-type.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-array-type.json-result new file mode 100644 index 000000000..d2a62c9ff --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-array-type.json-result @@ -0,0 +1,1055 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Debugger. +InspectorBackend.registerEnum("Debugger.Reason", {Died: "Died", Fainted: "Fainted", Hungry: "Hungry"}); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Debugger { +enum class Reason; +} // Debugger +// End of forward declarations. + + +// Typedefs. +namespace Debugger { +typedef int BreakpointId; +} // Debugger + +namespace Runtime { +typedef int ObjectId; +typedef Inspector::Protocol::Array<int> LuckyNumbers; +typedef Inspector::Protocol::Array<String> BabyNames; +typedef Inspector::Protocol::Array<Inspector::Protocol::Runtime::ObjectId> NewObjects; +typedef Inspector::Protocol::Array<Inspector::Protocol::Debugger::BreakpointId> OldObjects; +typedef Inspector::Protocol::Array<Inspector::Protocol::Debugger::Reason> StopReasons; +} // Runtime +// End of typedefs. + +namespace TestHelpers { + +String getEnumConstantValue(int code); + +template<typename T> String getEnumConstantValue(T enumValue) +{ + return getEnumConstantValue(static_cast<int>(enumValue)); +} + +} // namespace TestHelpers + +namespace Debugger { +/* */ +enum class Reason { + Died = 0, + Fainted = 1, + Hungry = 2, +}; // enum class Reason +} // Debugger + + + +namespace TestHelpers { + +template<typename ProtocolEnumType> +std::optional<ProtocolEnumType> parseEnumValueFromString(const String&); + +// Enums in the 'Debugger' Domain +template<> +std::optional<Inspector::Protocol::Debugger::Reason> parseEnumValueFromString<Inspector::Protocol::Debugger::Reason>(const String&); + +} // namespace TestHelpers + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + +namespace TestHelpers { + +static const char* const enum_constant_values[] = { + "Died", + "Fainted", + "Hungry", +}; + +String getEnumConstantValue(int code) { + return enum_constant_values[code]; +} + +// Enums in the 'Debugger' Domain +template<> +std::optional<Inspector::Protocol::Debugger::Reason> parseEnumValueFromString<Inspector::Protocol::Debugger::Reason>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Debugger::Reason::Died, + (size_t)Inspector::Protocol::Debugger::Reason::Fainted, + (size_t)Inspector::Protocol::Debugger::Reason::Hungry, + }; + for (size_t i = 0; i < 3; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Debugger::Reason)constantValues[i]; + + return std::nullopt; +} + + +} // namespace TestHelpers + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + +typedef NS_ENUM(NSInteger, TestProtocolDebuggerReason) { + TestProtocolDebuggerReasonDied, + TestProtocolDebuggerReasonFainted, + TestProtocolDebuggerReasonHungry, +}; + + + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + +inline String toProtocolString(TestProtocolDebuggerReason value) +{ + switch(value) { + case TestProtocolDebuggerReasonDied: + return ASCIILiteral("Died"); + case TestProtocolDebuggerReasonFainted: + return ASCIILiteral("Fainted"); + case TestProtocolDebuggerReasonHungry: + return ASCIILiteral("Hungry"); + } +} + +template<> +inline std::optional<TestProtocolDebuggerReason> fromProtocolString(const String& value) +{ + if (value == "Died") + return TestProtocolDebuggerReasonDied; + if (value == "Fainted") + return TestProtocolDebuggerReasonFainted; + if (value == "Hungry") + return TestProtocolDebuggerReasonHungry; + return std::nullopt; +} + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (DebuggerDomain) + ++ (void)_parseBreakpointId:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseReason:(NSNumber **)outValue fromPayload:(id)payload; + +@end +@interface TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseObjectId:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseLuckyNumbers:(NSArray/*<NSNumber>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseBabyNames:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseNewObjects:(NSArray/*<NSNumber>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseOldObjects:(NSArray/*<NSNumber>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseStopReasons:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (DebuggerDomain) + ++ (void)_parseBreakpointId:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSNumber class]); + *outValue = (NSNumber *)payload; +} + ++ (void)_parseReason:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolDebuggerReason> result = Inspector::fromProtocolString<TestProtocolDebuggerReason>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"Reason"); + *outValue = @(result.value()); +} + +@end +@implementation TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseObjectId:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSNumber class]); + *outValue = (NSNumber *)payload; +} + ++ (void)_parseLuckyNumbers:(NSArray/*<NSNumber>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSNumber>*/ class]); + *outValue = (NSArray/*<NSNumber>*/ *)payload; +} + ++ (void)_parseBabyNames:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSString>*/ class]); + *outValue = (NSArray/*<NSString>*/ *)payload; +} + ++ (void)_parseNewObjects:(NSArray/*<NSNumber>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSNumber>*/ class]); + *outValue = (NSArray/*<NSNumber>*/ *)payload; +} + ++ (void)_parseOldObjects:(NSArray/*<NSNumber>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSNumber>*/ class]); + *outValue = (NSArray/*<NSNumber>*/ *)payload; +} + ++ (void)_parseStopReasons:(NSArray/*<NSString>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<NSString>*/ class]); + *outValue = (NSArray/*<NSString>*/ *)payload; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-array-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + + + + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-enum-type.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-enum-type.json-result new file mode 100644 index 000000000..a1cfcf54b --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-enum-type.json-result @@ -0,0 +1,1064 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Runtime. +InspectorBackend.registerEnum("Runtime.FarmAnimals", {Pigs: "Pigs", Cows: "Cows", Cats: "Cats", Hens: "Hens"}); +InspectorBackend.registerEnum("Runtime.TwoLeggedAnimals", {Ducks: "Ducks", Hens: "Hens", Crows: "Crows", Flamingos: "Flamingos"}); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Runtime { +enum class FarmAnimals; +enum class TwoLeggedAnimals; +} // Runtime +// End of forward declarations. + + + + +namespace TestHelpers { + +String getEnumConstantValue(int code); + +template<typename T> String getEnumConstantValue(T enumValue) +{ + return getEnumConstantValue(static_cast<int>(enumValue)); +} + +} // namespace TestHelpers + +namespace Runtime { +/* */ +enum class FarmAnimals { + Pigs = 0, + Cows = 1, + Cats = 2, + Hens = 3, +}; // enum class FarmAnimals +/* */ +enum class TwoLeggedAnimals { + Ducks = 4, + Hens = 3, + Crows = 5, + Flamingos = 6, +}; // enum class TwoLeggedAnimals +} // Runtime + + + +namespace TestHelpers { + +template<typename ProtocolEnumType> +std::optional<ProtocolEnumType> parseEnumValueFromString(const String&); + +// Enums in the 'Runtime' Domain +template<> +std::optional<Inspector::Protocol::Runtime::FarmAnimals> parseEnumValueFromString<Inspector::Protocol::Runtime::FarmAnimals>(const String&); +template<> +std::optional<Inspector::Protocol::Runtime::TwoLeggedAnimals> parseEnumValueFromString<Inspector::Protocol::Runtime::TwoLeggedAnimals>(const String&); + +} // namespace TestHelpers + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + +namespace TestHelpers { + +static const char* const enum_constant_values[] = { + "Pigs", + "Cows", + "Cats", + "Hens", + "Ducks", + "Crows", + "Flamingos", +}; + +String getEnumConstantValue(int code) { + return enum_constant_values[code]; +} + +// Enums in the 'Runtime' Domain +template<> +std::optional<Inspector::Protocol::Runtime::FarmAnimals> parseEnumValueFromString<Inspector::Protocol::Runtime::FarmAnimals>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Runtime::FarmAnimals::Pigs, + (size_t)Inspector::Protocol::Runtime::FarmAnimals::Cows, + (size_t)Inspector::Protocol::Runtime::FarmAnimals::Cats, + (size_t)Inspector::Protocol::Runtime::FarmAnimals::Hens, + }; + for (size_t i = 0; i < 4; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Runtime::FarmAnimals)constantValues[i]; + + return std::nullopt; +} + +template<> +std::optional<Inspector::Protocol::Runtime::TwoLeggedAnimals> parseEnumValueFromString<Inspector::Protocol::Runtime::TwoLeggedAnimals>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Runtime::TwoLeggedAnimals::Ducks, + (size_t)Inspector::Protocol::Runtime::TwoLeggedAnimals::Hens, + (size_t)Inspector::Protocol::Runtime::TwoLeggedAnimals::Crows, + (size_t)Inspector::Protocol::Runtime::TwoLeggedAnimals::Flamingos, + }; + for (size_t i = 0; i < 4; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Runtime::TwoLeggedAnimals)constantValues[i]; + + return std::nullopt; +} + + +} // namespace TestHelpers + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + +typedef NS_ENUM(NSInteger, TestProtocolRuntimeFarmAnimals) { + TestProtocolRuntimeFarmAnimalsPigs, + TestProtocolRuntimeFarmAnimalsCows, + TestProtocolRuntimeFarmAnimalsCats, + TestProtocolRuntimeFarmAnimalsHens, +}; + +typedef NS_ENUM(NSInteger, TestProtocolRuntimeTwoLeggedAnimals) { + TestProtocolRuntimeTwoLeggedAnimalsDucks, + TestProtocolRuntimeTwoLeggedAnimalsHens, + TestProtocolRuntimeTwoLeggedAnimalsCrows, + TestProtocolRuntimeTwoLeggedAnimalsFlamingos, +}; + + + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + +inline String toProtocolString(TestProtocolRuntimeFarmAnimals value) +{ + switch(value) { + case TestProtocolRuntimeFarmAnimalsPigs: + return ASCIILiteral("Pigs"); + case TestProtocolRuntimeFarmAnimalsCows: + return ASCIILiteral("Cows"); + case TestProtocolRuntimeFarmAnimalsCats: + return ASCIILiteral("Cats"); + case TestProtocolRuntimeFarmAnimalsHens: + return ASCIILiteral("Hens"); + } +} + +template<> +inline std::optional<TestProtocolRuntimeFarmAnimals> fromProtocolString(const String& value) +{ + if (value == "Pigs") + return TestProtocolRuntimeFarmAnimalsPigs; + if (value == "Cows") + return TestProtocolRuntimeFarmAnimalsCows; + if (value == "Cats") + return TestProtocolRuntimeFarmAnimalsCats; + if (value == "Hens") + return TestProtocolRuntimeFarmAnimalsHens; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolRuntimeTwoLeggedAnimals value) +{ + switch(value) { + case TestProtocolRuntimeTwoLeggedAnimalsDucks: + return ASCIILiteral("Ducks"); + case TestProtocolRuntimeTwoLeggedAnimalsHens: + return ASCIILiteral("Hens"); + case TestProtocolRuntimeTwoLeggedAnimalsCrows: + return ASCIILiteral("Crows"); + case TestProtocolRuntimeTwoLeggedAnimalsFlamingos: + return ASCIILiteral("Flamingos"); + } +} + +template<> +inline std::optional<TestProtocolRuntimeTwoLeggedAnimals> fromProtocolString(const String& value) +{ + if (value == "Ducks") + return TestProtocolRuntimeTwoLeggedAnimalsDucks; + if (value == "Hens") + return TestProtocolRuntimeTwoLeggedAnimalsHens; + if (value == "Crows") + return TestProtocolRuntimeTwoLeggedAnimalsCrows; + if (value == "Flamingos") + return TestProtocolRuntimeTwoLeggedAnimalsFlamingos; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseFarmAnimals:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseTwoLeggedAnimals:(NSNumber **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (RuntimeDomain) + ++ (void)_parseFarmAnimals:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolRuntimeFarmAnimals> result = Inspector::fromProtocolString<TestProtocolRuntimeFarmAnimals>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"FarmAnimals"); + *outValue = @(result.value()); +} + ++ (void)_parseTwoLeggedAnimals:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolRuntimeTwoLeggedAnimals> result = Inspector::fromProtocolString<TestProtocolRuntimeTwoLeggedAnimals>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"TwoLeggedAnimals"); + *outValue = @(result.value()); +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-enum-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-object-type.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-object-type.json-result new file mode 100644 index 000000000..1b23ab2a9 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-declaration-object-type.json-result @@ -0,0 +1,2012 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Database { +class Error; +class OptionalParameterBundle; +class ParameterBundle; +class ObjectWithPropertyNameConflicts; +class DummyObject; +} // Database + +namespace Test { +class ParameterBundle; +} // Test +// End of forward declarations. + + +// Typedefs. +namespace Database { +typedef Inspector::Protocol::Array<Inspector::Protocol::Database::Error> ErrorList; +} // Database +// End of typedefs. + +namespace Database { +/* Database error. */ +class Error : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + MessageSet = 1 << 0, + CodeSet = 1 << 1, + AllFieldsSet = (MessageSet | CodeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*Error*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class Error; + public: + + Builder<STATE | MessageSet>& setMessage(const String& value) + { + COMPILE_ASSERT(!(STATE & MessageSet), property_message_already_set); + m_result->setString(ASCIILiteral("message"), value); + return castState<MessageSet>(); + } + + Builder<STATE | CodeSet>& setCode(int value) + { + COMPILE_ASSERT(!(STATE & CodeSet), property_code_already_set); + m_result->setInteger(ASCIILiteral("code"), value); + return castState<CodeSet>(); + } + + Ref<Error> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(Error) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<Error>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<Error> result = Error::create() + * .setMessage(...) + * .setCode(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +class OptionalParameterBundle : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + AllFieldsSet = 0 + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*OptionalParameterBundle*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class OptionalParameterBundle; + public: + + Ref<OptionalParameterBundle> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(OptionalParameterBundle) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<OptionalParameterBundle>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<OptionalParameterBundle> result = OptionalParameterBundle::create() + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } + + void setColumnNames(RefPtr<Inspector::Protocol::Array<String>> value) + { + InspectorObjectBase::setArray(ASCIILiteral("columnNames"), WTFMove(value)); + } + + void setNotes(const String& value) + { + InspectorObjectBase::setString(ASCIILiteral("notes"), value); + } + + void setTimestamp(double value) + { + InspectorObjectBase::setDouble(ASCIILiteral("timestamp"), value); + } + + void setValues(RefPtr<Inspector::InspectorObject> value) + { + InspectorObjectBase::setObject(ASCIILiteral("values"), WTFMove(value)); + } + + void setPayload(RefPtr<Inspector::InspectorValue> value) + { + InspectorObjectBase::setValue(ASCIILiteral("payload"), WTFMove(value)); + } + + void setError(RefPtr<Inspector::Protocol::Database::Error> value) + { + InspectorObjectBase::setObject(ASCIILiteral("error"), WTFMove(value)); + } + + void setErrorList(RefPtr<Inspector::Protocol::Database::ErrorList> value) + { + InspectorObjectBase::setArray(ASCIILiteral("errorList"), WTFMove(value)); + } +}; + +class ParameterBundle : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + ColumnNamesSet = 1 << 0, + NotesSet = 1 << 1, + TimestampSet = 1 << 2, + ValuesSet = 1 << 3, + PayloadSet = 1 << 4, + ErrorSet = 1 << 5, + ErrorListSet = 1 << 6, + AllFieldsSet = (ColumnNamesSet | NotesSet | TimestampSet | ValuesSet | PayloadSet | ErrorSet | ErrorListSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*ParameterBundle*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class ParameterBundle; + public: + + Builder<STATE | ColumnNamesSet>& setColumnNames(RefPtr<Inspector::Protocol::Array<String>> value) + { + COMPILE_ASSERT(!(STATE & ColumnNamesSet), property_columnNames_already_set); + m_result->setArray(ASCIILiteral("columnNames"), value); + return castState<ColumnNamesSet>(); + } + + Builder<STATE | NotesSet>& setNotes(const String& value) + { + COMPILE_ASSERT(!(STATE & NotesSet), property_notes_already_set); + m_result->setString(ASCIILiteral("notes"), value); + return castState<NotesSet>(); + } + + Builder<STATE | TimestampSet>& setTimestamp(double value) + { + COMPILE_ASSERT(!(STATE & TimestampSet), property_timestamp_already_set); + m_result->setDouble(ASCIILiteral("timestamp"), value); + return castState<TimestampSet>(); + } + + Builder<STATE | ValuesSet>& setValues(RefPtr<Inspector::InspectorObject> value) + { + COMPILE_ASSERT(!(STATE & ValuesSet), property_values_already_set); + m_result->setObject(ASCIILiteral("values"), value); + return castState<ValuesSet>(); + } + + Builder<STATE | PayloadSet>& setPayload(RefPtr<Inspector::InspectorValue> value) + { + COMPILE_ASSERT(!(STATE & PayloadSet), property_payload_already_set); + m_result->setValue(ASCIILiteral("payload"), value); + return castState<PayloadSet>(); + } + + Builder<STATE | ErrorSet>& setError(RefPtr<Inspector::Protocol::Database::Error> value) + { + COMPILE_ASSERT(!(STATE & ErrorSet), property_error_already_set); + m_result->setObject(ASCIILiteral("error"), value); + return castState<ErrorSet>(); + } + + Builder<STATE | ErrorListSet>& setErrorList(RefPtr<Inspector::Protocol::Database::ErrorList> value) + { + COMPILE_ASSERT(!(STATE & ErrorListSet), property_errorList_already_set); + m_result->setArray(ASCIILiteral("errorList"), value); + return castState<ErrorListSet>(); + } + + Ref<ParameterBundle> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(ParameterBundle) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<ParameterBundle>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<ParameterBundle> result = ParameterBundle::create() + * .setColumnNames(...) + * .setNotes(...) + * .setTimestamp(...) + * .setValues(...) + * .setPayload(...) + * .setError(...) + * .setErrorList(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +/* Conflicted names may cause generated getters/setters to clash with built-in InspectorObject methods. */ +class ObjectWithPropertyNameConflicts : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + IntegerSet = 1 << 0, + ArraySet = 1 << 1, + StringSet = 1 << 2, + ValueSet = 1 << 3, + ObjectSet = 1 << 4, + AllFieldsSet = (IntegerSet | ArraySet | StringSet | ValueSet | ObjectSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*ObjectWithPropertyNameConflicts*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class ObjectWithPropertyNameConflicts; + public: + + Builder<STATE | IntegerSet>& setInteger(const String& value) + { + COMPILE_ASSERT(!(STATE & IntegerSet), property_integer_already_set); + m_result->setString(ASCIILiteral("integer"), value); + return castState<IntegerSet>(); + } + + Builder<STATE | ArraySet>& setArray(const String& value) + { + COMPILE_ASSERT(!(STATE & ArraySet), property_array_already_set); + m_result->setString(ASCIILiteral("array"), value); + return castState<ArraySet>(); + } + + Builder<STATE | StringSet>& setString(const String& value) + { + COMPILE_ASSERT(!(STATE & StringSet), property_string_already_set); + m_result->setString(ASCIILiteral("string"), value); + return castState<StringSet>(); + } + + Builder<STATE | ValueSet>& setValue(const String& value) + { + COMPILE_ASSERT(!(STATE & ValueSet), property_value_already_set); + m_result->setString(ASCIILiteral("value"), value); + return castState<ValueSet>(); + } + + Builder<STATE | ObjectSet>& setObject(const String& value) + { + COMPILE_ASSERT(!(STATE & ObjectSet), property_object_already_set); + m_result->setString(ASCIILiteral("object"), value); + return castState<ObjectSet>(); + } + + Ref<ObjectWithPropertyNameConflicts> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(ObjectWithPropertyNameConflicts) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<ObjectWithPropertyNameConflicts>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<ObjectWithPropertyNameConflicts> result = ObjectWithPropertyNameConflicts::create() + * .setInteger(...) + * .setArray(...) + * .setString(...) + * .setValue(...) + * .setObject(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +} // Database + +namespace Test { +class ParameterBundle : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + ColumnNamesSet = 1 << 0, + NotesSet = 1 << 1, + TimestampSet = 1 << 2, + ValuesSet = 1 << 3, + PayloadSet = 1 << 4, + ErrorSet = 1 << 5, + AllFieldsSet = (ColumnNamesSet | NotesSet | TimestampSet | ValuesSet | PayloadSet | ErrorSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*ParameterBundle*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class ParameterBundle; + public: + + Builder<STATE | ColumnNamesSet>& setColumnNames(RefPtr<Inspector::Protocol::Array<String>> value) + { + COMPILE_ASSERT(!(STATE & ColumnNamesSet), property_columnNames_already_set); + m_result->setArray(ASCIILiteral("columnNames"), value); + return castState<ColumnNamesSet>(); + } + + Builder<STATE | NotesSet>& setNotes(const String& value) + { + COMPILE_ASSERT(!(STATE & NotesSet), property_notes_already_set); + m_result->setString(ASCIILiteral("notes"), value); + return castState<NotesSet>(); + } + + Builder<STATE | TimestampSet>& setTimestamp(double value) + { + COMPILE_ASSERT(!(STATE & TimestampSet), property_timestamp_already_set); + m_result->setDouble(ASCIILiteral("timestamp"), value); + return castState<TimestampSet>(); + } + + Builder<STATE | ValuesSet>& setValues(RefPtr<Inspector::InspectorObject> value) + { + COMPILE_ASSERT(!(STATE & ValuesSet), property_values_already_set); + m_result->setObject(ASCIILiteral("values"), value); + return castState<ValuesSet>(); + } + + Builder<STATE | PayloadSet>& setPayload(RefPtr<Inspector::InspectorValue> value) + { + COMPILE_ASSERT(!(STATE & PayloadSet), property_payload_already_set); + m_result->setValue(ASCIILiteral("payload"), value); + return castState<PayloadSet>(); + } + + Builder<STATE | ErrorSet>& setError(RefPtr<Inspector::Protocol::Database::Error> value) + { + COMPILE_ASSERT(!(STATE & ErrorSet), property_error_already_set); + m_result->setObject(ASCIILiteral("error"), value); + return castState<ErrorSet>(); + } + + Ref<ParameterBundle> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(ParameterBundle) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<ParameterBundle>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<ParameterBundle> result = ParameterBundle::create() + * .setColumnNames(...) + * .setNotes(...) + * .setTimestamp(...) + * .setValues(...) + * .setPayload(...) + * .setError(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +} // Test + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolDatabaseError; +@class TestProtocolDatabaseOptionalParameterBundle; +@class TestProtocolDatabaseParameterBundle; +@class TestProtocolDatabaseObjectWithPropertyNameConflicts; +@class TestProtocolDatabaseDummyObject; +@class TestProtocolTestParameterBundle; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseError : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithMessage:(NSString *)message code:(int)code; +/* required */ @property (nonatomic, copy) NSString *message; +/* required */ @property (nonatomic, assign) int code; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseOptionalParameterBundle : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +/* optional */ @property (nonatomic, copy) NSArray/*<NSString>*/ *columnNames; +/* optional */ @property (nonatomic, copy) NSString *notes; +/* optional */ @property (nonatomic, assign) double timestamp; +/* optional */ @property (nonatomic, retain) RWIProtocolJSONObject *values; +/* optional */ @property (nonatomic, retain) RWIProtocolJSONObject *payload; +/* optional */ @property (nonatomic, retain) TestProtocolDatabaseError *error; +/* optional */ @property (nonatomic, copy) NSArray/*<TestProtocolDatabaseError>*/ *errorList; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseParameterBundle : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithColumnNames:(NSArray/*<NSString>*/ *)columnNames notes:(NSString *)notes timestamp:(double)timestamp values:(RWIProtocolJSONObject *)values payload:(RWIProtocolJSONObject *)payload error:(TestProtocolDatabaseError *)error errorList:(NSArray/*<TestProtocolDatabaseError>*/ *)errorList; +/* required */ @property (nonatomic, copy) NSArray/*<NSString>*/ *columnNames; +/* required */ @property (nonatomic, copy) NSString *notes; +/* required */ @property (nonatomic, assign) double timestamp; +/* required */ @property (nonatomic, retain) RWIProtocolJSONObject *values; +/* required */ @property (nonatomic, retain) RWIProtocolJSONObject *payload; +/* required */ @property (nonatomic, retain) TestProtocolDatabaseError *error; +/* required */ @property (nonatomic, copy) NSArray/*<TestProtocolDatabaseError>*/ *errorList; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseObjectWithPropertyNameConflicts : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithInteger:(NSString *)integer array:(NSString *)array string:(NSString *)string value:(NSString *)value object:(NSString *)object; +/* required */ @property (nonatomic, copy) NSString *integer; +/* required */ @property (nonatomic, copy) NSString *array; +/* required */ @property (nonatomic, copy) NSString *string; +/* required */ @property (nonatomic, copy) NSString *value; +/* required */ @property (nonatomic, copy) NSString *object; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolDatabaseDummyObject : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolTestParameterBundle : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithColumnNames:(NSArray/*<NSString>*/ *)columnNames notes:(NSString *)notes timestamp:(double)timestamp values:(RWIProtocolJSONObject *)values payload:(RWIProtocolJSONObject *)payload error:(TestProtocolDatabaseError *)error; +/* required */ @property (nonatomic, copy) NSArray/*<NSString>*/ *columnNames; +/* required */ @property (nonatomic, copy) NSString *notes; +/* required */ @property (nonatomic, assign) double timestamp; +/* required */ @property (nonatomic, retain) RWIProtocolJSONObject *values; +/* required */ @property (nonatomic, retain) RWIProtocolJSONObject *payload; +/* required */ @property (nonatomic, retain) TestProtocolDatabaseError *error; +@end + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + + + + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload; ++ (void)_parseErrorList:(NSArray/*<TestProtocolDatabaseError>*/ **)outValue fromPayload:(id)payload; ++ (void)_parseOptionalParameterBundle:(TestProtocolDatabaseOptionalParameterBundle **)outValue fromPayload:(id)payload; ++ (void)_parseParameterBundle:(TestProtocolDatabaseParameterBundle **)outValue fromPayload:(id)payload; ++ (void)_parseObjectWithPropertyNameConflicts:(TestProtocolDatabaseObjectWithPropertyNameConflicts **)outValue fromPayload:(id)payload; ++ (void)_parseDummyObject:(TestProtocolDatabaseDummyObject **)outValue fromPayload:(id)payload; + +@end +@interface TestProtocolTypeConversions (TestDomain) + ++ (void)_parseParameterBundle:(TestProtocolTestParameterBundle **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (DatabaseDomain) + ++ (void)_parseError:(TestProtocolDatabaseError **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseError alloc] initWithPayload:payload]; +} + ++ (void)_parseErrorList:(NSArray/*<TestProtocolDatabaseError>*/ **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSArray/*<TestProtocolDatabaseError>*/ class]); + *outValue = (NSArray/*<TestProtocolDatabaseError>*/ *)payload; +} + ++ (void)_parseOptionalParameterBundle:(TestProtocolDatabaseOptionalParameterBundle **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseOptionalParameterBundle alloc] initWithPayload:payload]; +} + ++ (void)_parseParameterBundle:(TestProtocolDatabaseParameterBundle **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseParameterBundle alloc] initWithPayload:payload]; +} + ++ (void)_parseObjectWithPropertyNameConflicts:(TestProtocolDatabaseObjectWithPropertyNameConflicts **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseObjectWithPropertyNameConflicts alloc] initWithPayload:payload]; +} + ++ (void)_parseDummyObject:(TestProtocolDatabaseDummyObject **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolDatabaseDummyObject alloc] initWithPayload:payload]; +} + +@end +@implementation TestProtocolTypeConversions (TestDomain) + ++ (void)_parseParameterBundle:(TestProtocolTestParameterBundle **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolTestParameterBundle alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-declaration-object-type.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolDatabaseError + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"message"], @"message"); + self.message = payload[@"message"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"code"], @"code"); + self.code = [payload[@"code"] integerValue]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithMessage:(NSString *)message code:(int)code +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(message, @"message"); + + self.message = message; + self.code = code; + + return self; +} + +- (void)setMessage:(NSString *)message +{ + [super setString:message forKey:@"message"]; +} + +- (NSString *)message +{ + return [super stringForKey:@"message"]; +} + +- (void)setCode:(int)code +{ + [super setInteger:code forKey:@"code"]; +} + +- (int)code +{ + return [super integerForKey:@"code"]; +} + +@end + +@implementation TestProtocolDatabaseOptionalParameterBundle + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + self.columnNames = objcArrayFromPayload<NSString>(payload[@"columnNames"]); + + self.notes = payload[@"notes"]; + + self.timestamp = [payload[@"timestamp"] doubleValue]; + + self.values = payload[@"values"]; + + self.payload = payload[@"payload"]; + + self.error = [[TestProtocolDatabaseError alloc] initWithPayload:payload[@"error"]]; + + self.errorList = objcArrayFromPayload<TestProtocolDatabaseError>(payload[@"errorList"]); + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (void)setColumnNames:(NSArray/*<NSString>*/ *)columnNames +{ + [super setInspectorArray:inspectorStringArray(columnNames) forKey:@"columnNames"]; +} + +- (NSArray/*<NSString>*/ *)columnNames +{ + return objcStringArray([super inspectorArrayForKey:@"columnNames"]); +} + +- (void)setNotes:(NSString *)notes +{ + [super setString:notes forKey:@"notes"]; +} + +- (NSString *)notes +{ + return [super stringForKey:@"notes"]; +} + +- (void)setTimestamp:(double)timestamp +{ + [super setDouble:timestamp forKey:@"timestamp"]; +} + +- (double)timestamp +{ + return [super doubleForKey:@"timestamp"]; +} + +- (void)setValues:(RWIProtocolJSONObject *)values +{ + [super setObject:values forKey:@"values"]; +} + +- (RWIProtocolJSONObject *)values +{ + return [[RWIProtocolJSONObject alloc] initWithInspectorObject:[[super objectForKey:@"values"] toInspectorObject].get()]; +} + +- (void)setPayload:(RWIProtocolJSONObject *)payload +{ + [super setObject:payload forKey:@"payload"]; +} + +- (RWIProtocolJSONObject *)payload +{ + return [[RWIProtocolJSONObject alloc] initWithInspectorObject:[[super objectForKey:@"payload"] toInspectorObject].get()]; +} + +- (void)setError:(TestProtocolDatabaseError *)error +{ + [super setObject:error forKey:@"error"]; +} + +- (TestProtocolDatabaseError *)error +{ + return [[TestProtocolDatabaseError alloc] initWithInspectorObject:[[super objectForKey:@"error"] toInspectorObject].get()]; +} + +- (void)setErrorList:(NSArray/*<TestProtocolDatabaseError>*/ *)errorList +{ + THROW_EXCEPTION_FOR_BAD_TYPE_IN_ARRAY(errorList, [TestProtocolDatabaseError class]); + [super setInspectorArray:inspectorObjectArray(errorList) forKey:@"errorList"]; +} + +- (NSArray/*<TestProtocolDatabaseError>*/ *)errorList +{ + return objcArray<TestProtocolDatabaseError>([super inspectorArrayForKey:@"errorList"]); +} + +@end + +@implementation TestProtocolDatabaseParameterBundle + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"columnNames"], @"columnNames"); + self.columnNames = objcArrayFromPayload<NSString>(payload[@"columnNames"]); + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"notes"], @"notes"); + self.notes = payload[@"notes"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"timestamp"], @"timestamp"); + self.timestamp = [payload[@"timestamp"] doubleValue]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"values"], @"values"); + self.values = payload[@"values"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"payload"], @"payload"); + self.payload = payload[@"payload"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"error"], @"error"); + self.error = [[TestProtocolDatabaseError alloc] initWithPayload:payload[@"error"]]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"errorList"], @"errorList"); + self.errorList = objcArrayFromPayload<TestProtocolDatabaseError>(payload[@"errorList"]); + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithColumnNames:(NSArray/*<NSString>*/ *)columnNames notes:(NSString *)notes timestamp:(double)timestamp values:(RWIProtocolJSONObject *)values payload:(RWIProtocolJSONObject *)payload error:(TestProtocolDatabaseError *)error errorList:(NSArray/*<TestProtocolDatabaseError>*/ *)errorList +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(notes, @"notes"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(values, @"values"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload, @"payload"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(error, @"error"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(errorList, @"errorList"); + THROW_EXCEPTION_FOR_BAD_TYPE_IN_ARRAY(errorList, [TestProtocolDatabaseError class]); + + self.columnNames = columnNames; + self.notes = notes; + self.timestamp = timestamp; + self.values = values; + self.payload = payload; + self.error = error; + self.errorList = errorList; + + return self; +} + +- (void)setColumnNames:(NSArray/*<NSString>*/ *)columnNames +{ + [super setInspectorArray:inspectorStringArray(columnNames) forKey:@"columnNames"]; +} + +- (NSArray/*<NSString>*/ *)columnNames +{ + return objcStringArray([super inspectorArrayForKey:@"columnNames"]); +} + +- (void)setNotes:(NSString *)notes +{ + [super setString:notes forKey:@"notes"]; +} + +- (NSString *)notes +{ + return [super stringForKey:@"notes"]; +} + +- (void)setTimestamp:(double)timestamp +{ + [super setDouble:timestamp forKey:@"timestamp"]; +} + +- (double)timestamp +{ + return [super doubleForKey:@"timestamp"]; +} + +- (void)setValues:(RWIProtocolJSONObject *)values +{ + [super setObject:values forKey:@"values"]; +} + +- (RWIProtocolJSONObject *)values +{ + return [[RWIProtocolJSONObject alloc] initWithInspectorObject:[[super objectForKey:@"values"] toInspectorObject].get()]; +} + +- (void)setPayload:(RWIProtocolJSONObject *)payload +{ + [super setObject:payload forKey:@"payload"]; +} + +- (RWIProtocolJSONObject *)payload +{ + return [[RWIProtocolJSONObject alloc] initWithInspectorObject:[[super objectForKey:@"payload"] toInspectorObject].get()]; +} + +- (void)setError:(TestProtocolDatabaseError *)error +{ + [super setObject:error forKey:@"error"]; +} + +- (TestProtocolDatabaseError *)error +{ + return [[TestProtocolDatabaseError alloc] initWithInspectorObject:[[super objectForKey:@"error"] toInspectorObject].get()]; +} + +- (void)setErrorList:(NSArray/*<TestProtocolDatabaseError>*/ *)errorList +{ + THROW_EXCEPTION_FOR_BAD_TYPE_IN_ARRAY(errorList, [TestProtocolDatabaseError class]); + [super setInspectorArray:inspectorObjectArray(errorList) forKey:@"errorList"]; +} + +- (NSArray/*<TestProtocolDatabaseError>*/ *)errorList +{ + return objcArray<TestProtocolDatabaseError>([super inspectorArrayForKey:@"errorList"]); +} + +@end + +@implementation TestProtocolDatabaseObjectWithPropertyNameConflicts + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"integer"], @"integer"); + self.integer = payload[@"integer"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"array"], @"array"); + self.array = payload[@"array"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"string"], @"string"); + self.string = payload[@"string"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"value"], @"value"); + self.value = payload[@"value"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"object"], @"object"); + self.object = payload[@"object"]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithInteger:(NSString *)integer array:(NSString *)array string:(NSString *)string value:(NSString *)value object:(NSString *)object +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(integer, @"integer"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(array, @"array"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(string, @"string"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(value, @"value"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(object, @"object"); + + self.integer = integer; + self.array = array; + self.string = string; + self.value = value; + self.object = object; + + return self; +} + +- (void)setInteger:(NSString *)integer +{ + [super setString:integer forKey:@"integer"]; +} + +- (NSString *)integer +{ + return [super stringForKey:@"integer"]; +} + +- (void)setArray:(NSString *)array +{ + [super setString:array forKey:@"array"]; +} + +- (NSString *)array +{ + return [super stringForKey:@"array"]; +} + +- (void)setString:(NSString *)string +{ + [super setString:string forKey:@"string"]; +} + +- (NSString *)string +{ + return [super stringForKey:@"string"]; +} + +- (void)setValue:(NSString *)value +{ + [super setString:value forKey:@"value"]; +} + +- (NSString *)value +{ + return [super stringForKey:@"value"]; +} + +- (void)setObject:(NSString *)object +{ + [super setString:object forKey:@"object"]; +} + +- (NSString *)object +{ + return [super stringForKey:@"object"]; +} + +@end + +@implementation TestProtocolDatabaseDummyObject + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +@end + + +@implementation TestProtocolTestParameterBundle + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"columnNames"], @"columnNames"); + self.columnNames = objcArrayFromPayload<NSString>(payload[@"columnNames"]); + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"notes"], @"notes"); + self.notes = payload[@"notes"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"timestamp"], @"timestamp"); + self.timestamp = [payload[@"timestamp"] doubleValue]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"values"], @"values"); + self.values = payload[@"values"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"payload"], @"payload"); + self.payload = payload[@"payload"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"error"], @"error"); + self.error = [[TestProtocolDatabaseError alloc] initWithPayload:payload[@"error"]]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithColumnNames:(NSArray/*<NSString>*/ *)columnNames notes:(NSString *)notes timestamp:(double)timestamp values:(RWIProtocolJSONObject *)values payload:(RWIProtocolJSONObject *)payload error:(TestProtocolDatabaseError *)error +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(columnNames, @"columnNames"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(notes, @"notes"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(values, @"values"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload, @"payload"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(error, @"error"); + + self.columnNames = columnNames; + self.notes = notes; + self.timestamp = timestamp; + self.values = values; + self.payload = payload; + self.error = error; + + return self; +} + +- (void)setColumnNames:(NSArray/*<NSString>*/ *)columnNames +{ + [super setInspectorArray:inspectorStringArray(columnNames) forKey:@"columnNames"]; +} + +- (NSArray/*<NSString>*/ *)columnNames +{ + return objcStringArray([super inspectorArrayForKey:@"columnNames"]); +} + +- (void)setNotes:(NSString *)notes +{ + [super setString:notes forKey:@"notes"]; +} + +- (NSString *)notes +{ + return [super stringForKey:@"notes"]; +} + +- (void)setTimestamp:(double)timestamp +{ + [super setDouble:timestamp forKey:@"timestamp"]; +} + +- (double)timestamp +{ + return [super doubleForKey:@"timestamp"]; +} + +- (void)setValues:(RWIProtocolJSONObject *)values +{ + [super setObject:values forKey:@"values"]; +} + +- (RWIProtocolJSONObject *)values +{ + return [[RWIProtocolJSONObject alloc] initWithInspectorObject:[[super objectForKey:@"values"] toInspectorObject].get()]; +} + +- (void)setPayload:(RWIProtocolJSONObject *)payload +{ + [super setObject:payload forKey:@"payload"]; +} + +- (RWIProtocolJSONObject *)payload +{ + return [[RWIProtocolJSONObject alloc] initWithInspectorObject:[[super objectForKey:@"payload"] toInspectorObject].get()]; +} + +- (void)setError:(TestProtocolDatabaseError *)error +{ + [super setObject:error forKey:@"error"]; +} + +- (TestProtocolDatabaseError *)error +{ + return [[TestProtocolDatabaseError alloc] initWithInspectorObject:[[super objectForKey:@"error"] toInspectorObject].get()]; +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-requiring-runtime-casts.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-requiring-runtime-casts.json-result new file mode 100644 index 000000000..893692982 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/type-requiring-runtime-casts.json-result @@ -0,0 +1,1617 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// Test. +InspectorBackend.registerEnum("Test.UncastedAnimals", {Pigs: "Pigs", Cows: "Cows", Cats: "Cats", Hens: "Hens"}); +InspectorBackend.registerEnum("Test.CastedAnimals", {Ducks: "Ducks", Hens: "Hens", Crows: "Crows", Flamingos: "Flamingos"}); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + + + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + + + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + + + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + +// Forward declarations. +namespace Test { +class TypeNeedingCast; +class RecursiveObject1; +class RecursiveObject2; +enum class UncastedAnimals; +enum class CastedAnimals; +} // Test +// End of forward declarations. + + +// Typedefs. +namespace Test { +typedef int CastedObjectId; +typedef int UncastedObjectId; +} // Test +// End of typedefs. + +namespace TestHelpers { + +String getEnumConstantValue(int code); + +template<typename T> String getEnumConstantValue(T enumValue) +{ + return getEnumConstantValue(static_cast<int>(enumValue)); +} + +} // namespace TestHelpers + +namespace Test { +/* A dummy type that requires runtime casts, and forces non-primitive referenced types to also emit runtime cast helpers. */ +class TypeNeedingCast : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + StringSet = 1 << 0, + NumberSet = 1 << 1, + AnimalsSet = 1 << 2, + IdSet = 1 << 3, + TreeSet = 1 << 4, + AllFieldsSet = (StringSet | NumberSet | AnimalsSet | IdSet | TreeSet) + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*TypeNeedingCast*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class TypeNeedingCast; + public: + + Builder<STATE | StringSet>& setString(const String& value) + { + COMPILE_ASSERT(!(STATE & StringSet), property_string_already_set); + m_result->setString(ASCIILiteral("string"), value); + return castState<StringSet>(); + } + + Builder<STATE | NumberSet>& setNumber(int value) + { + COMPILE_ASSERT(!(STATE & NumberSet), property_number_already_set); + m_result->setInteger(ASCIILiteral("number"), value); + return castState<NumberSet>(); + } + + Builder<STATE | AnimalsSet>& setAnimals(Inspector::Protocol::Test::CastedAnimals value) + { + COMPILE_ASSERT(!(STATE & AnimalsSet), property_animals_already_set); + m_result->setString(ASCIILiteral("animals"), Inspector::Protocol::TestHelpers::getEnumConstantValue(value)); + return castState<AnimalsSet>(); + } + + Builder<STATE | IdSet>& setId(int value) + { + COMPILE_ASSERT(!(STATE & IdSet), property_id_already_set); + m_result->setInteger(ASCIILiteral("id"), value); + return castState<IdSet>(); + } + + Builder<STATE | TreeSet>& setTree(RefPtr<Inspector::Protocol::Test::RecursiveObject1> value) + { + COMPILE_ASSERT(!(STATE & TreeSet), property_tree_already_set); + m_result->setObject(ASCIILiteral("tree"), value); + return castState<TreeSet>(); + } + + Ref<TypeNeedingCast> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(TypeNeedingCast) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<TypeNeedingCast>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<TypeNeedingCast> result = TypeNeedingCast::create() + * .setString(...) + * .setNumber(...) + * .setAnimals(...) + * .setId(...) + * .setTree(...) + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } +}; + +/* */ +enum class UncastedAnimals { + Pigs = 4, + Cows = 5, + Cats = 6, + Hens = 1, +}; // enum class UncastedAnimals +/* */ +enum class CastedAnimals { + Ducks = 0, + Hens = 1, + Crows = 2, + Flamingos = 3, +}; // enum class CastedAnimals +class RecursiveObject1 : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + AllFieldsSet = 0 + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*RecursiveObject1*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class RecursiveObject1; + public: + + Ref<RecursiveObject1> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(RecursiveObject1) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<RecursiveObject1>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<RecursiveObject1> result = RecursiveObject1::create() + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } + + void setObj(RefPtr<Inspector::Protocol::Test::RecursiveObject2> value) + { + InspectorObjectBase::setObject(ASCIILiteral("obj"), WTFMove(value)); + } +}; + +class RecursiveObject2 : public Inspector::InspectorObjectBase { +public: + enum { + NoFieldsSet = 0, + AllFieldsSet = 0 + }; + + template<int STATE> + class Builder { + private: + RefPtr<InspectorObject> m_result; + + template<int STEP> Builder<STATE | STEP>& castState() + { + return *reinterpret_cast<Builder<STATE | STEP>*>(this); + } + + Builder(Ref</*RecursiveObject2*/InspectorObject>&& object) + : m_result(WTFMove(object)) + { + COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); + } + friend class RecursiveObject2; + public: + + Ref<RecursiveObject2> release() + { + COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); + COMPILE_ASSERT(sizeof(RecursiveObject2) == sizeof(InspectorObject), cannot_cast); + + Ref<InspectorObject> result = m_result.releaseNonNull(); + return WTFMove(*reinterpret_cast<Ref<RecursiveObject2>*>(&result)); + } + }; + + /* + * Synthetic constructor: + * Ref<RecursiveObject2> result = RecursiveObject2::create() + * .release(); + */ + static Builder<NoFieldsSet> create() + { + return Builder<NoFieldsSet>(InspectorObject::create()); + } + + void setObj(RefPtr<Inspector::Protocol::Test::RecursiveObject1> value) + { + InspectorObjectBase::setObject(ASCIILiteral("obj"), WTFMove(value)); + } +}; + +} // Test + +template<> struct BindingTraits<Inspector::Protocol::Test::CastedAnimals> { +#if !ASSERT_DISABLED +static void assertValueHasExpectedType(Inspector::InspectorValue*); +#endif // !ASSERT_DISABLED +}; +template<> struct BindingTraits<Inspector::Protocol::Test::TypeNeedingCast> { +static RefPtr<Inspector::Protocol::Test::TypeNeedingCast> runtimeCast(RefPtr<Inspector::InspectorValue>&& value); +#if !ASSERT_DISABLED +static void assertValueHasExpectedType(Inspector::InspectorValue*); +#endif // !ASSERT_DISABLED +}; +template<> struct BindingTraits<Inspector::Protocol::Test::RecursiveObject1> { +#if !ASSERT_DISABLED +static void assertValueHasExpectedType(Inspector::InspectorValue*); +#endif // !ASSERT_DISABLED +}; +template<> struct BindingTraits<Inspector::Protocol::Test::RecursiveObject2> { +#if !ASSERT_DISABLED +static void assertValueHasExpectedType(Inspector::InspectorValue*); +#endif // !ASSERT_DISABLED +}; + +namespace TestHelpers { + +template<typename ProtocolEnumType> +std::optional<ProtocolEnumType> parseEnumValueFromString(const String&); + +// Enums in the 'Test' Domain +template<> +std::optional<Inspector::Protocol::Test::UncastedAnimals> parseEnumValueFromString<Inspector::Protocol::Test::UncastedAnimals>(const String&); +template<> +std::optional<Inspector::Protocol::Test::CastedAnimals> parseEnumValueFromString<Inspector::Protocol::Test::CastedAnimals>(const String&); + +} // namespace TestHelpers + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + +namespace TestHelpers { + +static const char* const enum_constant_values[] = { + "Ducks", + "Hens", + "Crows", + "Flamingos", + "Pigs", + "Cows", + "Cats", +}; + +String getEnumConstantValue(int code) { + return enum_constant_values[code]; +} + +// Enums in the 'Test' Domain +template<> +std::optional<Inspector::Protocol::Test::UncastedAnimals> parseEnumValueFromString<Inspector::Protocol::Test::UncastedAnimals>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Test::UncastedAnimals::Pigs, + (size_t)Inspector::Protocol::Test::UncastedAnimals::Cows, + (size_t)Inspector::Protocol::Test::UncastedAnimals::Cats, + (size_t)Inspector::Protocol::Test::UncastedAnimals::Hens, + }; + for (size_t i = 0; i < 4; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Test::UncastedAnimals)constantValues[i]; + + return std::nullopt; +} + +template<> +std::optional<Inspector::Protocol::Test::CastedAnimals> parseEnumValueFromString<Inspector::Protocol::Test::CastedAnimals>(const String& protocolString) +{ + static const size_t constantValues[] = { + (size_t)Inspector::Protocol::Test::CastedAnimals::Ducks, + (size_t)Inspector::Protocol::Test::CastedAnimals::Hens, + (size_t)Inspector::Protocol::Test::CastedAnimals::Crows, + (size_t)Inspector::Protocol::Test::CastedAnimals::Flamingos, + }; + for (size_t i = 0; i < 4; ++i) + if (protocolString == enum_constant_values[constantValues[i]]) + return (Inspector::Protocol::Test::CastedAnimals)constantValues[i]; + + return std::nullopt; +} + + +} // namespace TestHelpers + + + +#if !ASSERT_DISABLED +void BindingTraits<Inspector::Protocol::Test::CastedAnimals>::assertValueHasExpectedType(Inspector::InspectorValue* value) +{ + ASSERT_ARG(value, value); + String result; + bool castSucceeded = value->asString(result); + ASSERT(castSucceeded); + ASSERT(result == "Ducks" || result == "Hens" || result == "Crows" || result == "Flamingos"); +} +#endif // !ASSERT_DISABLED + +#if !ASSERT_DISABLED +void BindingTraits<Inspector::Protocol::Test::TypeNeedingCast>::assertValueHasExpectedType(Inspector::InspectorValue* value) +{ + ASSERT_ARG(value, value); + RefPtr<InspectorObject> object; + bool castSucceeded = value->asObject(object); + ASSERT_UNUSED(castSucceeded, castSucceeded); + { + InspectorObject::iterator stringPos = object->find(ASCIILiteral("string")); + ASSERT(stringPos != object->end()); + BindingTraits<String>::assertValueHasExpectedType(stringPos->value.get()); + } + { + InspectorObject::iterator numberPos = object->find(ASCIILiteral("number")); + ASSERT(numberPos != object->end()); + BindingTraits<int>::assertValueHasExpectedType(numberPos->value.get()); + } + { + InspectorObject::iterator animalsPos = object->find(ASCIILiteral("animals")); + ASSERT(animalsPos != object->end()); + BindingTraits<Inspector::Protocol::Test::CastedAnimals>::assertValueHasExpectedType(animalsPos->value.get()); + } + { + InspectorObject::iterator idPos = object->find(ASCIILiteral("id")); + ASSERT(idPos != object->end()); + BindingTraits<int>::assertValueHasExpectedType(idPos->value.get()); + } + { + InspectorObject::iterator treePos = object->find(ASCIILiteral("tree")); + ASSERT(treePos != object->end()); + BindingTraits<Inspector::Protocol::Test::RecursiveObject1>::assertValueHasExpectedType(treePos->value.get()); + } + + int foundPropertiesCount = 5; + if (foundPropertiesCount != object->size()) + FATAL("Unexpected properties in object: %s\n", object->toJSONString().ascii().data()); +} +#endif // !ASSERT_DISABLED + +RefPtr<Inspector::Protocol::Test::TypeNeedingCast> BindingTraits<Inspector::Protocol::Test::TypeNeedingCast>::runtimeCast(RefPtr<InspectorValue>&& value) +{ + RefPtr<InspectorObject> result; + bool castSucceeded = value->asObject(result); + ASSERT_UNUSED(castSucceeded, castSucceeded); +#if !ASSERT_DISABLED + BindingTraits<Inspector::Protocol::Test::TypeNeedingCast>::assertValueHasExpectedType(result.get()); +#endif // !ASSERT_DISABLED + COMPILE_ASSERT(sizeof(Inspector::Protocol::Test::TypeNeedingCast) == sizeof(InspectorObjectBase), type_cast_problem); + return static_cast<Inspector::Protocol::Test::TypeNeedingCast*>(static_cast<InspectorObjectBase*>(result.get())); +} + + +#if !ASSERT_DISABLED +void BindingTraits<Inspector::Protocol::Test::RecursiveObject1>::assertValueHasExpectedType(Inspector::InspectorValue* value) +{ + ASSERT_ARG(value, value); + RefPtr<InspectorObject> object; + bool castSucceeded = value->asObject(object); + ASSERT_UNUSED(castSucceeded, castSucceeded); + + int foundPropertiesCount = 0; + { + InspectorObject::iterator objPos = object->find(ASCIILiteral("obj")); + if (objPos != object->end()) { + BindingTraits<Inspector::Protocol::Test::RecursiveObject2>::assertValueHasExpectedType(objPos->value.get()); + ++foundPropertiesCount; + } + } + if (foundPropertiesCount != object->size()) + FATAL("Unexpected properties in object: %s\n", object->toJSONString().ascii().data()); +} +#endif // !ASSERT_DISABLED + +#if !ASSERT_DISABLED +void BindingTraits<Inspector::Protocol::Test::RecursiveObject2>::assertValueHasExpectedType(Inspector::InspectorValue* value) +{ + ASSERT_ARG(value, value); + RefPtr<InspectorObject> object; + bool castSucceeded = value->asObject(object); + ASSERT_UNUSED(castSucceeded, castSucceeded); + + int foundPropertiesCount = 0; + { + InspectorObject::iterator objPos = object->find(ASCIILiteral("obj")); + if (objPos != object->end()) { + BindingTraits<Inspector::Protocol::Test::RecursiveObject1>::assertValueHasExpectedType(objPos->value.get()); + ++foundPropertiesCount; + } + } + if (foundPropertiesCount != object->size()) + FATAL("Unexpected properties in object: %s\n", object->toJSONString().ascii().data()); +} +#endif // !ASSERT_DISABLED + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + + + +namespace Inspector { + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + +@class TestProtocolTestTypeNeedingCast; +@class TestProtocolTestRecursiveObject1; +@class TestProtocolTestRecursiveObject2; + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + +typedef NS_ENUM(NSInteger, TestProtocolTestUncastedAnimals) { + TestProtocolTestUncastedAnimalsPigs, + TestProtocolTestUncastedAnimalsCows, + TestProtocolTestUncastedAnimalsCats, + TestProtocolTestUncastedAnimalsHens, +}; + +typedef NS_ENUM(NSInteger, TestProtocolTestCastedAnimals) { + TestProtocolTestCastedAnimalsDucks, + TestProtocolTestCastedAnimalsHens, + TestProtocolTestCastedAnimalsCrows, + TestProtocolTestCastedAnimalsFlamingos, +}; + + +__attribute__((visibility ("default"))) +@interface TestProtocolTestTypeNeedingCast : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +- (instancetype)initWithString:(NSString *)string number:(int)number animals:(TestProtocolTestCastedAnimals)animals identifier:(int)identifier tree:(TestProtocolTestRecursiveObject1 *)tree; +/* required */ @property (nonatomic, copy) NSString *string; +/* required */ @property (nonatomic, assign) int number; +/* required */ @property (nonatomic, assign) TestProtocolTestCastedAnimals animals; +/* required */ @property (nonatomic, assign) int identifier; +/* required */ @property (nonatomic, retain) TestProtocolTestRecursiveObject1 *tree; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolTestRecursiveObject1 : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +/* optional */ @property (nonatomic, retain) TestProtocolTestRecursiveObject2 *obj; +@end + +__attribute__((visibility ("default"))) +@interface TestProtocolTestRecursiveObject2 : RWIProtocolJSONObject +- (instancetype)initWithPayload:(NSDictionary<NSString *, id> *)payload; +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject; +/* optional */ @property (nonatomic, retain) TestProtocolTestRecursiveObject1 *obj; +@end + + + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + + +inline String toProtocolString(TestProtocolTestUncastedAnimals value) +{ + switch(value) { + case TestProtocolTestUncastedAnimalsPigs: + return ASCIILiteral("Pigs"); + case TestProtocolTestUncastedAnimalsCows: + return ASCIILiteral("Cows"); + case TestProtocolTestUncastedAnimalsCats: + return ASCIILiteral("Cats"); + case TestProtocolTestUncastedAnimalsHens: + return ASCIILiteral("Hens"); + } +} + +template<> +inline std::optional<TestProtocolTestUncastedAnimals> fromProtocolString(const String& value) +{ + if (value == "Pigs") + return TestProtocolTestUncastedAnimalsPigs; + if (value == "Cows") + return TestProtocolTestUncastedAnimalsCows; + if (value == "Cats") + return TestProtocolTestUncastedAnimalsCats; + if (value == "Hens") + return TestProtocolTestUncastedAnimalsHens; + return std::nullopt; +} + +inline String toProtocolString(TestProtocolTestCastedAnimals value) +{ + switch(value) { + case TestProtocolTestCastedAnimalsDucks: + return ASCIILiteral("Ducks"); + case TestProtocolTestCastedAnimalsHens: + return ASCIILiteral("Hens"); + case TestProtocolTestCastedAnimalsCrows: + return ASCIILiteral("Crows"); + case TestProtocolTestCastedAnimalsFlamingos: + return ASCIILiteral("Flamingos"); + } +} + +template<> +inline std::optional<TestProtocolTestCastedAnimals> fromProtocolString(const String& value) +{ + if (value == "Ducks") + return TestProtocolTestCastedAnimalsDucks; + if (value == "Hens") + return TestProtocolTestCastedAnimalsHens; + if (value == "Crows") + return TestProtocolTestCastedAnimalsCrows; + if (value == "Flamingos") + return TestProtocolTestCastedAnimalsFlamingos; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + +@interface TestProtocolTypeConversions (TestDomain) + ++ (void)_parseTypeNeedingCast:(TestProtocolTestTypeNeedingCast **)outValue fromPayload:(id)payload; ++ (void)_parseCastedObjectId:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseUncastedObjectId:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseUncastedAnimals:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseCastedAnimals:(NSNumber **)outValue fromPayload:(id)payload; ++ (void)_parseRecursiveObject1:(TestProtocolTestRecursiveObject1 **)outValue fromPayload:(id)payload; ++ (void)_parseRecursiveObject2:(TestProtocolTestRecursiveObject2 **)outValue fromPayload:(id)payload; + +@end + +@implementation TestProtocolTypeConversions (TestDomain) + ++ (void)_parseTypeNeedingCast:(TestProtocolTestTypeNeedingCast **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolTestTypeNeedingCast alloc] initWithPayload:payload]; +} + ++ (void)_parseCastedObjectId:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSNumber class]); + *outValue = (NSNumber *)payload; +} + ++ (void)_parseUncastedObjectId:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSNumber class]); + *outValue = (NSNumber *)payload; +} + ++ (void)_parseUncastedAnimals:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolTestUncastedAnimals> result = Inspector::fromProtocolString<TestProtocolTestUncastedAnimals>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"UncastedAnimals"); + *outValue = @(result.value()); +} + ++ (void)_parseCastedAnimals:(NSNumber **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSString class]); + std::optional<TestProtocolTestCastedAnimals> result = Inspector::fromProtocolString<TestProtocolTestCastedAnimals>(payload); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(result, @"CastedAnimals"); + *outValue = @(result.value()); +} + ++ (void)_parseRecursiveObject1:(TestProtocolTestRecursiveObject1 **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolTestRecursiveObject1 alloc] initWithPayload:payload]; +} + ++ (void)_parseRecursiveObject2:(TestProtocolTestRecursiveObject2 **)outValue fromPayload:(id)payload +{ + THROW_EXCEPTION_FOR_BAD_TYPE(payload, [NSDictionary class]); + *outValue = [[TestProtocolTestRecursiveObject2 alloc] initWithPayload:payload]; +} + +@end + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from type-requiring-runtime-casts.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +@implementation TestProtocolTestTypeNeedingCast + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"string"], @"string"); + self.string = payload[@"string"]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"number"], @"number"); + self.number = [payload[@"number"] integerValue]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"animals"], @"animals"); + std::optional<TestProtocolTestCastedAnimals> animals = fromProtocolString<TestProtocolTestCastedAnimals>(payload[@"animals"]); + THROW_EXCEPTION_FOR_BAD_ENUM_VALUE(animals, @"animals"); + self.animals = animals.value(); + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"id"], @"id"); + self.identifier = [payload[@"id"] integerValue]; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(payload[@"tree"], @"tree"); + self.tree = [[TestProtocolTestRecursiveObject1 alloc] initWithPayload:payload[@"tree"]]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (instancetype)initWithString:(NSString *)string number:(int)number animals:(TestProtocolTestCastedAnimals)animals identifier:(int)identifier tree:(TestProtocolTestRecursiveObject1 *)tree +{ + if (!(self = [super init])) + return nil; + + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(string, @"string"); + THROW_EXCEPTION_FOR_REQUIRED_PROPERTY(tree, @"tree"); + + self.string = string; + self.number = number; + self.animals = animals; + self.identifier = identifier; + self.tree = tree; + + return self; +} + +- (void)setString:(NSString *)string +{ + [super setString:string forKey:@"string"]; +} + +- (NSString *)string +{ + return [super stringForKey:@"string"]; +} + +- (void)setNumber:(int)number +{ + [super setInteger:number forKey:@"number"]; +} + +- (int)number +{ + return [super integerForKey:@"number"]; +} + +- (void)setAnimals:(TestProtocolTestCastedAnimals)animals +{ + [super setString:toProtocolString(animals) forKey:@"animals"]; +} + +- (TestProtocolTestCastedAnimals)animals +{ + return fromProtocolString<TestProtocolTestCastedAnimals>([super stringForKey:@"animals"]).value(); +} + +- (void)setIdentifier:(int)identifier +{ + [super setInteger:identifier forKey:@"id"]; +} + +- (int)identifier +{ + return [super integerForKey:@"id"]; +} + +- (void)setTree:(TestProtocolTestRecursiveObject1 *)tree +{ + [super setObject:tree forKey:@"tree"]; +} + +- (TestProtocolTestRecursiveObject1 *)tree +{ + return [[TestProtocolTestRecursiveObject1 alloc] initWithInspectorObject:[[super objectForKey:@"tree"] toInspectorObject].get()]; +} + +@end + +@implementation TestProtocolTestRecursiveObject1 + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + self.obj = [[TestProtocolTestRecursiveObject2 alloc] initWithPayload:payload[@"obj"]]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (void)setObj:(TestProtocolTestRecursiveObject2 *)obj +{ + [super setObject:obj forKey:@"obj"]; +} + +- (TestProtocolTestRecursiveObject2 *)obj +{ + return [[TestProtocolTestRecursiveObject2 alloc] initWithInspectorObject:[[super objectForKey:@"obj"] toInspectorObject].get()]; +} + +@end + +@implementation TestProtocolTestRecursiveObject2 + +- (instancetype)initWithPayload:(nonnull NSDictionary<NSString *, id> *)payload +{ + if (!(self = [super init])) + return nil; + + self.obj = [[TestProtocolTestRecursiveObject1 alloc] initWithPayload:payload[@"obj"]]; + + return self; +} +- (instancetype)initWithJSONObject:(RWIProtocolJSONObject *)jsonObject +{ + if (!(self = [super initWithInspectorObject:[jsonObject toInspectorObject].get()])) + return nil; + + return self; +} + +- (void)setObj:(TestProtocolTestRecursiveObject1 *)obj +{ + [super setObject:obj forKey:@"obj"]; +} + +- (TestProtocolTestRecursiveObject1 *)obj +{ + return [[TestProtocolTestRecursiveObject1 alloc] initWithInspectorObject:[[super objectForKey:@"obj"] toInspectorObject].get()]; +} + +@end + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/worker-supported-domains.json-result b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/worker-supported-domains.json-result new file mode 100644 index 000000000..bb4dc2213 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/expected/worker-supported-domains.json-result @@ -0,0 +1,1121 @@ +### Begin File: InspectorBackendCommands.js +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +// DomainA. +InspectorBackend.registerCommand("DomainA.enable", [], []); +InspectorBackend.activateDomain("DomainA"); +InspectorBackend.workerSupportedDomain("DomainA"); + +// DomainB. +InspectorBackend.registerCommand("DomainB.enable", [], []); +InspectorBackend.activateDomain("DomainB"); +### End File: InspectorBackendCommands.js + +### Begin File: TestAlternateBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +#include "TestProtocolTypes.h" +#include <inspector/InspectorFrontendRouter.h> +#include <JavaScriptCore/InspectorBackendDispatcher.h> + +namespace Inspector { + +class AlternateBackendDispatcher { +public: + void setBackendDispatcher(RefPtr<BackendDispatcher>&& dispatcher) { m_backendDispatcher = WTFMove(dispatcher); } + BackendDispatcher* backendDispatcher() const { return m_backendDispatcher.get(); } +private: + RefPtr<BackendDispatcher> m_backendDispatcher; +}; + + +class AlternateDomainABackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateDomainABackendDispatcher() { } + virtual void enable(long callId) = 0; +}; +class AlternateDomainBBackendDispatcher : public AlternateBackendDispatcher { +public: + virtual ~AlternateDomainBBackendDispatcher() { } + virtual void enable(long callId) = 0; +}; + +} // namespace Inspector + +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +### End File: TestAlternateBackendDispatchers.h + +### Begin File: TestBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorBackendDispatcher.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +typedef String ErrorString; + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +class AlternateDomainABackendDispatcher; +class AlternateDomainBBackendDispatcher; +#endif // ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + +class DomainABackendDispatcherHandler { +public: + virtual void enable(ErrorString&) = 0; +protected: + virtual ~DomainABackendDispatcherHandler(); +}; + +class DomainBBackendDispatcherHandler { +public: + virtual void enable(ErrorString&) = 0; +protected: + virtual ~DomainBBackendDispatcherHandler(); +}; + +class DomainABackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<DomainABackendDispatcher> create(BackendDispatcher&, DomainABackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void enable(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateDomainABackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateDomainABackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + DomainABackendDispatcher(BackendDispatcher&, DomainABackendDispatcherHandler*); + DomainABackendDispatcherHandler* m_agent { nullptr }; +}; + +class DomainBBackendDispatcher final : public SupplementalBackendDispatcher { +public: + static Ref<DomainBBackendDispatcher> create(BackendDispatcher&, DomainBBackendDispatcherHandler*); + void dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) override; +private: + void enable(long requestId, RefPtr<InspectorObject>&& parameters); +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +public: + void setAlternateDispatcher(AlternateDomainBBackendDispatcher* alternateDispatcher) { m_alternateDispatcher = alternateDispatcher; } +private: + AlternateDomainBBackendDispatcher* m_alternateDispatcher { nullptr }; +#endif +private: + DomainBBackendDispatcher(BackendDispatcher&, DomainBBackendDispatcherHandler*); + DomainBBackendDispatcherHandler* m_agent { nullptr }; +}; + +} // namespace Inspector +### End File: TestBackendDispatchers.h + +### Begin File: TestBackendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestBackendDispatchers.h" + +#include <inspector/InspectorFrontendRouter.h> +#include <inspector/InspectorValues.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/CString.h> + +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) +#include "TestAlternateBackendDispatchers.h" +#endif + +namespace Inspector { + +DomainABackendDispatcherHandler::~DomainABackendDispatcherHandler() { } +DomainBBackendDispatcherHandler::~DomainBBackendDispatcherHandler() { } + +Ref<DomainABackendDispatcher> DomainABackendDispatcher::create(BackendDispatcher& backendDispatcher, DomainABackendDispatcherHandler* agent) +{ + return adoptRef(*new DomainABackendDispatcher(backendDispatcher, agent)); +} + +DomainABackendDispatcher::DomainABackendDispatcher(BackendDispatcher& backendDispatcher, DomainABackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("DomainA"), this); +} + +void DomainABackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<DomainABackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "enable") + enable(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "DomainA", '.', method, "' was not found")); +} + +void DomainABackendDispatcher::enable(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->enable(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->enable(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +Ref<DomainBBackendDispatcher> DomainBBackendDispatcher::create(BackendDispatcher& backendDispatcher, DomainBBackendDispatcherHandler* agent) +{ + return adoptRef(*new DomainBBackendDispatcher(backendDispatcher, agent)); +} + +DomainBBackendDispatcher::DomainBBackendDispatcher(BackendDispatcher& backendDispatcher, DomainBBackendDispatcherHandler* agent) + : SupplementalBackendDispatcher(backendDispatcher) + , m_agent(agent) +{ + m_backendDispatcher->registerDispatcherForDomain(ASCIILiteral("DomainB"), this); +} + +void DomainBBackendDispatcher::dispatch(long requestId, const String& method, Ref<InspectorObject>&& message) +{ + Ref<DomainBBackendDispatcher> protect(*this); + + RefPtr<InspectorObject> parameters; + message->getObject(ASCIILiteral("params"), parameters); + + if (method == "enable") + enable(requestId, WTFMove(parameters)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::MethodNotFound, makeString('\'', "DomainB", '.', method, "' was not found")); +} + +void DomainBBackendDispatcher::enable(long requestId, RefPtr<InspectorObject>&&) +{ +#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS) + if (m_alternateDispatcher) { + m_alternateDispatcher->enable(requestId); + return; + } +#endif + + ErrorString error; + Ref<InspectorObject> result = InspectorObject::create(); + m_agent->enable(error); + + if (!error.length()) + m_backendDispatcher->sendResponse(requestId, WTFMove(result)); + else + m_backendDispatcher->reportProtocolError(BackendDispatcher::ServerError, WTFMove(error)); +} + +} // namespace Inspector + +### End File: TestBackendDispatchers.cpp + +### Begin File: TestFrontendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include "TestProtocolObjects.h" +#include <inspector/InspectorValues.h> +#include <wtf/text/WTFString.h> + +namespace Inspector { + +class FrontendRouter; + +} // namespace Inspector +### End File: TestFrontendDispatchers.h + +### Begin File: TestFrontendDispatchers.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestFrontendDispatchers.h" + +#include "InspectorFrontendRouter.h" +#include <wtf/text/CString.h> + +namespace Inspector { + +} // namespace Inspector + +### End File: TestFrontendDispatchers.cpp + +### Begin File: TestProtocolObjects.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#pragma once + +#include <inspector/InspectorProtocolTypes.h> +#include <wtf/Assertions.h> + +namespace Inspector { + + + +namespace Protocol { + + + + + + + +} // namespace Protocol + +} // namespace Inspector +### End File: TestProtocolObjects.h + +### Begin File: TestProtocolObjects.cpp +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include "config.h" +#include "TestProtocolObjects.h" + +#include <wtf/Optional.h> +#include <wtf/text/CString.h> + +namespace Inspector { + +namespace Protocol { + + + +} // namespace Protocol + +} // namespace Inspector + +### End File: TestProtocolObjects.cpp + +### Begin File: TestProtocolBackendDispatchers.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#include <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#include <wtf/RetainPtr.h> + +@protocol TestProtocolDomainADomainHandler; +@protocol TestProtocolDomainBDomainHandler; + +namespace Inspector { + + +class ObjCInspectorDomainABackendDispatcher final : public AlternateDomainABackendDispatcher { +public: + ObjCInspectorDomainABackendDispatcher(id<TestProtocolDomainADomainHandler> handler) { m_delegate = handler; } + virtual void enable(long requestId) override; +private: + RetainPtr<id<TestProtocolDomainADomainHandler>> m_delegate; +}; + +class ObjCInspectorDomainBBackendDispatcher final : public AlternateDomainBBackendDispatcher { +public: + ObjCInspectorDomainBBackendDispatcher(id<TestProtocolDomainBDomainHandler> handler) { m_delegate = handler; } + virtual void enable(long requestId) override; +private: + RetainPtr<id<TestProtocolDomainBDomainHandler>> m_delegate; +}; + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.h + +### Begin File: TestProtocolBackendDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "config.h" +#import "TestProtocolBackendDispatchers.h" + +#include "TestProtocolInternal.h" +#include "TestProtocolTypeConversions.h" +#include <JavaScriptCore/InspectorValues.h> + +namespace Inspector { + +void ObjCInspectorDomainABackendDispatcher::enable(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate enableWithErrorCallback:errorCallback successCallback:successCallback]; +} + + +void ObjCInspectorDomainBBackendDispatcher::enable(long requestId) +{ + id errorCallback = ^(NSString *error) { + backendDispatcher()->reportProtocolError(requestId, BackendDispatcher::ServerError, error); + backendDispatcher()->sendPendingErrors(); + }; + + id successCallback = ^{ + backendDispatcher()->sendResponse(requestId, InspectorObject::create()); + }; + + [m_delegate enableWithErrorCallback:errorCallback successCallback:successCallback]; +} + + +} // namespace Inspector + +### End File: TestProtocolBackendDispatchers.mm + +### Begin File: TestProtocolConfiguration.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <WebInspector/TestProtocol.h> + +__attribute__((visibility ("default"))) +@interface TestProtocolConfiguration : NSObject +@property (nonatomic, retain, setter=setDomainAHandler:) id<TestProtocolDomainADomainHandler> domainAHandler; +@property (nonatomic, retain, setter=setDomainBHandler:) id<TestProtocolDomainBDomainHandler> domainBHandler; +@end + + +### End File: TestProtocolConfiguration.h + +### Begin File: TestProtocolConfiguration.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolConfiguration.h" + +#import "TestProtocolInternal.h" +#import "TestProtocolBackendDispatchers.h" +#import <JavaScriptCore/AlternateDispatchableAgent.h> +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorAlternateBackendDispatchers.h> +#import <JavaScriptCore/InspectorBackendDispatchers.h> + +using namespace Inspector; + +@implementation TestProtocolConfiguration +{ + AugmentableInspectorController* _controller; + id<TestProtocolDomainADomainHandler> _domainAHandler; + id<TestProtocolDomainBDomainHandler> _domainBHandler; +} + +- (instancetype)initWithController:(AugmentableInspectorController*)controller +{ + self = [super init]; + if (!self) + return nil; + ASSERT(controller); + _controller = controller; + return self; +} + +- (void)dealloc +{ + [_domainAHandler release]; + [_domainBHandler release]; + [super dealloc]; +} + +- (void)setDomainAHandler:(id<TestProtocolDomainADomainHandler>)handler +{ + if (handler == _domainAHandler) + return; + + [_domainAHandler release]; + _domainAHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorDomainABackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<DomainABackendDispatcher, AlternateDomainABackendDispatcher>>(ASCIILiteral("DomainA"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolDomainADomainHandler>)domainAHandler +{ + return _domainAHandler; +} + +- (void)setDomainBHandler:(id<TestProtocolDomainBDomainHandler>)handler +{ + if (handler == _domainBHandler) + return; + + [_domainBHandler release]; + _domainBHandler = [handler retain]; + + auto alternateDispatcher = std::make_unique<ObjCInspectorDomainBBackendDispatcher>(handler); + auto alternateAgent = std::make_unique<AlternateDispatchableAgent<DomainBBackendDispatcher, AlternateDomainBBackendDispatcher>>(ASCIILiteral("DomainB"), *_controller, WTFMove(alternateDispatcher)); + _controller->appendExtraAgent(WTFMove(alternateAgent)); +} + +- (id<TestProtocolDomainBDomainHandler>)domainBHandler +{ + return _domainBHandler; +} + +@end + + +### End File: TestProtocolConfiguration.mm + +### Begin File: TestProtocolEventDispatchers.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <JavaScriptCore/InspectorValues.h> + +using namespace Inspector; + + +### End File: TestProtocolEventDispatchers.mm + +### Begin File: TestProtocol.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import <Foundation/Foundation.h> + +#import <WebInspector/RWIProtocolJSONObject.h> + + + + +typedef NS_ENUM(NSInteger, TestProtocolPlatform) { + TestProtocolPlatformAll, + TestProtocolPlatformGeneric, + TestProtocolPlatformIOS, + TestProtocolPlatformMacOS, +}; + + + + + +@protocol TestProtocolDomainADomainHandler <NSObject> +@required +- (void)enableWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + +@protocol TestProtocolDomainBDomainHandler <NSObject> +@required +- (void)enableWithErrorCallback:(void(^)(NSString *error))errorCallback successCallback:(void(^)())successCallback; +@end + + + + +### End File: TestProtocol.h + +### Begin File: TestProtocolInternal.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import "TestProtocolJSONObjectPrivate.h" +#import <JavaScriptCore/AugmentableInspectorController.h> +#import <JavaScriptCore/InspectorValues.h> + + + + +### End File: TestProtocolInternal.h + +### Begin File: TestProtocolTypeConversions.h +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocol.h" +#import <WebInspector/RWIProtocolArrayConversions.h> + +namespace Inspector { + +template<typename ObjCEnumType> +std::optional<ObjCEnumType> fromProtocolString(const String& value); + +inline String toProtocolString(TestProtocolPlatform value) +{ + switch(value) { + case TestProtocolPlatformAll: + return ASCIILiteral("all"); + case TestProtocolPlatformGeneric: + return ASCIILiteral("generic"); + case TestProtocolPlatformIOS: + return ASCIILiteral("ios"); + case TestProtocolPlatformMacOS: + return ASCIILiteral("macos"); + } +} + +template<> +inline std::optional<TestProtocolPlatform> fromProtocolString(const String& value) +{ + if (value == "all") + return TestProtocolPlatformAll; + if (value == "generic") + return TestProtocolPlatformGeneric; + if (value == "ios") + return TestProtocolPlatformIOS; + if (value == "macos") + return TestProtocolPlatformMacOS; + return std::nullopt; +} + +} // namespace Inspector + +### End File: TestProtocolTypeConversions.h + +### Begin File: TestProtocolTypeConversions.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolTypeConversions.h" + +#import "TestProtocol.h" +#import "TestProtocolTypeParser.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> + +using namespace Inspector; + + + + + + +### End File: TestProtocolTypeConversions.mm + +### Begin File: TestProtocolTypes.mm +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013-2016 Apple Inc. All rights reserved. + * Copyright (C) 2014 University of Washington. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. + */ + +// DO NOT EDIT THIS FILE. It is automatically generated from worker-supported-domains.json +// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py + +#import "TestProtocolInternal.h" + +#import "TestProtocolTypeConversions.h" +#import <WebInspector/RWIProtocolJSONObjectPrivate.h> +#import <JavaScriptCore/InspectorValues.h> +#import <wtf/Assertions.h> + +using namespace Inspector; + + +### End File: TestProtocolTypes.mm diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-command-with-invalid-platform.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-command-with-invalid-platform.json new file mode 100644 index 000000000..a180cae9b --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-command-with-invalid-platform.json @@ -0,0 +1,16 @@ +{ + "domain": "Overlay", + "commands": [ + { + "name": "processPoints", + "platform": "invalid", + "parameters": [ + { "name": "point1", "type": "number" }, + { "name": "point2", "type": "number" } + ], + "returns": [ + { "name": "result", "type": "string" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-domain-availability.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-domain-availability.json new file mode 100644 index 000000000..36ee2c600 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-domain-availability.json @@ -0,0 +1,9 @@ +{ + "domain": "WebOnly", + "availability": "webb", + "commands": [ + { + "name": "enable" + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-command-call-parameter-names.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-command-call-parameter-names.json new file mode 100644 index 000000000..bab76ca62 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-command-call-parameter-names.json @@ -0,0 +1,16 @@ +{ + "domain": "Overlay", + "commands": [ + { + "name": "processPoints", + "parameters": [ + { "name": "point", "type": "number" }, + { "name": "point", "type": "number" } + ], + "returns": [ + { "name": "result1", "type": "string" }, + { "name": "result2", "type": "string" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-command-return-parameter-names.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-command-return-parameter-names.json new file mode 100644 index 000000000..c8bb15c04 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-command-return-parameter-names.json @@ -0,0 +1,16 @@ +{ + "domain": "Overlay", + "commands": [ + { + "name": "processPoints", + "parameters": [ + { "name": "point1", "type": "number" }, + { "name": "point2", "type": "number" } + ], + "returns": [ + { "name": "result", "type": "string" }, + { "name": "result", "type": "string" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-event-parameter-names.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-event-parameter-names.json new file mode 100644 index 000000000..d3d3b3cc6 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-event-parameter-names.json @@ -0,0 +1,12 @@ +{ + "domain": "Overlay", + "events": [ + { + "name": "processedPoints", + "parameters": [ + { "name": "point", "type": "number" }, + { "name": "point", "type": "number" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-type-declarations.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-type-declarations.json new file mode 100644 index 000000000..702fc6a32 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-type-declarations.json @@ -0,0 +1,15 @@ +{ + "domain": "Runtime", + "types": [ + { + "id": "RemoteObjectId", + "type": "string", + "description": "Unique object identifier." + }, + { + "id": "RemoteObjectId", + "type": "string", + "description": "Unique object identifier." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-type-member-names.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-type-member-names.json new file mode 100644 index 000000000..aebacee8b --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-duplicate-type-member-names.json @@ -0,0 +1,15 @@ +[ +{ + "domain": "OverlayTypes", + "types": [ + { + "id": "Point", + "type": "object", + "properties": [ + { "name": "x", "type": "integer" }, + { "name": "x", "type": "integer" } + ] + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-enum-with-no-values.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-enum-with-no-values.json new file mode 100644 index 000000000..232a7c324 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-enum-with-no-values.json @@ -0,0 +1,10 @@ +{ + "domain": "Database", + "types": [ + { + "id": "PrimaryColors", + "type": "string", + "enum": [] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-number-typed-optional-parameter-flag.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-number-typed-optional-parameter-flag.json new file mode 100644 index 000000000..7308db992 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-number-typed-optional-parameter-flag.json @@ -0,0 +1,18 @@ +{ + "domain": "Database", + "types": [ + { + "id": "DatabaseId", + "type": "string", + "description": "Unique identifier of Database object." + } + ], + "events": [ + { + "name": "didExecuteOptionalParameters", + "parameters": [ + { "name": "columnNames", "type": "string", "optional": 0 } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-number-typed-optional-type-member.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-number-typed-optional-type-member.json new file mode 100644 index 000000000..afea555ec --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-number-typed-optional-type-member.json @@ -0,0 +1,16 @@ +[ +{ + "domain": "Database", + "types": [ + { + "id": "Error", + "type": "object", + "description": "Database error.", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code.", "optional": 0 } + ] + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-string-typed-optional-parameter-flag.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-string-typed-optional-parameter-flag.json new file mode 100644 index 000000000..4012c79b6 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-string-typed-optional-parameter-flag.json @@ -0,0 +1,18 @@ +{ + "domain": "Database", + "types": [ + { + "id": "DatabaseId", + "type": "string", + "description": "Unique identifier of Database object." + } + ], + "events": [ + { + "name": "didExecuteOptionalParameters", + "parameters": [ + { "name": "columnNames", "type": "string", "optional": "true" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-string-typed-optional-type-member.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-string-typed-optional-type-member.json new file mode 100644 index 000000000..ca3ef28a8 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-string-typed-optional-type-member.json @@ -0,0 +1,16 @@ +[ +{ + "domain": "Database", + "types": [ + { + "id": "Error", + "type": "object", + "description": "Database error.", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code.", "optional": "false" } + ] + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-declaration-using-type-reference.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-declaration-using-type-reference.json new file mode 100644 index 000000000..19b7590cc --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-declaration-using-type-reference.json @@ -0,0 +1,13 @@ +[ +{ + "domain": "Runtime", + "types": [ + { + "id": "RemoteObjectId", + "type": "object", + "$ref": "SomeType", + "description": "Unique object identifier." + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-reference-as-primitive-type.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-reference-as-primitive-type.json new file mode 100644 index 000000000..8c83bbfce --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-reference-as-primitive-type.json @@ -0,0 +1,18 @@ +{ + "domain": "Database", + "types": [ + { + "id": "DatabaseId", + "type": "string", + "description": "Unique identifier of Database object." + } + ], + "events": [ + { + "name": "didExecuteOptionalParameters", + "parameters": [ + { "name": "columnNames", "type": "DatabaseId" } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-with-invalid-platform.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-with-invalid-platform.json new file mode 100644 index 000000000..a9fd2e995 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-with-invalid-platform.json @@ -0,0 +1,11 @@ +{ + "domain": "Runtime", + "types": [ + { + "id": "RemoteObjectId", + "type": "string", + "platform": "invalid", + "description": "Unique object identifier." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-with-lowercase-name.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-with-lowercase-name.json new file mode 100644 index 000000000..531901e4a --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-type-with-lowercase-name.json @@ -0,0 +1,10 @@ +{ + "domain": "Database", + "types": [ + { + "id": "databaseId", + "type": "integer", + "description": "Unique identifier of Database object." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-unknown-type-reference-in-type-declaration.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-unknown-type-reference-in-type-declaration.json new file mode 100644 index 000000000..d6887a274 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-unknown-type-reference-in-type-declaration.json @@ -0,0 +1,12 @@ +[ +{ + "domain": "Runtime", + "types": [ + { + "id": "RemoteObjectId", + "type": "dragon", + "description": "Unique object identifier." + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-unknown-type-reference-in-type-member.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-unknown-type-reference-in-type-member.json new file mode 100644 index 000000000..b817db504 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/fail-on-unknown-type-reference-in-type-member.json @@ -0,0 +1,15 @@ +[ +{ + "domain": "Fantasy", + "types": [ + { + "id": "DragonEgg", + "type": "object", + "description": "A dragon egg.", + "properties": [ + { "name": "color", "$ref": "Color" } + ] + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/generate-domains-with-feature-guards.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/generate-domains-with-feature-guards.json new file mode 100644 index 000000000..67cf8e582 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/generate-domains-with-feature-guards.json @@ -0,0 +1,36 @@ +[ +{ + "domain": "Network1", + "featureGuard": "PLATFORM(WEB_COMMANDS)", + "commands": [ + { + "name": "loadResource", + "description": "Loads a resource in the context of a frame on the inspected page without cross origin checks." + } + ] +}, +{ + "domain": "Network2", + "featureGuard": "PLATFORM(WEB_TYPES)", + "types": [ + { + "id": "NetworkError", + "type": "object", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + } + ] +}, +{ + "domain": "Network3", + "featureGuard": "PLATFORM(WEB_EVENTS)", + "events": [ + { + "name": "resourceLoaded", + "description": "A resource was loaded." + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/same-type-id-different-domain.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/same-type-id-different-domain.json new file mode 100644 index 000000000..3bf4dff5c --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/same-type-id-different-domain.json @@ -0,0 +1,22 @@ +[ +{ + "domain": "Runtime", + "types": [ + { + "id": "RemoteObjectId", + "type": "string", + "description": "Unique object identifier." + } + ] +}, +{ + "domain": "Runtime2", + "types": [ + { + "id": "RemoteObjectId", + "type": "string", + "description": "Unique object identifier." + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/shadowed-optional-type-setters.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/shadowed-optional-type-setters.json new file mode 100644 index 000000000..20a0c1552 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/shadowed-optional-type-setters.json @@ -0,0 +1,31 @@ +{ + "domain": "Runtime", + "types": [ + { + "id": "KeyPath", + "type": "object", + "description": "Key path.", + "properties": [ + { + "name": "type", + "type": "string", + "enum": ["null", "string", "array"], + "description": "Key path type." + }, + { + "name": "string", + "type": "string", + "optional": true, + "description": "String value." + }, + { + "name": "array", + "type": "array", + "optional": true, + "items": { "type": "string" }, + "description": "Array value." + } + ] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-aliased-primitive-type.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-aliased-primitive-type.json new file mode 100644 index 000000000..cbc9d5394 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-aliased-primitive-type.json @@ -0,0 +1,10 @@ +{ + "domain": "Runtime", + "types": [ + { + "id": "RemoteObjectId", + "type": "integer", + "description": "Unique object identifier." + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-array-type.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-array-type.json new file mode 100644 index 000000000..cfb08bd94 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-array-type.json @@ -0,0 +1,50 @@ +[ +{ + "domain": "Debugger", + "types": [ + { + "id": "BreakpointId", + "type": "integer" + }, + { + "id": "Reason", + "type": "string", + "enum": ["Died", "Fainted", "Hungry"] + } + ] +}, +{ + "domain": "Runtime", + "types": [ + { + "id": "ObjectId", + "type": "integer" + }, + { + "id": "LuckyNumbers", + "type": "array", + "items": { "type": "integer" } + }, + { + "id": "BabyNames", + "type": "array", + "items": { "type": "string" } + }, + { + "id": "NewObjects", + "type": "array", + "items": { "$ref": "ObjectId" } + }, + { + "id": "OldObjects", + "type": "array", + "items": { "$ref": "Debugger.BreakpointId" } + }, + { + "id": "StopReasons", + "type": "array", + "items": { "$ref": "Debugger.Reason" } + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-enum-type.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-enum-type.json new file mode 100644 index 000000000..9f0aee9c9 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-enum-type.json @@ -0,0 +1,15 @@ +{ + "domain": "Runtime", + "types": [ + { + "id": "FarmAnimals", + "type": "string", + "enum": ["Pigs", "Cows", "Cats", "Hens"] + }, + { + "id": "TwoLeggedAnimals", + "type": "string", + "enum": ["Ducks", "Hens", "Crows", "Flamingos"] + } + ] +} diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-object-type.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-object-type.json new file mode 100644 index 000000000..178309197 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-declaration-object-type.json @@ -0,0 +1,83 @@ +[ +{ + "domain": "Database", + "description": "Test type builder generation of various object types.", + "types": [ + { + "id": "Error", + "type": "object", + "description": "Database error.", + "properties": [ + { "name": "message", "type": "string", "description": "Error message." }, + { "name": "code", "type": "integer", "description": "Error code." } + ] + }, + { + "id": "ErrorList", + "type": "array", + "items": { "$ref": "Error" } + }, + { + "id": "OptionalParameterBundle", + "type": "object", + "properties": [ + { "name": "columnNames", "type": "array", "optional": true, "items": { "type": "string" } }, + { "name": "notes", "type": "string", "optional": true }, + { "name": "timestamp", "type": "number", "optional": true }, + { "name": "values", "type": "object", "optional": true }, + { "name": "payload", "type": "any", "optional": true }, + { "name": "error", "$ref": "Error", "optional": true }, + { "name": "errorList", "$ref": "ErrorList", "optional": true } + ] + }, + { + "id": "ParameterBundle", + "type": "object", + "properties": [ + { "name": "columnNames", "type": "array", "items": { "type": "string" } }, + { "name": "notes", "type": "string" }, + { "name": "timestamp", "type": "number" }, + { "name": "values", "type": "object" }, + { "name": "payload", "type": "any" }, + { "name": "error", "$ref": "Error" }, + { "name": "errorList", "$ref": "ErrorList" } + ] + }, + { + "id": "ObjectWithPropertyNameConflicts", + "description": "Conflicted names may cause generated getters/setters to clash with built-in InspectorObject methods.", + "type": "object", + "properties": [ + { "name": "integer", "type": "string" }, + { "name": "array", "type": "string" }, + { "name": "string", "type": "string" }, + { "name": "value", "type": "string" }, + { "name": "object", "type": "string" } + ] + }, + { + "id": "DummyObject", + "description": "An open object that doesn't have any predefined fields.", + "type": "object" + } + ] +}, +{ + "domain": "Test", + "description": "Test the generation of special behaviors that only apply to specific classes.", + "types": [ + { + "id": "ParameterBundle", + "type": "object", + "properties": [ + { "name": "columnNames", "type": "array", "items": { "type": "string" } }, + { "name": "notes", "type": "string" }, + { "name": "timestamp", "type": "number" }, + { "name": "values", "type": "object" }, + { "name": "payload", "type": "any" }, + { "name": "error", "$ref": "Database.Error" } + ] + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/type-requiring-runtime-casts.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-requiring-runtime-casts.json new file mode 100644 index 000000000..83d94be89 --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/type-requiring-runtime-casts.json @@ -0,0 +1,51 @@ +[ +{ + "domain": "Test", + "types": [ + { + "id": "TypeNeedingCast", + "type": "object", + "description": "A dummy type that requires runtime casts, and forces non-primitive referenced types to also emit runtime cast helpers.", + "properties": [ + { "name": "string", "type": "string", "description": "String member." }, + { "name": "number", "type": "integer", "description": "Number member." }, + { "name": "animals", "$ref": "CastedAnimals", "description": "Enum member." }, + { "name": "id", "$ref": "CastedObjectId", "description": "Aliased member." }, + { "name": "tree", "$ref": "RecursiveObject1", "description": "Recursive object member." } + ] + }, + { + "id": "CastedObjectId", + "type": "integer" + }, + { + "id": "UncastedObjectId", + "type": "integer" + }, + { + "id": "UncastedAnimals", + "type": "string", + "enum": ["Pigs", "Cows", "Cats", "Hens"] + }, + { + "id": "CastedAnimals", + "type": "string", + "enum": ["Ducks", "Hens", "Crows", "Flamingos"] + }, + { + "id": "RecursiveObject1", + "type": "object", + "properties": [ + { "name": "obj", "$ref": "RecursiveObject2", "optional": true } + ] + }, + { + "id": "RecursiveObject2", + "type": "object", + "properties": [ + { "name": "obj", "$ref": "RecursiveObject1", "optional": true } + ] + } + ] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/tests/generic/worker-supported-domains.json b/Source/JavaScriptCore/inspector/scripts/tests/generic/worker-supported-domains.json new file mode 100644 index 000000000..5e5889afc --- /dev/null +++ b/Source/JavaScriptCore/inspector/scripts/tests/generic/worker-supported-domains.json @@ -0,0 +1,11 @@ +[ +{ + "domain": "DomainA", + "workerSupported": true, + "commands": [{"name": "enable"}] +}, +{ + "domain": "DomainB", + "commands": [{"name": "enable"}] +} +] diff --git a/Source/JavaScriptCore/inspector/scripts/xxd.pl b/Source/JavaScriptCore/inspector/scripts/xxd.pl deleted file mode 100644 index 5ee08a52d..000000000 --- a/Source/JavaScriptCore/inspector/scripts/xxd.pl +++ /dev/null @@ -1,45 +0,0 @@ -#! /usr/bin/perl - -# Copyright (C) 2010-2011 Google Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# # Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# # Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# # Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -$varname = shift; -$fname = shift; -$output = shift; - -open($input, '<', $fname) or die "Can't open file for read: $fname $!"; -$/ = undef; -$text = <$input>; -close($input); - -$text = join(', ', map('0x' . unpack("H*", $_), split(undef, $text))); - -open($output, '>', $output) or die "Can't open file for write: $output $!"; -print $output "const unsigned char $varname\[\] = {\n$text\n};\n"; -close($output); |