diff options
author | blundell <blundell@chromium.org> | 2015-01-19 09:18:33 -0800 |
---|---|---|
committer | Commit bot <commit-bot@chromium.org> | 2015-01-19 17:19:27 +0000 |
commit | 70fb54767b472a5edfb859e489beeeec7abdb0e4 (patch) | |
tree | 28e534ec774391a9f6571a1770e12a0d63ebf833 /mojo/public/tools/bindings/generators | |
parent | ba5f0233fa38f949e24f6274ba891fa652eab640 (diff) | |
download | chromium_src-70fb54767b472a5edfb859e489beeeec7abdb0e4.zip chromium_src-70fb54767b472a5edfb859e489beeeec7abdb0e4.tar.gz chromium_src-70fb54767b472a5edfb859e489beeeec7abdb0e4.tar.bz2 |
Move //mojo/{public, edk} underneath //third_party
This CL move //mojo/public and //mojo/edk to live in the following locations:
- //third_party/mojo/src/mojo/public
- //third_party/mojo/src/mojo/edk
It moves the related gypfiles from //mojo to //third_party/mojo and updates
them as necessary to account for the file moves. It also updates clients of the
mojo SDK and EDK targets in both GYP and GN. (Note that for GN, the mojo SDK
and EDK build systems are maintained in the Mojo repo and designed to be
flexible wrt the location of the SDK/EDK in a client repo, so no changes are
needed.
This CL does not update include paths to the code being moved to limit the
number of moving parts, instead relying on the include_dirs that the SDK and
EDK targets supply to their direct dependents to ensure that include paths
continue to resolve correctly.
NOPRESUBMIT=true
Review URL: https://codereview.chromium.org/814543006
Cr-Commit-Position: refs/heads/master@{#312129}
Diffstat (limited to 'mojo/public/tools/bindings/generators')
51 files changed, 0 insertions, 4861 deletions
diff --git a/mojo/public/tools/bindings/generators/cpp_templates/enum_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/enum_declaration.tmpl deleted file mode 100644 index 86c85d7d..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/enum_declaration.tmpl +++ /dev/null @@ -1,9 +0,0 @@ -enum {{enum.name}} { -{%- for field in enum.fields %} -{%- if field.value %} - {{enum.name|to_all_caps}}_{{field.name}} = {{field.value|expression_to_text}}, -{%- else %} - {{enum.name|to_all_caps}}_{{field.name}}, -{%- endif %} -{%- endfor %} -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_declaration.tmpl deleted file mode 100644 index 30d20d8..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_declaration.tmpl +++ /dev/null @@ -1,49 +0,0 @@ -{%- import "interface_macros.tmpl" as interface_macros %} -class {{interface.name}}Proxy; -class {{interface.name}}Stub; - -class {{interface.name}}RequestValidator; -{%- if interface|has_callbacks %} -class {{interface.name}}ResponseValidator; -{%- endif %} -{% if interface.client %} -class {{interface.client}}; -{% endif %} - -class {{interface.name}} { - public: - static const char* Name_; - - typedef {{interface.name}}Proxy Proxy_; - typedef {{interface.name}}Stub Stub_; - - typedef {{interface.name}}RequestValidator RequestValidator_; -{%- if interface|has_callbacks %} - typedef {{interface.name}}ResponseValidator ResponseValidator_; -{%- else %} - typedef mojo::PassThroughFilter ResponseValidator_; -{%- endif %} -{% if interface.client %} - typedef {{interface.client}} Client; -{% else %} - typedef mojo::NoInterface Client; -{% endif %} - -{#--- Constants #} -{%- for constant in interface.constants %} - static const {{constant.kind|cpp_pod_type}} {{constant.name}}; -{%- endfor %} - -{#--- Enums #} -{%- for enum in interface.enums %} -{% macro enum_def() %}{% include "enum_declaration.tmpl" %}{% endmacro %} - {{enum_def()|indent(2)}} -{%- endfor %} - -{#--- Methods #} - virtual ~{{interface.name}}() {} - -{%- for method in interface.methods %} - virtual void {{method.name}}({{interface_macros.declare_request_params("", method)}}) = 0; -{%- endfor %} -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl deleted file mode 100644 index fdbe8ca..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl +++ /dev/null @@ -1,351 +0,0 @@ -{%- import "interface_macros.tmpl" as interface_macros %} -{%- set class_name = interface.name %} -{%- set proxy_name = interface.name ~ "Proxy" %} -{%- set namespace_as_string = "%s"|format(namespace|replace(".","::")) %} - -{%- macro alloc_params(parameters) %} -{%- for param in parameters %} -{%- if param.kind|is_object_kind %} -{{param.kind|cpp_result_type}} p{{loop.index}}; -Deserialize_(params->{{param.name}}.ptr, &p{{loop.index}}); -{% endif -%} -{%- endfor %} -{%- endmacro %} - -{%- macro pass_params(parameters) %} -{%- for param in parameters %} -{%- if param.kind|is_string_kind -%} -p{{loop.index}} -{%- elif param.kind|is_object_kind -%} -p{{loop.index}}.Pass() -{%- elif param.kind|is_interface_kind -%} -mojo::MakeProxy<{{param.kind|get_name_for_kind}}>(mojo::MakeScopedHandle(mojo::internal::FetchAndReset(¶ms->{{param.name}}))) -{%- elif param.kind|is_interface_request_kind -%} -mojo::MakeRequest<{{param.kind.kind|get_name_for_kind}}>(mojo::MakeScopedHandle(mojo::internal::FetchAndReset(¶ms->{{param.name}}))) -{%- elif param.kind|is_any_handle_kind -%} -mojo::MakeScopedHandle(mojo::internal::FetchAndReset(¶ms->{{param.name}})) -{%- elif param.kind|is_enum_kind -%} -static_cast<{{param.kind|cpp_wrapper_type}}>(params->{{param.name}}) -{%- else -%} -params->{{param.name}} -{%- endif -%} -{%- if not loop.last %}, {% endif %} -{%- endfor %} -{%- endmacro %} - -{%- macro compute_payload_size(params_name, parameters) -%} - size_t payload_size = - mojo::internal::Align(sizeof({{params_name}})); -{#--- Computes #} -{%- for param in parameters %} -{%- if param.kind|is_object_kind %} - payload_size += GetSerializedSize_(in_{{param.name}}); -{%- endif %} -{%- endfor %} -{%- endmacro %} - -{%- macro build_message(params_name, parameters, params_description) -%} - {# TODO(yzshen): Consider refactoring to share code with - struct_serialization_definition.tmpl #} - {{params_name}}* params = - {{params_name}}::New(builder.buffer()); -{#--- Sets #} -{% for param in parameters %} -{%- if param.kind|is_object_kind %} -{%- if param.kind|is_array_kind %} - mojo::SerializeArray_<{{param.kind|get_array_validate_params|indent(24)}}>( - mojo::internal::Forward(in_{{param.name}}), builder.buffer(), ¶ms->{{param.name}}.ptr); -{%- elif param.kind|is_map_kind %} - mojo::SerializeMap_<{{param.kind.value_kind|get_map_validate_params|indent(24)}}>( - mojo::internal::Forward(in_{{param.name}}), builder.buffer(), ¶ms->{{param.name}}.ptr); -{%- else %} - Serialize_(mojo::internal::Forward(in_{{param.name}}), builder.buffer(), ¶ms->{{param.name}}.ptr); -{%- endif %} -{%- if not param.kind|is_nullable_kind %} - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - !params->{{param.name}}.ptr, - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - "null {{param.name}} argument in {{params_description}}"); -{%- endif %} -{%- elif param.kind|is_any_handle_kind %} -{%- if param.kind|is_interface_kind or - param.kind|is_interface_request_kind %} - // Delegate handle. - params->{{param.name}} = in_{{param.name}}.PassMessagePipe().release(); -{%- else %} - params->{{param.name}} = in_{{param.name}}.release(); -{%- endif %} -{%- if not param.kind|is_nullable_kind %} - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - !params->{{param.name}}.is_valid(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, - "invalid {{param.name}} argument in {{params_description}}"); -{%- endif %} -{%- else %} - params->{{param.name}} = in_{{param.name}}; -{%- endif %} -{%- endfor %} - mojo::Message message; - params->EncodePointersAndHandles(message.mutable_handles()); - builder.Finish(&message); -{%- endmacro %} - -{#--- Begin #} -const char* {{class_name}}::Name_ = "{{namespace_as_string}}::{{class_name}}"; -{#--- Constants #} -{% for constant in interface.constants %} -const {{constant.kind|cpp_pod_type}} {{interface.name}}::{{constant.name}} = {{constant|constant_value}}; -{%- endfor %} - -{#--- ForwardToCallback definition #} -{%- for method in interface.methods -%} -{%- if method.response_parameters != None %} -class {{class_name}}_{{method.name}}_ForwardToCallback - : public mojo::MessageReceiver { - public: - {{class_name}}_{{method.name}}_ForwardToCallback( - const {{interface_macros.declare_callback(method)}}& callback) - : callback_(callback) { - } - virtual bool Accept(mojo::Message* message) override; - private: - {{interface_macros.declare_callback(method)}} callback_; - MOJO_DISALLOW_COPY_AND_ASSIGN({{class_name}}_{{method.name}}_ForwardToCallback); -}; -bool {{class_name}}_{{method.name}}_ForwardToCallback::Accept( - mojo::Message* message) { - internal::{{class_name}}_{{method.name}}_ResponseParams_Data* params = - reinterpret_cast<internal::{{class_name}}_{{method.name}}_ResponseParams_Data*>( - message->mutable_payload()); - - params->DecodePointersAndHandles(message->mutable_handles()); - {{alloc_params(method.response_parameters)|indent(2)}} - callback_.Run({{pass_params(method.response_parameters)}}); - return true; -} -{%- endif %} -{%- endfor %} - -{{proxy_name}}::{{proxy_name}}(mojo::MessageReceiverWithResponder* receiver) - : receiver_(receiver) { -} - -{#--- Proxy definitions #} - -{%- for method in interface.methods %} -{%- set message_name = - "internal::k%s_%s_Name"|format(interface.name, method.name) %} -{%- set params_name = - "internal::%s_%s_Params_Data"|format(interface.name, method.name) %} -{%- set params_description = - "%s.%s request"|format(interface.name, method.name) %} -void {{proxy_name}}::{{method.name}}( - {{interface_macros.declare_request_params("in_", method)}}) { - {{compute_payload_size(params_name, method.parameters)}} - -{%- if method.response_parameters != None %} - mojo::internal::RequestMessageBuilder builder({{message_name}}, payload_size); -{%- else %} - mojo::internal::MessageBuilder builder({{message_name}}, payload_size); -{%- endif %} - - {{build_message(params_name, method.parameters, params_description)}} - -{%- if method.response_parameters != None %} - mojo::MessageReceiver* responder = - new {{class_name}}_{{method.name}}_ForwardToCallback(callback); - if (!receiver_->AcceptWithResponder(&message, responder)) - delete responder; -{%- else %} - bool ok = receiver_->Accept(&message); - // This return value may be ignored as !ok implies the Connector has - // encountered an error, which will be visible through other means. - MOJO_ALLOW_UNUSED_LOCAL(ok); -{%- endif %} -} -{%- endfor %} - -{#--- ProxyToResponder definition #} -{%- for method in interface.methods -%} -{%- if method.response_parameters != None %} -{%- set message_name = - "internal::k%s_%s_Name"|format(interface.name, method.name) %} -{%- set params_name = - "internal::%s_%s_ResponseParams_Data"|format(interface.name, method.name) %} -{%- set params_description = - "%s.%s response"|format(interface.name, method.name) %} -class {{class_name}}_{{method.name}}_ProxyToResponder - : public {{interface_macros.declare_callback(method)}}::Runnable { - public: - virtual ~{{class_name}}_{{method.name}}_ProxyToResponder() { - delete responder_; - } - - {{class_name}}_{{method.name}}_ProxyToResponder( - uint64_t request_id, - mojo::MessageReceiver* responder) - : request_id_(request_id), - responder_(responder) { - } - - virtual void Run({{interface_macros.declare_params("in_", method.response_parameters)}}) const override; - - private: - uint64_t request_id_; - mutable mojo::MessageReceiver* responder_; - MOJO_DISALLOW_COPY_AND_ASSIGN({{class_name}}_{{method.name}}_ProxyToResponder); -}; -void {{class_name}}_{{method.name}}_ProxyToResponder::Run( - {{interface_macros.declare_params("in_", method.response_parameters)}}) const { - {{compute_payload_size(params_name, method.response_parameters)}} - mojo::internal::ResponseMessageBuilder builder( - {{message_name}}, payload_size, request_id_); - {{build_message(params_name, method.response_parameters, params_description)}} - bool ok = responder_->Accept(&message); - MOJO_ALLOW_UNUSED_LOCAL(ok); - // TODO(darin): !ok returned here indicates a malformed message, and that may - // be good reason to close the connection. However, we don't have a way to do - // that from here. We should add a way. - delete responder_; - responder_ = nullptr; -} -{%- endif -%} -{%- endfor %} - -{{class_name}}Stub::{{class_name}}Stub() - : sink_(nullptr) { -} - -{#--- Stub definition #} - -bool {{class_name}}Stub::Accept(mojo::Message* message) { -{%- if interface.methods %} - switch (message->header()->name) { -{%- for method in interface.methods %} - case internal::k{{class_name}}_{{method.name}}_Name: { -{%- if method.response_parameters == None %} - internal::{{class_name}}_{{method.name}}_Params_Data* params = - reinterpret_cast<internal::{{class_name}}_{{method.name}}_Params_Data*>( - message->mutable_payload()); - - params->DecodePointersAndHandles(message->mutable_handles()); - {{alloc_params(method.parameters)|indent(6)}} - // A null |sink_| typically means there is a missing call to - // InterfacePtr::set_client(). - assert(sink_); - sink_->{{method.name}}({{pass_params(method.parameters)}}); - return true; -{%- else %} - break; -{%- endif %} - } -{%- endfor %} - } -{%- endif %} - return false; -} - -bool {{class_name}}Stub::AcceptWithResponder( - mojo::Message* message, mojo::MessageReceiver* responder) { -{%- if interface.methods %} - switch (message->header()->name) { -{%- for method in interface.methods %} - case internal::k{{class_name}}_{{method.name}}_Name: { -{%- if method.response_parameters != None %} - internal::{{class_name}}_{{method.name}}_Params_Data* params = - reinterpret_cast<internal::{{class_name}}_{{method.name}}_Params_Data*>( - message->mutable_payload()); - - params->DecodePointersAndHandles(message->mutable_handles()); - {{interface_macros.declare_callback(method)}}::Runnable* runnable = - new {{class_name}}_{{method.name}}_ProxyToResponder( - message->request_id(), responder); - {{interface_macros.declare_callback(method)}} callback(runnable); - {{alloc_params(method.parameters)|indent(6)}} - // A null |sink_| typically means there is a missing call to - // InterfacePtr::set_client(). - assert(sink_); - sink_->{{method.name}}( -{%- if method.parameters -%}{{pass_params(method.parameters)}}, {% endif -%}callback); - return true; -{%- else %} - break; -{%- endif %} - } -{%- endfor %} - } -{%- endif %} - return false; -} - -{#--- Request validator definitions #} - -{{class_name}}RequestValidator::{{class_name}}RequestValidator( - mojo::MessageReceiver* sink) : MessageFilter(sink) { -} - -bool {{class_name}}RequestValidator::Accept(mojo::Message* message) { -{%- if interface.methods %} - switch (message->header()->name) { -{%- for method in interface.methods %} - case internal::k{{class_name}}_{{method.name}}_Name: { -{%- if method.response_parameters != None %} - if (!message->has_flag(mojo::internal::kMessageExpectsResponse)) - break; -{%- else %} - if (message->has_flag(mojo::internal::kMessageExpectsResponse) || - message->has_flag(mojo::internal::kMessageIsResponse)) { - break; - } -{%- endif %} - mojo::internal::BoundsChecker bounds_checker( - message->payload(), message->payload_num_bytes(), - message->handles()->size()); - if (!internal::{{class_name}}_{{method.name}}_Params_Data::Validate( - message->payload(), &bounds_checker)) { - return false; - } - break; - } -{%- endfor %} - } -{%- endif %} - - // A null |sink_| typically means there is a missing call to - // InterfacePtr::set_client(). - assert(sink_); - return sink_->Accept(message); -} - -{#--- Response validator definitions #} -{% if interface|has_callbacks %} -{{class_name}}ResponseValidator::{{class_name}}ResponseValidator( - mojo::MessageReceiver* sink) : MessageFilter(sink) { -} - -bool {{class_name}}ResponseValidator::Accept(mojo::Message* message) { -{%- if interface.methods %} - switch (message->header()->name) { -{%- for method in interface.methods if method.response_parameters != None %} - case internal::k{{class_name}}_{{method.name}}_Name: { - if (!message->has_flag(mojo::internal::kMessageIsResponse)) - break; - mojo::internal::BoundsChecker bounds_checker( - message->payload(), message->payload_num_bytes(), - message->handles()->size()); - if (!internal::{{class_name}}_{{method.name}}_ResponseParams_Data::Validate( - message->payload(), &bounds_checker)) { - return false; - } - break; - } -{%- endfor %} - } -{%- endif %} - - // A null |sink_| typically means there is a missing call to - // InterfacePtr::set_client(). - assert(sink_); - return sink_->Accept(message); -} -{%- endif -%} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_macros.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_macros.tmpl deleted file mode 100644 index fbefce2..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_macros.tmpl +++ /dev/null @@ -1,23 +0,0 @@ -{%- macro declare_params(prefix, parameters) %} -{%- for param in parameters -%} -{{param.kind|cpp_const_wrapper_type}} {{prefix}}{{param.name}} -{%- if not loop.last %}, {% endif %} -{%- endfor %} -{%- endmacro %} - -{%- macro declare_callback(method) -%} -mojo::Callback<void( -{%- for param in method.response_parameters -%} -{{param.kind|cpp_result_type}} -{%- if not loop.last %}, {% endif %} -{%- endfor -%} -)> -{%- endmacro -%} - -{%- macro declare_request_params(prefix, method) -%} -{{declare_params(prefix, method.parameters)}} -{%- if method.response_parameters != None -%} -{%- if method.parameters %}, {% endif %} -const {{declare_callback(method)}}& callback -{%- endif -%} -{%- endmacro -%} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_proxy_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_proxy_declaration.tmpl deleted file mode 100644 index 6b8e7c5..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_proxy_declaration.tmpl +++ /dev/null @@ -1,14 +0,0 @@ -{%- import "interface_macros.tmpl" as interface_macros %} -class {{interface.name}}Proxy : public {{interface.name}} { - public: - explicit {{interface.name}}Proxy(mojo::MessageReceiverWithResponder* receiver); - -{%- for method in interface.methods %} - virtual void {{method.name}}( - {{interface_macros.declare_request_params("", method)}} - ) override; -{%- endfor %} - - private: - mojo::MessageReceiverWithResponder* receiver_; -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_request_validator_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_request_validator_declaration.tmpl deleted file mode 100644 index 2239b69..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_request_validator_declaration.tmpl +++ /dev/null @@ -1,6 +0,0 @@ -class {{interface.name}}RequestValidator : public mojo::MessageFilter { - public: - explicit {{interface.name}}RequestValidator(mojo::MessageReceiver* sink = nullptr); - - virtual bool Accept(mojo::Message* message) override; -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_response_validator_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_response_validator_declaration.tmpl deleted file mode 100644 index 801603d..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_response_validator_declaration.tmpl +++ /dev/null @@ -1,6 +0,0 @@ -class {{interface.name}}ResponseValidator : public mojo::MessageFilter { - public: - explicit {{interface.name}}ResponseValidator(mojo::MessageReceiver* sink = nullptr); - - virtual bool Accept(mojo::Message* message) override; -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_stub_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_stub_declaration.tmpl deleted file mode 100644 index afc6504..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_stub_declaration.tmpl +++ /dev/null @@ -1,13 +0,0 @@ -class {{interface.name}}Stub : public mojo::MessageReceiverWithResponder { - public: - {{interface.name}}Stub(); - void set_sink({{interface.name}}* sink) { sink_ = sink; } - {{interface.name}}* sink() { return sink_; } - - virtual bool Accept(mojo::Message* message) override; - virtual bool AcceptWithResponder(mojo::Message* message, - mojo::MessageReceiver* responder) override; - - private: - {{interface.name}}* sink_; -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/module-internal.h.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/module-internal.h.tmpl deleted file mode 100644 index 116e86a..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/module-internal.h.tmpl +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -{%- set header_guard = "%s_INTERNAL_H_"| - format(module.path|upper|replace("/","_")|replace(".","_")) %} - -#ifndef {{header_guard}} -#define {{header_guard}} - -#include "mojo/public/cpp/bindings/lib/bindings_internal.h" -#include "mojo/public/cpp/bindings/lib/buffer.h" -#include "mojo/public/cpp/bindings/lib/union_accessor.h" -#include "mojo/public/cpp/bindings/struct_ptr.h" - -{%- for import in imports %} -#include "{{import.module.path}}-internal.h" -{%- endfor %} - -namespace mojo { -namespace internal { -class BoundsChecker; -} -} - -{%- for namespace in namespaces_as_array %} -namespace {{namespace}} { -{%- endfor %} - -{#--- Wrapper forward declarations #} -{% for struct in structs %} -class {{struct.name}}; -{%- endfor %} - -namespace internal { - -{#--- Internal forward declarations #} -{% for struct in structs %} -class {{struct.name}}_Data; -{%- endfor %} - -#pragma pack(push, 1) - -{#--- Class declarations #} -{% for struct in structs %} -{% include "struct_declaration.tmpl" %} -{%- endfor %} - -#pragma pack(pop) - -} // namespace internal -{%- for namespace in namespaces_as_array|reverse %} -} // namespace {{namespace}} -{%- endfor %} - -#endif // {{header_guard}} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/module.cc.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/module.cc.tmpl deleted file mode 100644 index 1ddcc45..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/module.cc.tmpl +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-private-field" -#elif defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable:4056) -#pragma warning(disable:4756) -#endif - -#include "{{module.path}}.h" - -#include <math.h> - -#include "mojo/public/cpp/bindings/lib/array_serialization.h" -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" -#include "mojo/public/cpp/bindings/lib/bounds_checker.h" -#include "mojo/public/cpp/bindings/lib/map_data_internal.h" -#include "mojo/public/cpp/bindings/lib/map_serialization.h" -#include "mojo/public/cpp/bindings/lib/message_builder.h" -#include "mojo/public/cpp/bindings/lib/string_serialization.h" -#include "mojo/public/cpp/bindings/lib/validate_params.h" -#include "mojo/public/cpp/bindings/lib/validation_errors.h" -#include "mojo/public/cpp/environment/logging.h" - -{%- for namespace in namespaces_as_array %} -namespace {{namespace}} { -{%- endfor %} - -{#--- Constants #} -{% for constant in module.constants %} -const {{constant.kind|cpp_pod_type}} {{constant.name}} = {{constant|constant_value}}; -{%- endfor %} - -namespace internal { -namespace { - -#pragma pack(push, 1) - -{#--- Interface parameter definitions #} -{%- for interface in interfaces %} -{%- for method in interface.methods %} -{%- set method_name = "k%s_%s_Name"|format(interface.name, method.name) %} -const uint32_t {{method_name}} = {{method.ordinal}}; -{% set struct = method|struct_from_method %} -{%- include "params_definition.tmpl" %} -{%- if method.response_parameters != None %} -{%- set struct = method|response_struct_from_method %} -{%- include "params_definition.tmpl" %} -{%- endif %} -{%- endfor %} -{%- endfor %} - -#pragma pack(pop) - -} // namespace - -{#--- Struct definitions #} -{% for struct in structs %} -{%- include "struct_definition.tmpl" %} -{%- endfor %} - -} // namespace internal - -{#--- Struct Constants #} -{%- for struct in structs %} -{% for constant in struct.constants %} -const {{constant.kind|cpp_pod_type}} {{struct.name}}::{{constant.name}} = {{constant|constant_value}}; -{%- endfor %} -{%- endfor %} - -{#--- Struct builder definitions #} -{%- for struct in structs %} -{%- include "wrapper_class_definition.tmpl" %} -{%- endfor %} - -{#--- Interface definitions #} -{%- for interface in interfaces %} -{%- include "interface_definition.tmpl" %} -{%- endfor %} - -{#--- Struct Serialization Helpers #} -{%- for struct in structs %} -{%- include "struct_serialization_definition.tmpl" %} -{%- endfor %} - -{%- for namespace in namespaces_as_array|reverse %} -} // namespace {{namespace}} -{%- endfor %} - -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(_MSC_VER) -#pragma warning(pop) -#endif diff --git a/mojo/public/tools/bindings/generators/cpp_templates/module.h.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/module.h.tmpl deleted file mode 100644 index 3da6c32..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/module.h.tmpl +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -{%- set header_guard = "%s_H_"| - format(module.path|upper|replace("/","_")|replace(".","_")) %} - -#ifndef {{header_guard}} -#define {{header_guard}} - -#include "mojo/public/cpp/bindings/array.h" -#include "mojo/public/cpp/bindings/callback.h" -#include "mojo/public/cpp/bindings/interface_impl.h" -#include "mojo/public/cpp/bindings/interface_ptr.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#include "mojo/public/cpp/bindings/map.h" -#include "mojo/public/cpp/bindings/message_filter.h" -#include "mojo/public/cpp/bindings/no_interface.h" -#include "mojo/public/cpp/bindings/string.h" -#include "mojo/public/cpp/bindings/struct_ptr.h" -#include "{{module.path}}-internal.h" -{%- for import in imports %} -#include "{{import.module.path}}.h" -{%- endfor %} - -{%- for namespace in namespaces_as_array %} -namespace {{namespace}} { -{%- endfor %} - -{#--- Constants #} -{% for constant in module.constants %} -extern const {{constant.kind|cpp_pod_type}} {{constant.name}}; -{%- endfor %} - -{#--- Enums #} -{% for enum in enums %} -{% include "enum_declaration.tmpl" %} -{%- endfor %} - -{#--- Interface Forward Declarations -#} -{% for interface in interfaces %} -class {{interface.name}}; -typedef mojo::InterfacePtr<{{interface.name}}> {{interface.name}}Ptr; -{% endfor %} - -{#--- Struct Forward Declarations -#} -{% for struct in structs %} -class {{struct.name}}; -{% if struct|should_inline %} -typedef mojo::InlinedStructPtr<{{struct.name}}> {{struct.name}}Ptr; -{% else %} -typedef mojo::StructPtr<{{struct.name}}> {{struct.name}}Ptr; -{% endif %} -{% endfor %} - -{#--- NOTE: Non-inlined structs may have pointers to inlined structs, so we #} -{#--- need to fully define inlined structs ahead of the others. #} - -{#--- Inlined structs #} -{% for struct in structs %} -{% if struct|should_inline %} -{% include "wrapper_class_declaration.tmpl" %} -{% endif %} -{%- endfor %} - -{#--- Non-inlined structs #} -{% for struct in structs %} -{% if not struct|should_inline %} -{% include "wrapper_class_declaration.tmpl" %} -{% endif %} -{%- endfor %} - -{#--- Interfaces -#} -{% for interface in interfaces %} -{% include "interface_declaration.tmpl" %} -{%- endfor %} - -{#--- Interface Proxies -#} -{% for interface in interfaces %} -{% include "interface_proxy_declaration.tmpl" %} -{%- endfor %} - -{#--- Interface Stubs -#} -{% for interface in interfaces %} -{% include "interface_stub_declaration.tmpl" %} -{%- endfor %} - -{#--- Interface Request Validators -#} -{% for interface in interfaces %} -{% include "interface_request_validator_declaration.tmpl" %} -{%- endfor %} - -{#--- Interface Response Validators -#} -{% for interface in interfaces if interface|has_callbacks %} -{% include "interface_response_validator_declaration.tmpl" %} -{%- endfor %} - -{#--- Struct Serialization Helpers -#} -{% if structs %} -{% for struct in structs %} -{% include "struct_serialization_declaration.tmpl" %} -{%- endfor %} -{%- endif %} - -{%- for namespace in namespaces_as_array|reverse %} -} // namespace {{namespace}} -{%- endfor %} - -#endif // {{header_guard}} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/params_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/params_definition.tmpl deleted file mode 100644 index 5de77d3..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/params_definition.tmpl +++ /dev/null @@ -1,33 +0,0 @@ -{%- import "struct_macros.tmpl" as struct_macros %} -{%- set class_name = struct.name ~ "_Data" %} -class {{class_name}} { - public: - static {{class_name}}* New(mojo::internal::Buffer* buf) { - return new (buf->Allocate(sizeof({{class_name}}))) - {{class_name}}(); - } - - static bool Validate(const void* data, - mojo::internal::BoundsChecker* bounds_checker) { - {{ struct_macros.validate(struct, class_name)|indent(4) }} - } - - mojo::internal::StructHeader header_; -{{struct_macros.fields(struct)}} - - void EncodePointersAndHandles(std::vector<mojo::Handle>* handles) { - {{ struct_macros.encodes(struct)|indent(4) }} - } - - void DecodePointersAndHandles(std::vector<mojo::Handle>* handles) { - {{ struct_macros.decodes(struct)|indent(4) }} - } - - private: - {{class_name}}() { - header_.num_bytes = sizeof(*this); - header_.num_fields = {{struct.packed.packed_fields|length}}; - } -}; -static_assert(sizeof({{class_name}}) == {{struct.packed|struct_size}}, - "Bad sizeof({{class_name}})"); diff --git a/mojo/public/tools/bindings/generators/cpp_templates/struct_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/struct_declaration.tmpl deleted file mode 100644 index 34c0f11..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/struct_declaration.tmpl +++ /dev/null @@ -1,22 +0,0 @@ -{%- import "struct_macros.tmpl" as struct_macros %} -{%- set class_name = struct.name ~ "_Data" -%} - -class {{class_name}} { - public: - static {{class_name}}* New(mojo::internal::Buffer* buf); - - static bool Validate(const void* data, - mojo::internal::BoundsChecker* bounds_checker); - - mojo::internal::StructHeader header_; -{{struct_macros.fields(struct)}} - - void EncodePointersAndHandles(std::vector<mojo::Handle>* handles); - void DecodePointersAndHandles(std::vector<mojo::Handle>* handles); - - private: - {{class_name}}(); - ~{{class_name}}() = delete; -}; -static_assert(sizeof({{class_name}}) == {{struct.packed|struct_size}}, - "Bad sizeof({{class_name}})"); diff --git a/mojo/public/tools/bindings/generators/cpp_templates/struct_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/struct_definition.tmpl deleted file mode 100644 index 461f158..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/struct_definition.tmpl +++ /dev/null @@ -1,28 +0,0 @@ -{%- import "struct_macros.tmpl" as struct_macros %} -{%- set class_name = struct.name ~ "_Data" %} - -// static -{{class_name}}* {{class_name}}::New(mojo::internal::Buffer* buf) { - return new (buf->Allocate(sizeof({{class_name}}))) {{class_name}}(); -} - -// static -bool {{class_name}}::Validate(const void* data, - mojo::internal::BoundsChecker* bounds_checker) { - {{ struct_macros.validate(struct, class_name)|indent(2) }} -} - -{{class_name}}::{{class_name}}() { - header_.num_bytes = sizeof(*this); - header_.num_fields = {{struct.packed.packed_fields|length}}; -} - -void {{class_name}}::EncodePointersAndHandles( - std::vector<mojo::Handle>* handles) { - {{ struct_macros.encodes(struct)|indent(2) }} -} - -void {{class_name}}::DecodePointersAndHandles( - std::vector<mojo::Handle>* handles) { - {{ struct_macros.decodes(struct)|indent(2) }} -} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/struct_macros.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/struct_macros.tmpl deleted file mode 100644 index 623ebb4..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/struct_macros.tmpl +++ /dev/null @@ -1,124 +0,0 @@ -{%- macro validate(struct, class_name) %} - if (!data) - return true; - - if (!ValidateStructHeader( - data, sizeof({{class_name}}), - {{struct.packed.packed_fields|length}}, bounds_checker)) { - return false; - } - - const {{class_name}}* object = static_cast<const {{class_name}}*>(data); - MOJO_ALLOW_UNUSED_LOCAL(object); - -{%- for packed_field in struct.packed.packed_fields %} -{%- set name = packed_field.field.name %} -{%- set kind = packed_field.field.kind %} -{%- if kind|is_object_kind %} -{%- set wrapper_type = kind|cpp_wrapper_type %} -{%- if not kind|is_nullable_kind %} - if (!object->{{name}}.offset) { - ReportValidationError( - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - "null {{name}} field in {{struct.name}} struct"); - return false; - } -{%- endif %} - if (!mojo::internal::ValidateEncodedPointer(&object->{{name}}.offset)) { - ReportValidationError(mojo::internal::VALIDATION_ERROR_ILLEGAL_POINTER); - return false; - } -{%- if kind|is_array_kind or kind|is_string_kind %} - if (!{{wrapper_type}}::Data_::Validate< - {{kind|get_array_validate_params|indent(10)}}>( - mojo::internal::DecodePointerRaw(&object->{{name}}.offset), - bounds_checker)) { -{%- elif kind|is_map_kind %} - if (!{{wrapper_type}}::Data_::Validate< - {{kind.value_kind|get_map_validate_params|indent(10)}}>( - mojo::internal::DecodePointerRaw(&object->{{name}}.offset), - bounds_checker)) { -{%- elif kind|is_struct_kind %} - if (!{{kind|get_name_for_kind}}::Data_::Validate( - mojo::internal::DecodePointerRaw(&object->{{name}}.offset), - bounds_checker)) { -{%- else %} - if (!{{wrapper_type}}::Data_::Validate( - mojo::internal::DecodePointerRaw(&object->{{name}}.offset), - bounds_checker)) { -{%- endif %} - return false; - } -{%- elif kind|is_any_handle_kind %} -{%- if not kind|is_nullable_kind %} - if (object->{{name}}.value() == mojo::internal::kEncodedInvalidHandleValue) { - ReportValidationError( - mojo::internal::VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, - "invalid {{name}} field in {{struct.name}} struct"); - return false; - } -{%- endif %} - if (!bounds_checker->ClaimHandle(object->{{name}})) { - ReportValidationError(mojo::internal::VALIDATION_ERROR_ILLEGAL_HANDLE); - return false; - } -{%- endif %} -{%- endfor %} - - return true; -{%- endmacro %} - -{%- macro field_line(field) %} -{%- set type = field.kind|cpp_field_type %} -{%- set name = field.name -%} -{%- if field.kind.spec == 'b' -%} - uint8_t {{name}} : 1; -{%- elif field.kind|is_enum_kind -%} - int32_t {{name}}; -{%- else -%} - {{type}} {{name}}; -{%- endif %} -{%- endmacro %} - -{%- macro fields(struct) %} -{%- for packed_field in struct.packed.packed_fields %} - {{field_line(packed_field.field)}} -{%- if not loop.last %} -{%- set next_pf = struct.packed.packed_fields[loop.index0 + 1] %} -{%- set pad = next_pf.offset - (packed_field.offset + packed_field.size) %} -{%- if pad > 0 %} - uint8_t pad{{loop.index0}}_[{{pad}}]; -{%- endif %} -{%- endif %} -{%- endfor -%} - -{%- set num_fields = struct.packed.packed_fields|length %} -{%- if num_fields > 0 %} -{%- set last_field = struct.packed.packed_fields[num_fields - 1] %} -{%- set offset = last_field.offset + last_field.size %} -{%- set pad = offset|get_pad(8) -%} -{%- if pad > 0 %} - uint8_t padfinal_[{{pad}}]; -{%- endif %} -{%- endif %} -{%- endmacro %} - -{%- macro encodes(struct) -%} -{%- for pf in struct.packed.packed_fields %} -{%- if pf.field.kind|is_object_kind %} -mojo::internal::Encode(&{{pf.field.name}}, handles); -{%- elif pf.field.kind|is_any_handle_kind %} -mojo::internal::EncodeHandle(&{{pf.field.name}}, handles); -{%- endif %} -{%- endfor %} -{%- endmacro -%} - -{%- macro decodes(struct) -%} -{%- for pf in struct.packed.packed_fields %} -{%- if pf.field.kind|is_object_kind %} -mojo::internal::Decode(&{{pf.field.name}}, handles); -{%- elif pf.field.kind|is_any_handle_kind %} -mojo::internal::DecodeHandle(&{{pf.field.name}}, handles); -{%- endif %} -{%- endfor %} -{%- endmacro -%} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_declaration.tmpl deleted file mode 100644 index 604be86..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_declaration.tmpl +++ /dev/null @@ -1,5 +0,0 @@ -size_t GetSerializedSize_(const {{struct.name}}Ptr& input); -void Serialize_({{struct.name}}Ptr input, mojo::internal::Buffer* buffer, - internal::{{struct.name}}_Data** output); -void Deserialize_(internal::{{struct.name}}_Data* input, - {{struct.name}}Ptr* output); diff --git a/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_definition.tmpl deleted file mode 100644 index 1612bbe..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_definition.tmpl +++ /dev/null @@ -1,78 +0,0 @@ -size_t GetSerializedSize_(const {{struct.name}}Ptr& input) { - if (!input) - return 0; - size_t size = sizeof(internal::{{struct.name}}_Data); -{%- for pf in struct.packed.packed_fields if pf.field.kind|is_object_kind %} - size += GetSerializedSize_(input->{{pf.field.name}}); -{%- endfor %} - return size; -} - -void Serialize_({{struct.name}}Ptr input, mojo::internal::Buffer* buf, - internal::{{struct.name}}_Data** output) { - if (input) { - internal::{{struct.name}}_Data* result = - internal::{{struct.name}}_Data::New(buf); -{%- for pf in struct.packed.packed_fields %} -{%- if pf.field.kind|is_object_kind %} -{%- if pf.field.kind|is_array_kind %} - mojo::SerializeArray_<{{pf.field.kind|get_array_validate_params|indent(26)}}>( - mojo::internal::Forward(input->{{pf.field.name}}), buf, &result->{{pf.field.name}}.ptr); -{%- elif pf.field.kind|is_map_kind %} - mojo::SerializeMap_<{{pf.field.kind.value_kind|get_map_validate_params|indent(26)}}>( - mojo::internal::Forward(input->{{pf.field.name}}), buf, &result->{{pf.field.name}}.ptr); -{%- else %} - Serialize_(mojo::internal::Forward(input->{{pf.field.name}}), buf, &result->{{pf.field.name}}.ptr); -{%- endif %} -{%- if not pf.field.kind|is_nullable_kind %} - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - !result->{{pf.field.name}}.ptr, - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - "null {{pf.field.name}} field in {{struct.name}} struct"); -{%- endif %} -{%- elif pf.field.kind|is_any_handle_kind %} -{%- if pf.field.kind|is_interface_kind %} - result->{{pf.field.name}} = input->{{pf.field.name}}.PassMessagePipe().release(); -{%- else %} - result->{{pf.field.name}} = input->{{pf.field.name}}.release(); -{%- endif %} -{%- if not pf.field.kind|is_nullable_kind %} - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - !result->{{pf.field.name}}.is_valid(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, - "invalid {{pf.field.name}} field in {{struct.name}} struct"); -{%- endif %} -{%- else %} - result->{{pf.field.name}} = input->{{pf.field.name}}; -{%- endif %} -{%- endfor %} - *output = result; - } else { - *output = nullptr; - } -} - -void Deserialize_(internal::{{struct.name}}_Data* input, - {{struct.name}}Ptr* output) { - if (input) { - {{struct.name}}Ptr result({{struct.name}}::New()); -{%- for pf in struct.packed.packed_fields %} -{%- if pf.field.kind|is_object_kind %} - Deserialize_(input->{{pf.field.name}}.ptr, &result->{{pf.field.name}}); -{%- elif pf.field.kind|is_interface_kind %} - if (input->{{pf.field.name}}.is_valid()) - result->{{pf.field.name}}.Bind(mojo::MakeScopedHandle(mojo::internal::FetchAndReset(&input->{{pf.field.name}}))); -{%- elif pf.field.kind|is_any_handle_kind %} - result->{{pf.field.name}}.reset(mojo::internal::FetchAndReset(&input->{{pf.field.name}})); -{%- elif pf.field.kind|is_enum_kind %} - result->{{pf.field.name}} = static_cast<{{pf.field.kind|cpp_wrapper_type}}>( - input->{{pf.field.name}}); -{%- else %} - result->{{pf.field.name}} = input->{{pf.field.name}}; -{%- endif %} -{%- endfor %} - *output = result.Pass(); - } else { - output->reset(); - } -} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl deleted file mode 100644 index a29df07..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl +++ /dev/null @@ -1,67 +0,0 @@ -size_t GetSerializedSize_(const {{union.name}}Ptr& input) { - if (!input) - return 0; - - size_t size = sizeof(internal::{{union.name}}_Data); - switch (input->which()) { -{% for field in union.fields %} -{% if field.kind|is_string_kind %} - case {{union.name}}::Tag::{{field.name|upper}}: - size += GetSerializedSize_(input->get_{{field.name}}()); - break; -{%- endif %} -{%- endfor %} - default: - break; - } - return size; -} - - -void Serialize_({{union.name}}Ptr input, mojo::internal::Buffer* buf, - internal::{{union.name}}_Data** output) { - if (input) { - mojo::internal::UnionAccessor<{{union.name}}> input_acc(input.get()); - internal::{{union.name}}_Data* result = - internal::{{union.name}}_Data::New(buf); - // TODO(azani): Handle unknown and objects. - result->tag = input->which(); - switch (input->which()) { -{% for field in union.fields %} - case {{union.name}}::Tag::{{field.name|upper}}: -{% if field.kind|is_string_kind %} - Serialize_(input_acc.data()->{{field.name}}, buf, &result->data.{{field.name}}.ptr); -{% else %} - result->data.{{field.name}} = input_acc.data()->{{field.name}}; -{%- endif %} - break; -{%- endfor %} - } - *output = result; - } else { - *output = nullptr; - } -} - -void Deserialize_(internal::{{union.name}}_Data* input, - {{union.name}}Ptr* output) { - if (input) { - {{union.name}}Ptr result({{union.name}}::New()); - mojo::internal::UnionAccessor<{{union.name}}> result_acc(result.get()); - switch (input->tag) { -{% for field in union.fields %} - case {{union.name}}::Tag::{{field.name|upper}}: -{% if field.kind|is_string_kind %} - result_acc.SwitchActive({{union.name}}::Tag::{{field.name|upper}}); - Deserialize_(input->data.{{field.name}}.ptr, &result_acc.data()->{{field.name}}); -{% else %} - result->set_{{field.name}}(input->data.{{field.name}}); -{%- endif %} - break; -{%- endfor %} - } - *output = result.Pass(); - } else { - output->reset(); - } -} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_declaration.tmpl deleted file mode 100644 index 25b39b3..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_declaration.tmpl +++ /dev/null @@ -1,41 +0,0 @@ - -class {{struct.name}} { - public: - typedef internal::{{struct.name}}_Data Data_; - -{#--- Constants #} -{%- for constant in struct.constants %} - static const {{constant.kind|cpp_pod_type}} {{constant.name}}; -{%- endfor %} -{#--- Enums #} -{%- for enum in struct.enums -%} -{% macro enum_def() %}{% include "enum_declaration.tmpl" %}{% endmacro %} - {{enum_def()|indent(2)}} -{%- endfor %} - static {{struct.name}}Ptr New(); - - template <typename U> - static {{struct.name}}Ptr From(const U& u) { - return mojo::TypeConverter<{{struct.name}}Ptr, U>::Convert(u); - } - - template <typename U> - U To() const { - return mojo::TypeConverter<U, {{struct.name}}>::Convert(*this); - } - - {{struct.name}}(); - ~{{struct.name}}(); - -{% if struct|is_cloneable_kind %} - {{struct.name}}Ptr Clone() const; -{%- endif %} - bool Equals(const {{struct.name}}& other) const; - -{#--- Getters #} -{% for field in struct.fields %} -{%- set type = field.kind|cpp_wrapper_type %} -{%- set name = field.name %} - {{type}} {{name}}; -{%- endfor %} -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl deleted file mode 100644 index da93e07..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl +++ /dev/null @@ -1,37 +0,0 @@ -// static -{{struct.name}}Ptr {{struct.name}}::New() { - {{struct.name}}Ptr rv; - mojo::internal::StructHelper<{{struct.name}}>::Initialize(&rv); - return rv.Pass(); -} - -{{struct.name}}::{{struct.name}}() -{%- for field in struct.fields %} - {% if loop.first %}:{% else %} {% endif %} {{field.name}}({{field|default_value}}){% if not loop.last %},{% endif %} -{%- endfor %} { -} - -{{struct.name}}::~{{struct.name}}() { -} - -{% if struct|is_cloneable_kind %} -{{struct.name}}Ptr {{struct.name}}::Clone() const { - {{struct.name}}Ptr rv(New()); -{%- for field in struct.fields %} -{%- if field.kind|is_struct_kind or field.kind|is_array_kind or field.kind|is_map_kind %} - rv->{{field.name}} = {{field.name}}.Clone(); -{%- else %} - rv->{{field.name}} = {{field.name}}; -{%- endif %} -{%- endfor %} - return rv.Pass(); -} -{% endif %} - -bool {{struct.name}}::Equals(const {{struct.name}}& other) const { -{%- for field in struct.fields %} - if (!mojo::internal::ValueTraits<{{field.kind|cpp_wrapper_type}}>::Equals({{field.name}}, other.{{field.name}})) - return false; -{%- endfor %} - return true; -} diff --git a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl deleted file mode 100644 index 91ea7cf..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl +++ /dev/null @@ -1,50 +0,0 @@ -class {{union.name}} { - public: - typedef internal::{{union.name}}_Data Data_; - typedef Data_::{{union.name}}_Tag Tag; - - static {{union.name}}Ptr New(); - - template <typename U> - static {{union.name}}Ptr From(const U& u) { - return mojo::TypeConverter<{{union.name}}Ptr, U>::Convert(u); - } - - template <typename U> - U To() const { - return mojo::TypeConverter<U, {{union.name}}>::Convert(*this); - } - - {{union.name}}(); - ~{{union.name}}(); - -{% if union|is_cloneable_kind %} - {{union.name}}Ptr Clone() const; -{%- endif %} - bool Equals(const {{union.name}}& other) const; - - Tag which() const { - return tag_; - } - -{% for field in union.fields %} - bool is_{{field.name}}() const; - {{field.kind|cpp_result_type}} get_{{field.name}}() const; - void set_{{field.name}}({{field.kind|cpp_const_wrapper_type}} {{field.name}}); -{%- endfor %} - - private: - friend class mojo::internal::UnionAccessor<{{union.name}}>; - union Union_ { - Union_() {} - ~Union_() {} -{% for field in union.fields %} - {{field.kind|cpp_wrapper_type}} {{field.name}}; -{%- endfor %} - }; - void SwitchActive(Tag new_active); - void SetActive(Tag new_active); - void DestroyActive(); - Tag tag_; - Union_ data_; -}; diff --git a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl deleted file mode 100644 index bab528c..0000000 --- a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl +++ /dev/null @@ -1,96 +0,0 @@ -// static -{{union.name}}Ptr {{union.name}}::New() { - {{union.name}}Ptr rv; - mojo::internal::StructHelper<{{union.name}}>::Initialize(&rv); - return rv.Pass(); -} - -{{union.name}}::{{union.name}}() { - // TODO(azani): Implement default values here when/if we support them. - // TODO(azani): Set to UNKNOWN when unknown is implemented. - SetActive(static_cast<Tag>(0)); -} - -{{union.name}}::~{{union.name}}() { - DestroyActive(); -} - -{% if union|is_cloneable_kind %} -{{union.name}}Ptr {{union.name}}::Clone() const { - {{union.name}}Ptr rv(New()); - switch (tag_) { -{% for field in union.fields %} - case Tag::{{field.name|upper}}: - rv->set_{{field.name}}(data_.{{field.name}}); - break; -{%- endfor %} - }; - return rv.Pass(); -} -{%- endif %} - -bool {{union.name}}::Equals(const {{union.name}}& other) const { - if (tag_ != other.which()) { - return false; - } - - switch (tag_) { -{% for field in union.fields %} - case Tag::{{field.name|upper}}: - return mojo::internal::ValueTraits<{{field.kind|cpp_wrapper_type}}>::Equals(data_.{{field.name}}, other.get_{{field.name}}()); -{%- endfor %} - }; - - return false; -} - -{% for field in union.fields %} -bool {{union.name}}::is_{{field.name}}() const { - return tag_ == Tag::{{field.name|upper}}; -} - -{{field.kind|cpp_result_type}} {{union.name}}::get_{{field.name}}() const { - MOJO_DCHECK(tag_ == Tag::{{field.name|upper}}); - return data_.{{field.name}}; -} - -void {{union.name}}::set_{{field.name}}({{field.kind|cpp_const_wrapper_type}} {{field.name}}) { - SwitchActive(Tag::{{field.name|upper}}); - data_.{{field.name}} = {{field.name}}; -} -{%- endfor %} - -void {{union.name}}::SwitchActive(Tag new_active) { - if (new_active == tag_) { - return; - } - - DestroyActive(); - SetActive(new_active); -} - -void {{union.name}}::SetActive(Tag new_active) { - switch (new_active) { -{% for field in union.fields %} - case Tag::{{field.name|upper}}: -{% if field.kind|is_string_kind %} - new (&data_.{{field.name}}) String(); -{%- endif %} - break; -{%- endfor %} - } - - tag_ = new_active; -} - -void {{union.name}}::DestroyActive() { - switch (tag_) { -{% for field in union.fields %} - case Tag::{{field.name|upper}}: -{% if field.kind|is_string_kind %} - data_.{{field.name}}.~String(); -{%- endif %} - break; -{%- endfor %} - } -} diff --git a/mojo/public/tools/bindings/generators/dart_templates/enum_definition.tmpl b/mojo/public/tools/bindings/generators/dart_templates/enum_definition.tmpl deleted file mode 100644 index 524b998..0000000 --- a/mojo/public/tools/bindings/generators/dart_templates/enum_definition.tmpl +++ /dev/null @@ -1,12 +0,0 @@ -{%- macro enum_def(prefix, enum) -%} -{%- set prev_enum = 0 %} -{%- for field in enum.fields %} -{%- if field.value %} -{{prefix}}final int {{enum.name}}_{{field.name}} = {{field.value|expression_to_text}}; -{%- elif loop.first %} -{{prefix}}final int {{enum.name}}_{{field.name}} = 0; -{%- else %} -{{prefix}}final int {{enum.name}}_{{field.name}} = {{enum.name}}_{{enum.fields[loop.index0 - 1].name}} + 1; -{%- endif %} -{%- endfor %} -{%- endmacro %} diff --git a/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl b/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl deleted file mode 100644 index d9fee1c..0000000 --- a/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl +++ /dev/null @@ -1,189 +0,0 @@ -{%- for method in interface.methods %} -const int k{{interface|name}}_{{method|name}}_name = {{method.ordinal}}; -{%- endfor %} - -abstract class {{interface|name}}Calls { - void sendMessage(bindings.Struct message, int name); - Future sendMessageWithRequestId(bindings.Struct message, int name, int id); - -{%- for method in interface.methods %} -{%- if method.response_parameters == None %} - void call{{method|name|upper_camel_case}}( -{%- for parameter in method.parameters -%} - {{parameter.kind|dart_type}} {{parameter|name}}{% if not loop.last %}, {% endif %} -{%- endfor -%} -{%- set request_struct = method|struct_from_method %} - ) { - var params = new {{request_struct|name}}(); -{%- for parameter in method.parameters %} - params.{{parameter|name}} = {{parameter|name}}; -{%- endfor %} - sendMessage(params, k{{interface|name}}_{{method|name}}_name); - } -{% else %} -{%- set response_struct = method|response_struct_from_method %} - Future<{{response_struct|name}}> call{{method|name|upper_camel_case}}( -{%- for parameter in method.parameters -%} - {{parameter.kind|dart_type}} {{parameter|name}}, -{%- endfor -%} -{%- set request_struct = method|struct_from_method %} - [int requestId = -1] - ) { - var params = new {{request_struct|name}}(); -{%- for parameter in method.parameters %} - params.{{parameter|name}} = {{parameter|name}}; -{%- endfor %} - return sendMessageWithRequestId( - params, - k{{interface|name}}_{{method|name}}_name, - requestId, - bindings.MessageHeader.kMessageExpectsResponse); - } -{%- endif %} -{%- endfor %} -} - -class {{interface|name}}Client extends bindings.Client with {{interface|name}}Calls { - {{interface|name}}Client(core.MojoMessagePipeEndpoint endpoint) : super(endpoint); - - {{interface|name}}Client.fromHandle(core.MojoHandle handle) : - super.fromHandle(handle); - - {{interface|name}}Client.unbound() : super.unbound(); - - static {{interface|name}}Client newFromEndpoint( - core.MojoMessagePipeEndpoint endpoint) => - new {{interface|name}}Client(endpoint); - - void handleResponse(bindings.ServiceMessage message) { - switch (message.header.type) { -{%- for method in interface.methods %} -{%- if method.response_parameters != None %} -{%- set response_struct = method|response_struct_from_method %} - case k{{interface|name}}_{{method|name}}_name: - var r = {{response_struct|name}}.deserialize( - message.payload); - if (!message.header.hasRequestId) { - throw 'Expected a message with a valid request Id.'; - } - Completer c = completerMap[message.header.requestId]; - completerMap[message.header.requestId] = null; - c.complete(r); - break; -{%- endif %} -{%- endfor %} - default: - throw new Exception("Unexpected message name"); - break; - } - } -} - - -class {{interface|name}}Interface extends bindings.Interface -{% if interface.client != None -%} -with {{imported_from[interface.client]}}{{interface.client|upper_camel_case}}Calls -{% endif -%} { - {{interface|name}}Interface _delegate = null; - - {{interface|name}}Interface(core.MojoMessagePipeEndpoint endpoint) : super(endpoint); - - {{interface|name}}Interface.fromHandle(core.MojoHandle handle) : - super.fromHandle(handle); - - {{interface|name}}Interface.unbound() : super.unbound(); - - static {{interface|name}}Interface newFromEndpoint( - core.MojoMessagePipeEndpoint endpoint) => - new {{interface|name}}Interface(endpoint); - - static const String name = '{{namespace|replace(".","::")}}::{{interface|name}}'; - -{% for method in interface.methods %} -{%- if method.response_parameters == None %} - void {{method|name}}( - {%- for parameter in method.parameters -%} - {{parameter.kind|dart_type}} {{parameter|name}}{% if not loop.last %}, {% endif %} - {%- endfor -%} - ) { - assert(_delegate != null); - _delegate.{{method|name}}( - {%- for parameter in method.parameters -%} - {{parameter|name}}{% if not loop.last %}, {% endif %} - {%- endfor %}); - } -{%- else %} -{%- set response_struct = method|response_struct_from_method %} - Future<{{response_struct|name}}> {{method|name}}( - {%- for parameter in method.parameters -%} - {{parameter.kind|dart_type}} {{parameter|name}}{% if not loop.last %}, {% endif %} - {%- endfor -%} - ) { - assert(_delegate != null); - return _delegate.{{method|name}}( - {%- for parameter in method.parameters -%} - {{parameter|name}}{% if not loop.last %}, {% endif %} - {%- endfor %}); - } -{%- endif %} -{%- endfor %} - - Future<bindings.Message> handleMessage(bindings.ServiceMessage message) { - switch (message.header.type) { -{%- for method in interface.methods %} -{%- set request_struct = method|struct_from_method %} - case k{{interface|name}}_{{method|name}}_name: - var params = {{request_struct|name}}.deserialize( - message.payload); -{%- if method.response_parameters == None %} - {{method|name}}( - {%- for parameter in method.parameters -%} - params.{{parameter|name}}{% if not loop.last %}, {% endif %} - {%- endfor -%} - ); -{%- else %} - return {{method|name}}( - {%- for parameter in method.parameters -%} - params.{{parameter|name}}{% if not loop.last %}, {% endif %} - {%- endfor -%} - ).then((response) { - if (response != null) { - return buildResponseWithId( - response, - k{{interface|name}}_{{method|name}}_name, - message.header.requestId, - bindings.MessageHeader.kMessageIsResponse); - } - }); -{%- endif %} - break; -{%- endfor %} - default: - throw new Exception("Unexpected message name"); - break; - } - return null; - } - - {{interface|name}}Interface get delegate => _delegate; - set delegate({{interface|name}}Interface d) { - assert(_delegate == null); - _delegate = d; - } -} - - -{#--- TODO(zra): Validation #} - - -{#--- Interface Constants #} -{% for constant in interface.constants %} -final {{constant|name}} = {{constant.value|expression_to_text}}; -{%- endfor %} - - -{#--- Interface Enums #} -{%- from "enum_definition.tmpl" import enum_def -%} -{%- for enum in interface.enums %} - {{ enum_def("", enum) }} -{%- endfor %} diff --git a/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl b/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl deleted file mode 100644 index 3512480..0000000 --- a/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -library {{module.name}}; - -import 'dart:async'; -import 'dart:mojo_bindings' as bindings; -import 'dart:mojo_core' as core; - -{%- for import in imports %} -import 'package:{{import.module.path}}.dart' as {{import.unique_name}}; -{%- endfor %} - -{%- include "module_definition.tmpl" %} diff --git a/mojo/public/tools/bindings/generators/dart_templates/module_definition.tmpl b/mojo/public/tools/bindings/generators/dart_templates/module_definition.tmpl deleted file mode 100644 index cf72c1e..0000000 --- a/mojo/public/tools/bindings/generators/dart_templates/module_definition.tmpl +++ /dev/null @@ -1,21 +0,0 @@ -{#--- Constants #} -{%- for constant in module.constants %} -final {{constant.name}} = {{constant.value|expression_to_text}}; -{%- endfor %} - -{#--- Enums #} -{%- from "enum_definition.tmpl" import enum_def %} -{%- for enum in enums %} -{{ enum_def("", enum) }} -{%- endfor %} - -{#--- Struct definitions #} -{%- from "struct_definition.tmpl" import struct_def %} -{% for struct in structs %} -{{ struct_def(struct) }} -{%- endfor -%} - -{#--- Interface definitions #} -{%- for interface in interfaces -%} -{%- include "interface_definition.tmpl" %} -{%- endfor %} diff --git a/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl b/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl deleted file mode 100644 index f5b62a9..0000000 --- a/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl +++ /dev/null @@ -1,136 +0,0 @@ -{#--- Begin #} - -{%- macro encode(variable, kind, offset, bit, level=0, check_for_null=True) %} -{%- if kind|is_pointer_array_kind %} -{%- set sub_kind = kind.kind %} -{%- if check_for_null %} -if ({{variable}} == null) { - encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|dart_true_false}}); -} else { -{%- else %} -{ -{%- endif %} - var encoder{{level + 1}} = encoder{{level}}.encodePointerArray({{variable}}.length, {{offset}}, {{kind|array_expected_length}}); - for (int i{{level}} = 0; i{{level}} < {{variable}}.length; ++i{{level}}) { - {{encode(variable~'[i'~level~']', sub_kind, 'bindings.DataHeader.kHeaderSize + bindings.kPointerSize * i'~level, 0, level+1)|indent(4)}} - } -} -{%- elif kind|is_map_kind %} -if ({{variable}} == null) { - encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|dart_true_false}}); -} else { - var encoder{{level + 1}} = encoder{{level}}.encoderForMap({{offset}}); - int size{{level}} = {{variable}}.length; - var keys{{level}} = {{variable}}.keys.toList(); - var values{{level}} = {{variable}}.values.toList(); - {{encode('keys'~level, kind.key_kind|array, 'bindings.DataHeader.kHeaderSize', 0, level+1, False)|indent(2)}} - {{encode('values'~level, kind.value_kind|array, 'bindings.DataHeader.kHeaderSize + bindings.kPointerSize', 0, level+1, False)|indent(2)}} -} -{%- else %} -encoder{{level}}.{{kind|encode_method(variable, offset, bit)}}; -{%- endif %} -{%- endmacro %} - - -{%- macro decode(variable, kind, offset, bit, level=0) %} -{%- if kind|is_struct_kind or kind|is_pointer_array_kind or kind|is_map_kind %} -var decoder{{level+1}} = decoder{{level}}.decodePointer({{offset}}, {{kind|is_nullable_kind|dart_true_false}}); -{%- if kind|is_struct_kind %} -{{variable}} = {{kind|dart_type}}.decode(decoder{{level+1}}); -{%- else %}{# kind|is_pointer_array_kind or is_map_kind #} -{%- if kind|is_nullable_kind %} -if (decoder{{level+1}} == null) { - {{variable}} = null; -} else { -{%- else %} -{ -{%- endif %} -{%- if kind|is_map_kind %} - decoder{{level+1}}.decodeDataHeaderForMap(); - List<{{kind.key_kind|dart_type}}> keys{{level}}; - List<{{kind.value_kind|dart_type}}> values{{level}}; - { - {{decode('keys'~level, kind.key_kind|array, 'DataHeader.HEADER_SIZE', 0, level+1)|indent(4)}} - } - { - {{decode('values'~level, kind.value_kind|array('keys'~level~'.length'), 'bindings.DataHeader.kHeaderSize + bindings.kPointerSize', 0, level+1)|indent(4)}} - } - {{variable}} = new Map<{{kind.key_kind|dart_type}}, {{kind.value_kind|dart_type}}>.fromIterables(keys, values); -{%- else %} - var si{{level+1}} = decoder{{level+1}}.decodeDataHeaderForPointerArray({{kind|array_expected_length}}); - {{variable}} = new {{kind|dart_type}}(si{{level+1}}.numFields); - for (int i{{level+1}} = 0; i{{level+1}} < si{{level+1}}.numFields; ++i{{level+1}}) { - {{decode(variable~'[i'~(level+1)~']', kind.kind, 'bindings.DataHeader.kHeaderSize + bindings.kPointerSize * i'~(level+1), 0, level+1)|indent(4)}} - } -{%- endif %} -} -{%- endif %} -{%- else %} -{{variable}} = decoder{{level}}.{{kind|decode_method(offset, bit)}}; -{%- endif %} -{%- endmacro %} - - -{%- macro struct_def(struct) %} -class {{struct|name}} extends bindings.Struct { - static const int kStructSize = {{struct.packed|struct_size}}; - static const bindings.DataHeader kDefaultStructInfo = - const bindings.DataHeader(kStructSize, {{struct.packed.packed_fields|length}}); - -{#--- Enums #} -{%- from "enum_definition.tmpl" import enum_def %} -{%- for enum in struct.enums %} - {{enum_def(" static ", enum)}} -{%- endfor %} - - -{#--- Constants #} -{%- for constant in struct.constants %} - static final {{constant.name}} = {{constant.value|expression_to_text}}; -{%- endfor %} - -{#--- initDefaults() #} -{%- for packed_field in struct.packed.packed_fields %} - {{packed_field.field.kind|dart_type}} {{packed_field.field|name}} = {{packed_field.field|default_value}}; -{%- endfor %} - - {{struct|name}}() : super(kStructSize); - - static {{struct|name}} deserialize(bindings.Message message) { - return decode(new bindings.Decoder(message)); - } - - static {{struct|name}} decode(bindings.Decoder decoder0) { - if (decoder0 == null) { - return null; - } - {{struct|name}} result = new {{struct|name}}(); -{%- if not struct.bytes %} - decoder0.decodeDataHeader(); -{%- else %} - var mainDataHeader = decoder0.decodeDataHeader(); -{%- endif %} -{%- for byte in struct.bytes %} -{%- for packed_field in byte.packed_fields %} - if (mainDataHeader.numFields > {{packed_field.ordinal}}) { - {{decode('result.' ~ packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(6)}} - } -{%- endfor %} -{%- endfor %} - return result; - } - - void encode(bindings.Encoder encoder) { -{%- if not struct.bytes %} - encoder.getEncoderAtOffset(kDefaultStructInfo); -{%- else %} - var encoder0 = encoder.getEncoderAtOffset(kDefaultStructInfo); -{%- endif %} -{%- for byte in struct.bytes %} -{%- for packed_field in byte.packed_fields %} - {{encode(packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(4)}} -{%- endfor %} -{%- endfor %} - } -} -{%- endmacro %} diff --git a/mojo/public/tools/bindings/generators/java_templates/constant_definition.tmpl b/mojo/public/tools/bindings/generators/java_templates/constant_definition.tmpl deleted file mode 100644 index db193e2..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/constant_definition.tmpl +++ /dev/null @@ -1,3 +0,0 @@ -{% macro constant_def(constant) %} -public static final {{constant.kind|java_type}} {{constant|name}} = {{constant|constant_value}}; -{% endmacro %} diff --git a/mojo/public/tools/bindings/generators/java_templates/constants.java.tmpl b/mojo/public/tools/bindings/generators/java_templates/constants.java.tmpl deleted file mode 100644 index 0a4e299..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/constants.java.tmpl +++ /dev/null @@ -1,12 +0,0 @@ -{% from "constant_definition.tmpl" import constant_def %} -{% include "header.java.tmpl" %} - -public final class {{main_entity}} { -{% for constant in constants %} - - {{constant_def(constant)|indent(4)}} -{% endfor %} - - private {{main_entity}}() {} - -} diff --git a/mojo/public/tools/bindings/generators/java_templates/enum.java.tmpl b/mojo/public/tools/bindings/generators/java_templates/enum.java.tmpl deleted file mode 100644 index 7096a18..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/enum.java.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -{% from "enum_definition.tmpl" import enum_def %} -{% include "header.java.tmpl" %} - -{{enum_def(enum, true)}} diff --git a/mojo/public/tools/bindings/generators/java_templates/enum_definition.tmpl b/mojo/public/tools/bindings/generators/java_templates/enum_definition.tmpl deleted file mode 100644 index a16c178..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/enum_definition.tmpl +++ /dev/null @@ -1,21 +0,0 @@ -{%- macro enum_value(enum, field, index) -%} -{%- if field.value -%} -(int) ({{field.value|expression_to_text('i32')}}) -{%- elif index == 0 -%} -0 -{%- else -%} -{{enum.fields[index - 1]|name}} + 1 -{%- endif -%} -{%- endmacro -%} - -{%- macro enum_def(enum, top_level) -%} -public {{ 'static ' if not top_level }}final class {{enum|name}} { - -{% for field in enum.fields %} - public static final int {{field|name}} = {{enum_value(enum, field, loop.index0)}}; -{% endfor %} - - private {{enum|name}}() {} - -} -{%- endmacro -%} diff --git a/mojo/public/tools/bindings/generators/java_templates/header.java.tmpl b/mojo/public/tools/bindings/generators/java_templates/header.java.tmpl deleted file mode 100644 index ec6a88b..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/header.java.tmpl +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file is autogenerated by: -// mojo/public/tools/bindings/mojom_bindings_generator.py -// For: -// {{module.path}} -// - -package {{package}}; diff --git a/mojo/public/tools/bindings/generators/java_templates/interface.java.tmpl b/mojo/public/tools/bindings/generators/java_templates/interface.java.tmpl deleted file mode 100644 index 10e5d7a..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/interface.java.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -{% from "interface_definition.tmpl" import interface_def %} -{% include "header.java.tmpl" %} - -{{ interface_def(interface, client) }} diff --git a/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl b/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl deleted file mode 100644 index 941fec7..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl +++ /dev/null @@ -1,294 +0,0 @@ -{% from "constant_definition.tmpl" import constant_def %} -{% from "enum_definition.tmpl" import enum_def %} -{% from "struct_definition.tmpl" import struct_def %} - -{%- macro declare_params(parameters, boxed=false) %} -{%- for param in parameters -%} -{{param.kind|java_type(boxed)}} {{param|name}} -{%- if not loop.last %}, {% endif %} -{%- endfor %} -{%- endmacro %} - -{% macro declare_request_params(method) %} -{{declare_params(method.parameters)}} -{%- if method.response_parameters != None -%} -{%- if method.parameters %}, {% endif %} -{{method|interface_response_name}} callback -{%- endif -%} -{% endmacro %} - -{%- macro declare_callback(method) -%} - -interface {{method|interface_response_name}} extends org.chromium.mojo.bindings.Callbacks.Callback{{method.response_parameters|length}}{% if method.response_parameters %}< -{%- for param in method.response_parameters -%} -{{param.kind|java_type(True)}} -{%- if not loop.last %}, {% endif %} -{%- endfor -%} ->{% endif %} { } -{%- endmacro -%} - -{%- macro run_callback(variable, parameters) -%} -{%- if parameters -%} -{%- for param in parameters -%} -{{variable}}.{{param|name}} -{%- if not loop.last %}, {% endif %} -{%- endfor -%} -{%- endif -%} -{%- endmacro -%} - -{%- macro super_class(client, with_generic=True) -%} -{%- if client -%} -org.chromium.mojo.bindings.InterfaceWithClient{% if with_generic %}<{{client|java_type}}>{% endif %} -{%- else -%} -org.chromium.mojo.bindings.Interface -{%- endif -%} -{%- endmacro -%} - -{%- macro flags_for_method(method, is_parameter) -%} -{{flags(method.response_parameters, is_parameter)}} -{%- endmacro -%} - -{%- macro flags(has_response_parameters, is_parameter) -%} -{%- if not has_response_parameters -%} -org.chromium.mojo.bindings.MessageHeader.NO_FLAG -{%- elif is_parameter: -%} -org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG -{%- else -%} -org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG -{%- endif -%} -{%- endmacro -%} - -{%- macro manager_class(interface, client, fully_qualified=False) -%} -{% if fully_qualified %}{{super_class(client, False)}}.{% endif %}Manager<{{interface|name}}, {{interface|name}}.Proxy -{%- if client -%}, {{client|java_type}}{%- endif -%} -> -{%- endmacro -%} - -{%- macro manager_def(interface, client) -%} -public static final {{manager_class(interface, client, True)}} MANAGER = - new {{manager_class(interface, client, True)}}() { - - public String getName() { - return "{{namespace|replace(".","::")}}::{{interface.name}}"; - } - - public Proxy buildProxy(org.chromium.mojo.system.Core core, - org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) { - return new Proxy(core, messageReceiver); - } - - public Stub buildStub(org.chromium.mojo.system.Core core, {{interface|name}} impl) { - return new Stub(core, impl); - } - - public {{interface|name}}[] buildArray(int size) { - return new {{interface|name}}[size]; - } -{% if client %} - - protected org.chromium.mojo.bindings.Interface.Manager<{{client|java_type}}, ?> getClientManager() { - return {{client|java_type}}.MANAGER; - } -{% endif %} -}; -{%- endmacro -%} - -{%- macro accept_body(interface, with_response) -%} -{% if (interface|has_method_with_response and with_response) or - (interface|has_method_without_response and not with_response) %} -try { - org.chromium.mojo.bindings.ServiceMessage messageWithHeader = - message.asServiceMessage(); - org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader(); - if (!header.validateHeader({{flags(with_response, True)}})) { - return false; - } - switch(header.getType()) { -{% for method in interface.methods %} -{% if (with_response and method.response_parameters != None) or - (not with_response and method.response_parameters == None) %} -{% set request_struct = method|struct_from_method %} -{% if with_response %} -{% set response_struct = method|response_struct_from_method %} -{% endif %} - case {{method|method_ordinal_name}}: { -{% if method.parameters %} - {{request_struct|name}} data = - {{request_struct|name}}.deserialize(messageWithHeader.getPayload()); -{% else %} - {{request_struct|name}}.deserialize(messageWithHeader.getPayload()); -{% endif %} - getImpl().{{method|name}}({{run_callback('data', method.parameters)}}{% if with_response %}{% if method.parameters %}, {% endif %}new {{response_struct|name}}ProxyToResponder(getCore(), receiver, header.getRequestId()){% endif %}); - return true; - } -{% endif %} -{% endfor %} - default: - return false; - } -} catch (org.chromium.mojo.bindings.DeserializationException e) { - return false; -} -{% else %} -return false; -{% endif %} -{%- endmacro -%} - -{% macro interface_def(interface, client) %} -public interface {{interface|name}} extends {{super_class(client)}} { -{% for constant in interface.constants %} - - {{constant_def(constant)|indent(4)}} -{% endfor %} -{% for enum in interface.enums %} - - {{enum_def(enum, false)|indent(4)}} -{% endfor %} - - public interface Proxy extends {{interface|name}}, {{super_class(client, False)}}.Proxy{% if client %}<{{client|java_type}}>{% endif %} { - } - - {{manager_class(interface, client)}} MANAGER = {{interface|name}}_Internal.MANAGER; -{% for method in interface.methods %} - - void {{method|name}}({{declare_request_params(method)}}); -{% if method.response_parameters != None %} - {{declare_callback(method)|indent(4)}} -{% endif %} -{% endfor %} -} -{% endmacro %} - -{% macro interface_internal_def(interface, client) %} -class {{interface|name}}_Internal { - - {{manager_def(interface, client)|indent(4)}} - -{% for method in interface.methods %} - private static final int {{method|method_ordinal_name}} = {{method.ordinal}}; -{% endfor %} - - static final class Proxy extends {% if client %}org.chromium.mojo.bindings.InterfaceWithClient.AbstractProxy<{{client|java_type}}>{% else %}org.chromium.mojo.bindings.Interface.AbstractProxy{% endif %} implements {{interface|name}}.Proxy { - - Proxy(org.chromium.mojo.system.Core core, - org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) { - super(core, messageReceiver); - } -{% for method in interface.methods %} - - @Override - public void {{method|name}}({{declare_request_params(method)}}) { -{% set request_struct = method|struct_from_method %} - {{request_struct|name}} _message = new {{request_struct|name}}(); -{% for param in method.parameters %} - _message.{{param|name}} = {{param|name}}; -{% endfor %} -{% if method.response_parameters != None %} - getMessageReceiver().acceptWithResponder( - _message.serializeWithHeader( - getCore(), - new org.chromium.mojo.bindings.MessageHeader( - {{method|method_ordinal_name}}, - {{flags_for_method(method, True)}}, - 0)), - new {{method|response_struct_from_method|name}}ForwardToCallback(callback)); -{% else %} - getMessageReceiver().accept( - _message.serializeWithHeader( - getCore(), - new org.chromium.mojo.bindings.MessageHeader({{method|method_ordinal_name}}))); -{% endif %} - } -{% endfor %} - - } - - static final class Stub extends org.chromium.mojo.bindings.Interface.Stub<{{interface|name}}> { - - Stub(org.chromium.mojo.system.Core core, {{interface|name}} impl) { - super(core, impl); - } - - @Override - public boolean accept(org.chromium.mojo.bindings.Message message) { - {{accept_body(interface, False)|indent(12)}} - } - - @Override - public boolean acceptWithResponder(org.chromium.mojo.bindings.Message message, org.chromium.mojo.bindings.MessageReceiver receiver) { - {{accept_body(interface, True)|indent(12)}} - } - } -{% for method in interface.methods %} - - {{ struct_def(method|struct_from_method, True)|indent(4) }} -{% if method.response_parameters != None %} -{% set response_struct = method|response_struct_from_method %} - - {{ struct_def(response_struct, True)|indent(4) }} - - static class {{response_struct|name}}ForwardToCallback extends org.chromium.mojo.bindings.SideEffectFreeCloseable - implements org.chromium.mojo.bindings.MessageReceiver { - private final {{interface|name}}.{{method|interface_response_name}} mCallback; - - {{response_struct|name}}ForwardToCallback({{interface|name}}.{{method|interface_response_name}} callback) { - this.mCallback = callback; - } - - @Override - public boolean accept(org.chromium.mojo.bindings.Message message) { - try { - org.chromium.mojo.bindings.ServiceMessage messageWithHeader = - message.asServiceMessage(); - org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader(); - if (!header.validateHeader({{method|method_ordinal_name}}, - {{flags_for_method(method, False)}})) { - return false; - } -{% if method.response_parameters|length %} - {{response_struct|name}} response = {{response_struct|name}}.deserialize(messageWithHeader.getPayload()); -{% endif %} - mCallback.call({{run_callback('response', method.response_parameters)}}); - return true; - } catch (org.chromium.mojo.bindings.DeserializationException e) { - return false; - } - } - } - - static class {{response_struct|name}}ProxyToResponder implements {{interface|name}}.{{method|interface_response_name}} { - - private final org.chromium.mojo.system.Core mCore; - private final org.chromium.mojo.bindings.MessageReceiver mMessageReceiver; - private final long mRequestId; - - {{response_struct|name}}ProxyToResponder( - org.chromium.mojo.system.Core core, - org.chromium.mojo.bindings.MessageReceiver messageReceiver, - long requestId) { - mCore = core; - mMessageReceiver = messageReceiver; - mRequestId = requestId; - } - - @Override - public void call({{declare_params(method.response_parameters, true)}}) { - {{response_struct|name}} _response = new {{response_struct|name}}(); -{% for param in method.response_parameters %} - _response.{{param|name}} = {{param|name}}; -{% endfor %} - org.chromium.mojo.bindings.ServiceMessage _message = - _response.serializeWithHeader( - mCore, - new org.chromium.mojo.bindings.MessageHeader( - {{method|method_ordinal_name}}, - {{flags_for_method(method, False)}}, - mRequestId)); - mMessageReceiver.accept(_message); - } - } -{% endif %} -{% endfor %} - -} -{% endmacro %} diff --git a/mojo/public/tools/bindings/generators/java_templates/interface_internal.java.tmpl b/mojo/public/tools/bindings/generators/java_templates/interface_internal.java.tmpl deleted file mode 100644 index efb17f3..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/interface_internal.java.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -{% from "interface_definition.tmpl" import interface_internal_def %} -{% include "header.java.tmpl" %} - -{{ interface_internal_def(interface, client) }} diff --git a/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl b/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl deleted file mode 100644 index 232ec26..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -{% from "struct_definition.tmpl" import struct_def %} -{% include "header.java.tmpl" %} - -{{ struct_def(struct) }} diff --git a/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl b/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl deleted file mode 100644 index 0abdac4..0000000 --- a/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl +++ /dev/null @@ -1,215 +0,0 @@ -{% from "constant_definition.tmpl" import constant_def %} -{% from "enum_definition.tmpl" import enum_def %} - -{%- macro inequality(kind, v1, v2) -%} -{%- if kind|is_reference_kind -%} -{%- if kind|is_array_kind -%} -{%- if kind.kind|is_reference_kind -%} -!java.util.Arrays.deepEquals({{v1}}, {{v2}}) -{%- else -%} -!java.util.Arrays.equals({{v1}}, {{v2}}) -{%- endif -%} -{%- else -%} -!org.chromium.mojo.bindings.BindingsHelper.equals({{v1}}, {{v2}}) -{%- endif -%} -{%- else -%} -{{v1}} != {{v2}} -{%- endif -%} -{%- endmacro -%} - -{%- macro hash(kind, v) -%} -{%- if kind|is_array_kind -%} -{%- if kind.kind|is_reference_kind -%} -java.util.Arrays.deepHashCode({{v}}) -{%- else -%} -java.util.Arrays.hashCode({{v}}) -{%- endif -%} -{%- else -%} -org.chromium.mojo.bindings.BindingsHelper.hashCode({{v}}) -{%- endif -%} -{%- endmacro -%} - -{% macro encode(variable, kind, offset, bit, level=0, check_for_null=True) %} -{% if kind|is_pointer_array_kind %} -{% set sub_kind = kind.kind %} -{% if check_for_null %} -if ({{variable}} == null) { - encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}}); -} else { -{% else %} -{ -{% endif %} - org.chromium.mojo.bindings.Encoder encoder{{level + 1}} = encoder{{level}}.encodePointerArray({{variable}}.length, {{offset}}, {{kind|array_expected_length}}); - for (int i{{level}} = 0; i{{level}} < {{variable}}.length; ++i{{level}}) { - {{encode(variable~'[i'~level~']', sub_kind, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i'~level, 0, level+1)|indent(8)}} - } -} -{% elif kind|is_map_kind %} -if ({{variable}} == null) { - encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}}); -} else { - org.chromium.mojo.bindings.Encoder encoder{{level + 1}} = encoder{{level}}.encoderForMap({{offset}}); - int size{{level}} = {{variable}}.size(); - {{kind.key_kind|java_type}}[] keys{{level}} = {{kind.key_kind|array|new_array('size'~level)}}; - {{kind.value_kind|java_type}}[] values{{level}} = {{kind.value_kind|array|new_array('size'~level)}}; - int index{{level}} = 0; - for (java.util.Map.Entry<{{kind.key_kind|java_type(true)}}, {{kind.value_kind|java_type(true)}}> entry{{level}} : {{variable}}.entrySet()) { - keys{{level}}[index{{level}}] = entry{{level}}.getKey(); - values{{level}}[index{{level}}] = entry{{level}}.getValue(); - ++index{{level}}; - } - {{encode('keys'~level, kind.key_kind|array, 'DataHeader.HEADER_SIZE', 0, level+1, False)|indent(4)}} - {{encode('values'~level, kind.value_kind|array, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1, False)|indent(4)}} -} -{% else %} -encoder{{level}}.{{kind|encode_method(variable, offset, bit)}}; -{% endif %} -{% endmacro %} - -{% macro decode(variable, kind, offset, bit, level=0) %} -{% if kind|is_struct_kind or kind|is_pointer_array_kind or kind|is_map_kind %} -org.chromium.mojo.bindings.Decoder decoder{{level+1}} = decoder{{level}}.readPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}}); -{% if kind|is_struct_kind %} -{{variable}} = {{kind|java_type}}.decode(decoder{{level+1}}); -{% else %}{# kind|is_pointer_array_kind or is_map_kind #} -{% if kind|is_nullable_kind %} -if (decoder{{level+1}} == null) { - {{variable}} = null; -} else { -{% else %} -{ -{% endif %} -{% if kind|is_map_kind %} - decoder{{level+1}}.readDataHeaderForMap(); - {{kind.key_kind|java_type}}[] keys{{level}}; - {{kind.value_kind|java_type}}[] values{{level}}; - { - {{decode('keys'~level, kind.key_kind|array, 'DataHeader.HEADER_SIZE', 0, level+1)|indent(8)}} - } - { - {{decode('values'~level, kind.value_kind|array('keys'~level~'.length'), 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1)|indent(8)}} - } - {{variable}} = new java.util.HashMap<{{kind.key_kind|java_type(true)}}, {{kind.value_kind|java_type(true)}}>(); - for (int index{{level}} = 0; index{{level}} < keys{{level}}.length; ++index{{level}}) { - {{variable}}.put(keys{{level}}[index{{level}}], values{{level}}[index{{level}}]); - } -{% else %} - DataHeader si{{level+1}} = decoder{{level+1}}.readDataHeaderForPointerArray({{kind|array_expected_length}}); - {{variable}} = {{kind|new_array('si'~(level+1)~'.numFields')}}; - for (int i{{level+1}} = 0; i{{level+1}} < si{{level+1}}.numFields; ++i{{level+1}}) { - {{decode(variable~'[i'~(level+1)~']', kind.kind, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i'~(level+1), 0, level+1)|indent(8)}} - } -{% endif %} -} -{% endif %} -{% else %} -{{variable}} = decoder{{level}}.{{kind|decode_method(offset, bit)}}; -{% endif %} -{% endmacro %} - -{% macro struct_def(struct, inner_class=False) %} -{{'static' if inner_class else 'public'}} final class {{struct|name}} extends org.chromium.mojo.bindings.Struct { - - private static final int STRUCT_SIZE = {{struct.packed|struct_size}}; - private static final DataHeader DEFAULT_STRUCT_INFO = new DataHeader(STRUCT_SIZE, {{struct.packed.packed_fields|length}}); -{% for constant in struct.constants %} - - {{constant_def(constant)|indent(4)}} -{% endfor %} -{% for enum in struct.enums %} - - {{enum_def(enum, false)|indent(4)}} -{% endfor %} -{% if struct.fields %} - -{% for field in struct.fields %} - public {{field.kind|java_type}} {{field|name}}; -{% endfor %} -{% endif %} - - public {{struct|name}}() { - super(STRUCT_SIZE); -{% for field in struct.fields %} -{% if field.default %} - {{field|name}} = {{field|default_value}}; -{% elif field.kind|is_handle %} - {{field|name}} = org.chromium.mojo.system.InvalidHandle.INSTANCE; -{% endif %} -{% endfor %} - } - - public static {{struct|name}} deserialize(org.chromium.mojo.bindings.Message message) { - return decode(new org.chromium.mojo.bindings.Decoder(message)); - } - - @SuppressWarnings("unchecked") - public static {{struct|name}} decode(org.chromium.mojo.bindings.Decoder decoder0) { - if (decoder0 == null) { - return null; - } - {{struct|name}} result = new {{struct|name}}(); -{% if not struct.bytes %} - decoder0.readDataHeader(); -{% else %} - DataHeader mainDataHeader = decoder0.readDataHeader(); -{% endif %} -{% for byte in struct.bytes %} -{% for packed_field in byte.packed_fields %} - if (mainDataHeader.numFields > {{packed_field.ordinal}}) { - {{decode('result.' ~ packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(12)}} - } -{% endfor %} -{% endfor %} - return result; - } - - @SuppressWarnings("unchecked") - @Override - protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { -{% if not struct.bytes %} - encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); -{% else %} - org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); -{% endif %} -{% for byte in struct.bytes %} -{% for packed_field in byte.packed_fields %} - {{encode(packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(8)}} -{% endfor %} -{% endfor %} - } - - /** - * @see Object#equals(Object) - */ - @Override - public boolean equals(Object object) { - if (object == this) - return true; - if (object == null) - return false; - if (getClass() != object.getClass()) - return false; -{% if struct.fields|length %} - {{struct|name}} other = ({{struct|name}}) object; -{% for field in struct.fields %} - if ({{inequality(field.kind, field|name, 'other.'~field|name)}}) - return false; -{% endfor %} -{% endif %} - return true; - } - - /** - * @see Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = prime + getClass().hashCode(); -{% for field in struct.fields %} - result = prime * result + {{hash(field.kind, field|name)}}; -{% endfor %} - return result; - } -} -{% endmacro %} diff --git a/mojo/public/tools/bindings/generators/js_templates/enum_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/enum_definition.tmpl deleted file mode 100644 index 4ae0a9b..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/enum_definition.tmpl +++ /dev/null @@ -1,13 +0,0 @@ -{%- macro enum_def(enum_name, enum) -%} - {{enum_name}} = {}; -{%- set prev_enum = 0 %} -{%- for field in enum.fields %} -{%- if field.value %} - {{enum_name}}.{{field.name}} = {{field.value|expression_to_text}}; -{%- elif loop.first %} - {{enum_name}}.{{field.name}} = 0; -{%- else %} - {{enum_name}}.{{field.name}} = {{enum_name}}.{{enum.fields[loop.index0 - 1].name}} + 1; -{%- endif %} -{%- endfor %} -{%- endmacro %} diff --git a/mojo/public/tools/bindings/generators/js_templates/interface_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/interface_definition.tmpl deleted file mode 100644 index 1b5cafa..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/interface_definition.tmpl +++ /dev/null @@ -1,188 +0,0 @@ -{%- for method in interface.methods %} - var k{{interface.name}}_{{method.name}}_Name = {{method.ordinal}}; -{%- endfor %} - - function {{interface.name}}Proxy(receiver) { - bindings.ProxyBase.call(this, receiver); - } - {{interface.name}}Proxy.prototype = Object.create(bindings.ProxyBase.prototype); - -{%- for method in interface.methods %} - {{interface.name}}Proxy.prototype.{{method.name|stylize_method}} = function( -{%- for parameter in method.parameters -%} -{{parameter.name}}{% if not loop.last %}, {% endif %} -{%- endfor -%} -) { - var params = new {{interface.name}}_{{method.name}}_Params(); -{%- for parameter in method.parameters %} - params.{{parameter.name}} = {{parameter|js_proxy_method_parameter_value}}; -{%- endfor %} - -{%- if method.response_parameters == None %} - var builder = new codec.MessageBuilder( - k{{interface.name}}_{{method.name}}_Name, - codec.align({{interface.name}}_{{method.name}}_Params.encodedSize)); - builder.encodeStruct({{interface.name}}_{{method.name}}_Params, params); - var message = builder.finish(); - this.receiver_.accept(message); -{%- else %} - return new Promise(function(resolve, reject) { - var builder = new codec.MessageWithRequestIDBuilder( - k{{interface.name}}_{{method.name}}_Name, - codec.align({{interface.name}}_{{method.name}}_Params.encodedSize), - codec.kMessageExpectsResponse, 0); - builder.encodeStruct({{interface.name}}_{{method.name}}_Params, params); - var message = builder.finish(); - this.receiver_.acceptAndExpectResponse(message).then(function(message) { - var reader = new codec.MessageReader(message); - var responseParams = - reader.decodeStruct({{interface.name}}_{{method.name}}_ResponseParams); - resolve(responseParams); - }).catch(function(result) { - reject(Error("Connection error: " + result)); - }); - }.bind(this)); -{%- endif %} - }; -{%- endfor %} - - function {{interface.name}}Stub(delegate) { - bindings.StubBase.call(this, delegate); - } - {{interface.name}}Stub.prototype = Object.create(bindings.StubBase.prototype); - -{%- for method in interface.methods %} -{%- set js_method_name = method.name|stylize_method %} -{%- set delegate_expr = "bindings.StubBindings(this).delegate" %} - {{interface.name}}Stub.prototype.{{js_method_name}} = function({{method.parameters|map(attribute='name')|join(', ')}}) { - return {{delegate_expr}} && {{delegate_expr}}.{{js_method_name}} && {{delegate_expr}}.{{js_method_name}}({{method.parameters|map('js_stub_method_parameter_value')|join(', ')}}); - } -{%- endfor %} - - {{interface.name}}Stub.prototype.accept = function(message) { - var reader = new codec.MessageReader(message); - switch (reader.messageName) { -{%- for method in interface.methods %} -{%- if method.response_parameters == None %} - case k{{interface.name}}_{{method.name}}_Name: - var params = reader.decodeStruct({{interface.name}}_{{method.name}}_Params); - this.{{method.name|stylize_method}}( -{%- for parameter in method.parameters -%} - params.{{parameter.name}}{% if not loop.last %}, {% endif %} -{%- endfor %}); - return true; -{%- endif %} -{%- endfor %} - default: - return false; - } - }; - - {{interface.name}}Stub.prototype.acceptWithResponder = - function(message, responder) { - var reader = new codec.MessageReader(message); - switch (reader.messageName) { -{%- for method in interface.methods %} -{%- if method.response_parameters != None %} - case k{{interface.name}}_{{method.name}}_Name: - var params = reader.decodeStruct({{interface.name}}_{{method.name}}_Params); - return this.{{method.name|stylize_method}}( -{%- for parameter in method.parameters -%} -params.{{parameter.name}}{% if not loop.last %}, {% endif -%} -{%- endfor %}).then(function(response) { - var responseParams = - new {{interface.name}}_{{method.name}}_ResponseParams(); -{%- for parameter in method.response_parameters %} - responseParams.{{parameter.name}} = response.{{parameter.name}}; -{%- endfor %} - var builder = new codec.MessageWithRequestIDBuilder( - k{{interface.name}}_{{method.name}}_Name, - codec.align({{interface.name}}_{{method.name}}_ResponseParams.encodedSize), - codec.kMessageIsResponse, reader.requestID); - builder.encodeStruct({{interface.name}}_{{method.name}}_ResponseParams, - responseParams); - var message = builder.finish(); - responder.accept(message); - }); -{%- endif %} -{%- endfor %} - default: - return Promise.reject(Error("Unhandled message: " + reader.messageName)); - } - }; - -{#--- Validation #} - - function validate{{interface.name}}Request(messageValidator) { -{%- if not(interface.methods) %} - return validator.validationError.NONE; -{%- else %} - var message = messageValidator.message; - var paramsClass = null; - switch (message.getName()) { -{%- for method in interface.methods %} - case k{{interface.name}}_{{method.name}}_Name: -{%- if method.response_parameters == None %} - if (!message.expectsResponse() && !message.isResponse()) - paramsClass = {{interface.name}}_{{method.name}}_Params; -{%- else %} - if (message.expectsResponse()) - paramsClass = {{interface.name}}_{{method.name}}_Params; -{%- endif %} - break; -{%- endfor %} - } - if (paramsClass === null) - return validator.validationError.NONE; - return paramsClass.validate(messageValidator, messageValidator.message.getHeaderNumBytes()); -{%- endif %} - } - - function validate{{interface.name}}Response(messageValidator) { -{%- if not(interface|has_callbacks) %} - return validator.validationError.NONE; -{%- else %} - var message = messageValidator.message; - var paramsClass = null; - switch (message.getName()) { -{%- for method in interface.methods %} -{%- if method.response_parameters != None %} - case k{{interface.name}}_{{method.name}}_Name: - if (message.isResponse()) - paramsClass = {{interface.name}}_{{method.name}}_ResponseParams; - break; -{%- endif %} -{%- endfor %} - } - if (paramsClass === null) - return validator.validationError.NONE; - return paramsClass.validate(messageValidator, messageValidator.message.getHeaderNumBytes()); -{%- endif %} - } - - var {{interface.name}} = { - name: '{{namespace|replace(".","::")}}::{{interface.name}}', - proxyClass: {{interface.name}}Proxy, - stubClass: {{interface.name}}Stub, - validateRequest: validate{{interface.name}}Request, -{%- if interface|has_callbacks %} - validateResponse: validate{{interface.name}}Response, -{%- else %} - validateResponse: null, -{%- endif %} - }; -{#--- Interface Constants #} -{%- for constant in interface.constants %} - {{interface.name}}.{{constant.name}} = {{constant.value|expression_to_text}}, -{%- endfor %} -{#--- Interface Enums #} -{%- from "enum_definition.tmpl" import enum_def -%} -{%- for enum in interface.enums %} - {{ enum_def("%s.%s"|format(interface.name, enum.name), enum) }} -{%- endfor %} - {{interface.name}}Stub.prototype.validator = validate{{interface.name}}Request; -{%- if interface|has_callbacks %} - {{interface.name}}Proxy.prototype.validator = validate{{interface.name}}Response; -{%- else %} - {{interface.name}}Proxy.prototype.validator = null; -{%- endif %} diff --git a/mojo/public/tools/bindings/generators/js_templates/module.amd.tmpl b/mojo/public/tools/bindings/generators/js_templates/module.amd.tmpl deleted file mode 100644 index 6d7a1a2..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/module.amd.tmpl +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -define("{{module.path}}", [ - "mojo/public/js/bindings", - "mojo/public/js/codec", - "mojo/public/js/connection", - "mojo/public/js/core", - "mojo/public/js/validator", -{%- for import in imports %} - "{{import.module.path}}", -{%- endfor %} -], function(bindings, codec, connection, core, validator -{%- for import in imports -%} - , {{import.unique_name}} -{%- endfor -%} -) { - -{%- include "module_definition.tmpl" %} - - return exports; -}); diff --git a/mojo/public/tools/bindings/generators/js_templates/module.sky.tmpl b/mojo/public/tools/bindings/generators/js_templates/module.sky.tmpl deleted file mode 100644 index 78cdf3f..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/module.sky.tmpl +++ /dev/null @@ -1,16 +0,0 @@ -<!-- Copyright 2014 The Chromium Authors. All rights reserved. - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. --> - -<import src="/mojo/public/sky/bindings.sky" as="bindings" /> -<import src="/mojo/public/sky/codec.sky" as="codec" /> -<import src="/mojo/public/sky/connection.sky" as="connection" /> -<import src="/mojo/public/sky/core.sky" as="core" /> -<import src="/mojo/public/sky/validator.sky" as="validator" /> -{%- for import in imports %} -<import src="/{{import.module.path}}.sky" as="{{import.unique_name}}" /> -{%- endfor %} -<script> -{%- include "module_definition.tmpl" %} - module.exports = exports; -</script> diff --git a/mojo/public/tools/bindings/generators/js_templates/module_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/module_definition.tmpl deleted file mode 100644 index 6448081..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/module_definition.tmpl +++ /dev/null @@ -1,40 +0,0 @@ -{#--- Constants #} -{%- for constant in module.constants %} - var {{constant.name}} = {{constant.value|expression_to_text}}; -{%- endfor %} - -{#--- Enums #} -{%- from "enum_definition.tmpl" import enum_def %} -{%- for enum in enums %} - var {{ enum_def(enum.name, enum) }} -{%- endfor %} - -{#--- Struct definitions #} -{% for struct in structs %} -{%- include "struct_definition.tmpl" %} -{%- endfor -%} - -{#--- Interface definitions #} -{%- for interface in interfaces -%} -{%- include "interface_definition.tmpl" %} -{%- endfor %} - - var exports = {}; -{%- for constant in module.constants %} - exports.{{constant.name}} = {{constant.name}}; -{%- endfor %} -{%- for enum in enums %} - exports.{{enum.name}} = {{enum.name}}; -{%- endfor %} -{%- for struct in structs if struct.exported %} - exports.{{struct.name}} = {{struct.name}}; -{%- endfor %} -{%- for interface in interfaces %} - exports.{{interface.name}} = {{interface.name}}; -{#--- Interface Client #} -{%- if interface.client in interfaces|map(attribute='name') %} - exports.{{interface.name}}.client = {{interface.client}}; -{%- elif interface.client in imported_interfaces %} - exports.{{interface.name}}.client = {{imported_interfaces[interface.client]}}; -{%- endif %} -{%- endfor %} diff --git a/mojo/public/tools/bindings/generators/js_templates/struct_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/struct_definition.tmpl deleted file mode 100644 index 62b497c..0000000 --- a/mojo/public/tools/bindings/generators/js_templates/struct_definition.tmpl +++ /dev/null @@ -1,120 +0,0 @@ -{#--- Begin #} - function {{struct.name}}(values) { - this.initDefaults_(); - this.initFields_(values); - } - -{#--- Enums #} -{%- from "enum_definition.tmpl" import enum_def %} -{% for enum in struct.enums %} - {{enum_def("%s.%s"|format(struct.name, enum.name), enum)}} -{%- endfor %} - -{#--- Constants #} -{% for constant in struct.constants %} - {{struct.name}}.{{constant.name}} = {{constant.value|expression_to_text}}; -{%- endfor %} - -{#--- initDefaults() #} - {{struct.name}}.prototype.initDefaults_ = function() { -{%- for packed_field in struct.packed.packed_fields %} - this.{{packed_field.field.name}} = {{packed_field.field|default_value}}; -{%- endfor %} - }; - -{#--- initFields() #} - {{struct.name}}.prototype.initFields_ = function(fields) { - for(var field in fields) { - if (this.hasOwnProperty(field)) - this[field] = fields[field]; - } - }; - -{#--- Validation #} - - {{struct.name}}.validate = function(messageValidator, offset) { - var err; -{% macro check_err() -%} - if (err !== validator.validationError.NONE) - return err; -{%- endmacro %} - err = messageValidator.validateStructHeader(offset, {{struct.name}}.encodedSize, {{struct.packed.packed_fields|length}}); - {{check_err()}} - -{%- for packed_field in struct.packed.packed_fields %} -{%- set field_name = packed_field.field.name %} -{%- if packed_field.field|is_string_pointer_field %} - // validate {{struct.name}}.{{field_name}} - err = messageValidator.validateStringPointer({{packed_field|validate_string_params}}) - {{check_err()}} -{%- elif packed_field.field|is_array_pointer_field %} - // validate {{struct.name}}.{{field_name}} - err = messageValidator.validateArrayPointer({{packed_field|validate_array_params}}); - {{check_err()}} -{%- elif packed_field.field|is_struct_pointer_field %} - // validate {{struct.name}}.{{field_name}} - err = messageValidator.validateStructPointer({{packed_field|validate_struct_params}}); - {{check_err()}} -{%- elif packed_field.field|is_map_pointer_field %} - // validate {{struct.name}}.{{field_name}} - err = messageValidator.validateMapPointer({{packed_field|validate_map_params}}); - {{check_err()}} -{%- elif packed_field.field|is_handle_field %} - // validate {{struct.name}}.{{field_name}} - err = messageValidator.validateHandle({{packed_field|validate_handle_params}}) - {{check_err()}} -{%- endif %} -{%- endfor %} - - return validator.validationError.NONE; - }; - -{#--- Encoding and decoding #} - - {{struct.name}}.encodedSize = codec.kStructHeaderSize + {{struct.packed|payload_size}}; - - {{struct.name}}.decode = function(decoder) { - var packed; - var val = new {{struct.name}}(); - var numberOfBytes = decoder.readUint32(); - var numberOfFields = decoder.readUint32(); -{%- for byte in struct.bytes %} -{%- if byte.packed_fields|length > 1 %} - packed = decoder.readUint8(); -{%- for packed_field in byte.packed_fields %} - val.{{packed_field.field.name}} = (packed >> {{packed_field.bit}}) & 1 ? true : false; -{%- endfor %} -{%- else %} -{%- for packed_field in byte.packed_fields %} - val.{{packed_field.field.name}} = decoder.{{packed_field.field.kind|decode_snippet}}; -{%- endfor %} -{%- endif %} -{%- if byte.is_padding %} - decoder.skip(1); -{%- endif %} -{%- endfor %} - return val; - }; - - {{struct.name}}.encode = function(encoder, val) { - var packed; - encoder.writeUint32({{struct.name}}.encodedSize); - encoder.writeUint32({{struct.packed.packed_fields|length}}); - -{%- for byte in struct.bytes %} -{%- if byte.packed_fields|length > 1 %} - packed = 0; -{%- for packed_field in byte.packed_fields %} - packed |= (val.{{packed_field.field.name}} & 1) << {{packed_field.bit}} -{%- endfor %} - encoder.writeUint8(packed); -{%- else %} -{%- for packed_field in byte.packed_fields %} - encoder.{{packed_field.field.kind|encode_snippet}}val.{{packed_field.field.name}}); -{%- endfor %} -{%- endif %} -{%- if byte.is_padding %} - encoder.skip(1); -{%- endif %} -{%- endfor %} - }; diff --git a/mojo/public/tools/bindings/generators/mojom_cpp_generator.py b/mojo/public/tools/bindings/generators/mojom_cpp_generator.py deleted file mode 100644 index 34bba30..0000000 --- a/mojo/public/tools/bindings/generators/mojom_cpp_generator.py +++ /dev/null @@ -1,387 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Generates C++ source files from a mojom.Module.""" - -import mojom.generate.generator as generator -import mojom.generate.module as mojom -import mojom.generate.pack as pack -from mojom.generate.template_expander import UseJinja - - -_kind_to_cpp_type = { - mojom.BOOL: "bool", - mojom.INT8: "int8_t", - mojom.UINT8: "uint8_t", - mojom.INT16: "int16_t", - mojom.UINT16: "uint16_t", - mojom.INT32: "int32_t", - mojom.UINT32: "uint32_t", - mojom.FLOAT: "float", - mojom.HANDLE: "mojo::Handle", - mojom.DCPIPE: "mojo::DataPipeConsumerHandle", - mojom.DPPIPE: "mojo::DataPipeProducerHandle", - mojom.MSGPIPE: "mojo::MessagePipeHandle", - mojom.SHAREDBUFFER: "mojo::SharedBufferHandle", - mojom.NULLABLE_HANDLE: "mojo::Handle", - mojom.NULLABLE_DCPIPE: "mojo::DataPipeConsumerHandle", - mojom.NULLABLE_DPPIPE: "mojo::DataPipeProducerHandle", - mojom.NULLABLE_MSGPIPE: "mojo::MessagePipeHandle", - mojom.NULLABLE_SHAREDBUFFER: "mojo::SharedBufferHandle", - mojom.INT64: "int64_t", - mojom.UINT64: "uint64_t", - mojom.DOUBLE: "double", -} - -_kind_to_cpp_literal_suffix = { - mojom.UINT8: "U", - mojom.UINT16: "U", - mojom.UINT32: "U", - mojom.FLOAT: "f", - mojom.UINT64: "ULL", -} - -def ConstantValue(constant): - return ExpressionToText(constant.value, kind=constant.kind) - -def DefaultValue(field): - if field.default: - if mojom.IsStructKind(field.kind): - assert field.default == "default" - return "%s::New()" % GetNameForKind(field.kind) - return ExpressionToText(field.default, kind=field.kind) - return "" - -def NamespaceToArray(namespace): - return namespace.split('.') if namespace else [] - -def GetNameForKind(kind, internal = False): - parts = [] - if kind.imported_from: - parts.extend(NamespaceToArray(kind.imported_from["namespace"])) - if internal: - parts.append("internal") - if kind.parent_kind: - parts.append(kind.parent_kind.name) - parts.append(kind.name) - return "::".join(parts) - -def GetCppType(kind): - if mojom.IsArrayKind(kind): - return "mojo::internal::Array_Data<%s>*" % GetCppType(kind.kind) - if mojom.IsMapKind(kind): - return "mojo::internal::Map_Data<%s, %s>*" % ( - GetCppType(kind.key_kind), GetCppType(kind.value_kind)) - if mojom.IsStructKind(kind): - return "%s_Data*" % GetNameForKind(kind, internal=True) - if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind): - return "mojo::MessagePipeHandle" - if mojom.IsEnumKind(kind): - return "int32_t" - if mojom.IsStringKind(kind): - return "mojo::internal::String_Data*" - return _kind_to_cpp_type[kind] - -def GetCppPodType(kind): - if mojom.IsStringKind(kind): - return "char*" - return _kind_to_cpp_type[kind] - -def GetCppArrayArgWrapperType(kind): - if mojom.IsEnumKind(kind): - return GetNameForKind(kind) - if mojom.IsStructKind(kind): - return "%sPtr" % GetNameForKind(kind) - if mojom.IsArrayKind(kind): - return "mojo::Array<%s> " % GetCppArrayArgWrapperType(kind.kind) - if mojom.IsMapKind(kind): - return "mojo::Map<%s, %s> " % (GetCppArrayArgWrapperType(kind.key_kind), - GetCppArrayArgWrapperType(kind.value_kind)) - if mojom.IsInterfaceKind(kind): - raise Exception("Arrays of interfaces not yet supported!") - if mojom.IsInterfaceRequestKind(kind): - raise Exception("Arrays of interface requests not yet supported!") - if mojom.IsStringKind(kind): - return "mojo::String" - if mojom.IsHandleKind(kind): - return "mojo::ScopedHandle" - if mojom.IsDataPipeConsumerKind(kind): - return "mojo::ScopedDataPipeConsumerHandle" - if mojom.IsDataPipeProducerKind(kind): - return "mojo::ScopedDataPipeProducerHandle" - if mojom.IsMessagePipeKind(kind): - return "mojo::ScopedMessagePipeHandle" - if mojom.IsSharedBufferKind(kind): - return "mojo::ScopedSharedBufferHandle" - return _kind_to_cpp_type[kind] - -def GetCppResultWrapperType(kind): - if mojom.IsEnumKind(kind): - return GetNameForKind(kind) - if mojom.IsStructKind(kind): - return "%sPtr" % GetNameForKind(kind) - if mojom.IsArrayKind(kind): - return "mojo::Array<%s>" % GetCppArrayArgWrapperType(kind.kind) - if mojom.IsMapKind(kind): - return "mojo::Map<%s, %s>" % (GetCppArrayArgWrapperType(kind.key_kind), - GetCppArrayArgWrapperType(kind.value_kind)) - if mojom.IsInterfaceKind(kind): - return "%sPtr" % GetNameForKind(kind) - if mojom.IsInterfaceRequestKind(kind): - return "mojo::InterfaceRequest<%s>" % GetNameForKind(kind.kind) - if mojom.IsStringKind(kind): - return "mojo::String" - if mojom.IsHandleKind(kind): - return "mojo::ScopedHandle" - if mojom.IsDataPipeConsumerKind(kind): - return "mojo::ScopedDataPipeConsumerHandle" - if mojom.IsDataPipeProducerKind(kind): - return "mojo::ScopedDataPipeProducerHandle" - if mojom.IsMessagePipeKind(kind): - return "mojo::ScopedMessagePipeHandle" - if mojom.IsSharedBufferKind(kind): - return "mojo::ScopedSharedBufferHandle" - return _kind_to_cpp_type[kind] - -def GetCppWrapperType(kind): - if mojom.IsEnumKind(kind): - return GetNameForKind(kind) - if mojom.IsStructKind(kind): - return "%sPtr" % GetNameForKind(kind) - if mojom.IsArrayKind(kind): - return "mojo::Array<%s>" % GetCppArrayArgWrapperType(kind.kind) - if mojom.IsMapKind(kind): - return "mojo::Map<%s, %s>" % (GetCppArrayArgWrapperType(kind.key_kind), - GetCppArrayArgWrapperType(kind.value_kind)) - if mojom.IsInterfaceKind(kind): - return "%sPtr" % GetNameForKind(kind) - if mojom.IsInterfaceRequestKind(kind): - raise Exception("InterfaceRequest fields not supported!") - if mojom.IsStringKind(kind): - return "mojo::String" - if mojom.IsHandleKind(kind): - return "mojo::ScopedHandle" - if mojom.IsDataPipeConsumerKind(kind): - return "mojo::ScopedDataPipeConsumerHandle" - if mojom.IsDataPipeProducerKind(kind): - return "mojo::ScopedDataPipeProducerHandle" - if mojom.IsMessagePipeKind(kind): - return "mojo::ScopedMessagePipeHandle" - if mojom.IsSharedBufferKind(kind): - return "mojo::ScopedSharedBufferHandle" - return _kind_to_cpp_type[kind] - -def GetCppConstWrapperType(kind): - if mojom.IsStructKind(kind): - return "%sPtr" % GetNameForKind(kind) - if mojom.IsArrayKind(kind): - return "mojo::Array<%s>" % GetCppArrayArgWrapperType(kind.kind) - if mojom.IsMapKind(kind): - return "mojo::Map<%s, %s>" % (GetCppArrayArgWrapperType(kind.key_kind), - GetCppArrayArgWrapperType(kind.value_kind)) - if mojom.IsInterfaceKind(kind): - return "%sPtr" % GetNameForKind(kind) - if mojom.IsInterfaceRequestKind(kind): - return "mojo::InterfaceRequest<%s>" % GetNameForKind(kind.kind) - if mojom.IsEnumKind(kind): - return GetNameForKind(kind) - if mojom.IsStringKind(kind): - return "const mojo::String&" - if mojom.IsHandleKind(kind): - return "mojo::ScopedHandle" - if mojom.IsDataPipeConsumerKind(kind): - return "mojo::ScopedDataPipeConsumerHandle" - if mojom.IsDataPipeProducerKind(kind): - return "mojo::ScopedDataPipeProducerHandle" - if mojom.IsMessagePipeKind(kind): - return "mojo::ScopedMessagePipeHandle" - if mojom.IsSharedBufferKind(kind): - return "mojo::ScopedSharedBufferHandle" - if not kind in _kind_to_cpp_type: - print "missing:", kind.spec - return _kind_to_cpp_type[kind] - -def GetCppFieldType(kind): - if mojom.IsStructKind(kind): - return ("mojo::internal::StructPointer<%s_Data>" % - GetNameForKind(kind, internal=True)) - if mojom.IsArrayKind(kind): - return "mojo::internal::ArrayPointer<%s>" % GetCppType(kind.kind) - if mojom.IsMapKind(kind): - return ("mojo::internal::StructPointer<mojo::internal::Map_Data<%s, %s>>" % - (GetCppType(kind.key_kind), GetCppType(kind.value_kind))) - if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind): - return "mojo::MessagePipeHandle" - if mojom.IsEnumKind(kind): - return GetNameForKind(kind) - if mojom.IsStringKind(kind): - return "mojo::internal::StringPointer" - return _kind_to_cpp_type[kind] - -def IsStructWithHandles(struct): - for pf in struct.packed.packed_fields: - if mojom.IsAnyHandleKind(pf.field.kind): - return True - return False - -def TranslateConstants(token, kind): - if isinstance(token, mojom.NamedValue): - # Both variable and enum constants are constructed like: - # Namespace::Struct::CONSTANT_NAME - # For enums, CONSTANT_NAME is ENUM_NAME_ENUM_VALUE. - name = [] - if token.imported_from: - name.extend(NamespaceToArray(token.namespace)) - if token.parent_kind: - name.append(token.parent_kind.name) - if isinstance(token, mojom.EnumValue): - name.append( - "%s_%s" % (generator.CamelCaseToAllCaps(token.enum.name), token.name)) - else: - name.append(token.name) - return "::".join(name) - - if isinstance(token, mojom.BuiltinValue): - if token.value == "double.INFINITY" or token.value == "float.INFINITY": - return "INFINITY"; - if token.value == "double.NEGATIVE_INFINITY" or \ - token.value == "float.NEGATIVE_INFINITY": - return "-INFINITY"; - if token.value == "double.NAN" or token.value == "float.NAN": - return "NAN"; - - if (kind is not None and mojom.IsFloatKind(kind)): - return token if token.isdigit() else token + "f"; - - # Per C++11, 2.14.2, the type of an integer literal is the first of the - # corresponding list in Table 6 in which its value can be represented. In this - # case, the list for decimal constants with no suffix is: - # int, long int, long long int - # The standard considers a program ill-formed if it contains an integer - # literal that cannot be represented by any of the allowed types. - # - # As it turns out, MSVC doesn't bother trying to fall back to long long int, - # so the integral constant -2147483648 causes it grief: it decides to - # represent 2147483648 as an unsigned integer, and then warns that the unary - # minus operator doesn't make sense on unsigned types. Doh! - if kind == mojom.INT32 and token == '-2147483648': - return '(-%d - 1) /* %s */' % ( - 2**31 - 1, 'Workaround for MSVC bug; see https://crbug.com/445618') - - return '%s%s' % (token, _kind_to_cpp_literal_suffix.get(kind, '')) - -def ExpressionToText(value, kind=None): - return TranslateConstants(value, kind) - -def ShouldInlineStruct(struct): - # TODO(darin): Base this on the size of the wrapper class. - if len(struct.fields) > 4: - return False - for field in struct.fields: - if mojom.IsMoveOnlyKind(field.kind): - return False - return True - -def GetArrayValidateParams(kind): - if (not mojom.IsArrayKind(kind) and not mojom.IsMapKind(kind) and - not mojom.IsStringKind(kind)): - return "mojo::internal::NoValidateParams" - - if mojom.IsStringKind(kind): - expected_num_elements = 0 - element_is_nullable = False - element_validate_params = "mojo::internal::NoValidateParams" - elif mojom.IsMapKind(kind): - expected_num_elements = 0 - element_is_nullable = mojom.IsNullableKind(kind.value_kind) - element_validate_params = GetArrayValidateParams(kind.value_kind) - else: - expected_num_elements = generator.ExpectedArraySize(kind) or 0 - element_is_nullable = mojom.IsNullableKind(kind.kind) - element_validate_params = GetArrayValidateParams(kind.kind) - - return "mojo::internal::ArrayValidateParams<%d, %s,\n%s> " % ( - expected_num_elements, - 'true' if element_is_nullable else 'false', - element_validate_params) - -def GetMapValidateParams(value_kind): - # Unlike GetArrayValidateParams, we are given the wrapped kind, instead of - # the raw array kind. So we wrap the return value of GetArrayValidateParams. - element_is_nullable = mojom.IsNullableKind(value_kind) - return "mojo::internal::ArrayValidateParams<0, %s,\n%s> " % ( - 'true' if element_is_nullable else 'false', - GetArrayValidateParams(value_kind)) - -_HEADER_SIZE = 8 - -class Generator(generator.Generator): - - cpp_filters = { - "constant_value": ConstantValue, - "cpp_const_wrapper_type": GetCppConstWrapperType, - "cpp_field_type": GetCppFieldType, - "cpp_pod_type": GetCppPodType, - "cpp_result_type": GetCppResultWrapperType, - "cpp_type": GetCppType, - "cpp_wrapper_type": GetCppWrapperType, - "default_value": DefaultValue, - "expression_to_text": ExpressionToText, - "get_array_validate_params": GetArrayValidateParams, - "get_map_validate_params": GetMapValidateParams, - "get_name_for_kind": GetNameForKind, - "get_pad": pack.GetPad, - "has_callbacks": mojom.HasCallbacks, - "should_inline": ShouldInlineStruct, - "is_array_kind": mojom.IsArrayKind, - "is_cloneable_kind": mojom.IsCloneableKind, - "is_enum_kind": mojom.IsEnumKind, - "is_move_only_kind": mojom.IsMoveOnlyKind, - "is_any_handle_kind": mojom.IsAnyHandleKind, - "is_interface_kind": mojom.IsInterfaceKind, - "is_interface_request_kind": mojom.IsInterfaceRequestKind, - "is_map_kind": mojom.IsMapKind, - "is_nullable_kind": mojom.IsNullableKind, - "is_object_kind": mojom.IsObjectKind, - "is_string_kind": mojom.IsStringKind, - "is_struct_kind": mojom.IsStructKind, - "is_struct_with_handles": IsStructWithHandles, - "struct_size": lambda ps: ps.GetTotalSize() + _HEADER_SIZE, - "struct_from_method": generator.GetStructFromMethod, - "response_struct_from_method": generator.GetResponseStructFromMethod, - "stylize_method": generator.StudlyCapsToCamel, - "to_all_caps": generator.CamelCaseToAllCaps, - } - - def GetJinjaExports(self): - return { - "module": self.module, - "namespace": self.module.namespace, - "namespaces_as_array": NamespaceToArray(self.module.namespace), - "imports": self.module.imports, - "kinds": self.module.kinds, - "enums": self.module.enums, - "structs": self.GetStructs(), - "interfaces": self.module.interfaces, - } - - @UseJinja("cpp_templates/module.h.tmpl", filters=cpp_filters) - def GenerateModuleHeader(self): - return self.GetJinjaExports() - - @UseJinja("cpp_templates/module-internal.h.tmpl", filters=cpp_filters) - def GenerateModuleInternalHeader(self): - return self.GetJinjaExports() - - @UseJinja("cpp_templates/module.cc.tmpl", filters=cpp_filters) - def GenerateModuleSource(self): - return self.GetJinjaExports() - - def GenerateFiles(self, args): - self.Write(self.GenerateModuleHeader(), - self.MatchMojomFilePath("%s.h" % self.module.name)) - self.Write(self.GenerateModuleInternalHeader(), - self.MatchMojomFilePath("%s-internal.h" % self.module.name)) - self.Write(self.GenerateModuleSource(), - self.MatchMojomFilePath("%s.cc" % self.module.name)) diff --git a/mojo/public/tools/bindings/generators/mojom_dart_generator.py b/mojo/public/tools/bindings/generators/mojom_dart_generator.py deleted file mode 100644 index 893e665..0000000 --- a/mojo/public/tools/bindings/generators/mojom_dart_generator.py +++ /dev/null @@ -1,441 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Generates dart source files from a mojom.Module.""" - -import re - -import mojom.generate.generator as generator -import mojom.generate.module as mojom -import mojom.generate.pack as pack -from mojom.generate.template_expander import UseJinja - -GENERATOR_PREFIX = 'dart' - -_HEADER_SIZE = 8 - -_kind_to_dart_default_value = { - mojom.BOOL: "false", - mojom.INT8: "0", - mojom.UINT8: "0", - mojom.INT16: "0", - mojom.UINT16: "0", - mojom.INT32: "0", - mojom.UINT32: "0", - mojom.FLOAT: "0.0", - mojom.HANDLE: "null", - mojom.DCPIPE: "null", - mojom.DPPIPE: "null", - mojom.MSGPIPE: "null", - mojom.SHAREDBUFFER: "null", - mojom.NULLABLE_HANDLE: "null", - mojom.NULLABLE_DCPIPE: "null", - mojom.NULLABLE_DPPIPE: "null", - mojom.NULLABLE_MSGPIPE: "null", - mojom.NULLABLE_SHAREDBUFFER: "null", - mojom.INT64: "0", - mojom.UINT64: "0", - mojom.DOUBLE: "0.0", - mojom.STRING: "null", - mojom.NULLABLE_STRING: "null" -} - -_kind_to_dart_decl_type = { - mojom.BOOL: "bool", - mojom.INT8: "int", - mojom.UINT8: "int", - mojom.INT16: "int", - mojom.UINT16: "int", - mojom.INT32: "int", - mojom.UINT32: "int", - mojom.FLOAT: "double", - mojom.HANDLE: "core.MojoHandle", - mojom.DCPIPE: "core.MojoDataPipeConsumer", - mojom.DPPIPE: "core.MojoDataPipeProducer", - mojom.MSGPIPE: "core.MojoMessagePipeEndpoint", - mojom.SHAREDBUFFER: "core.MojoSharedBuffer", - mojom.NULLABLE_HANDLE: "core.MojoHandle", - mojom.NULLABLE_DCPIPE: "core.MojoDataPipeConsumer", - mojom.NULLABLE_DPPIPE: "core.MojoDataPipeProducer", - mojom.NULLABLE_MSGPIPE: "core.MojoMessagePipeEndpoint", - mojom.NULLABLE_SHAREDBUFFER: "core.MojoSharedBuffer", - mojom.INT64: "int", - mojom.UINT64: "int", - mojom.DOUBLE: "double", - mojom.STRING: "String", - mojom.NULLABLE_STRING: "String" -} - -_spec_to_decode_method = { - mojom.BOOL.spec: 'decodeBool', - mojom.DCPIPE.spec: 'decodeHandle', - mojom.DOUBLE.spec: 'decodeDouble', - mojom.DPPIPE.spec: 'decodeHandle', - mojom.FLOAT.spec: 'decodeFloat', - mojom.HANDLE.spec: 'decodeHandle', - mojom.INT16.spec: 'decodeInt16', - mojom.INT32.spec: 'decodeInt32', - mojom.INT64.spec: 'decodeInt64', - mojom.INT8.spec: 'decodeInt8', - mojom.MSGPIPE.spec: 'decodeMessagePipeHandle', - mojom.NULLABLE_DCPIPE.spec: 'decodeConsumerHandle', - mojom.NULLABLE_DPPIPE.spec: 'decodeProducerHandle', - mojom.NULLABLE_HANDLE.spec: 'decodeHandle', - mojom.NULLABLE_MSGPIPE.spec: 'decodeMessagePipeHandle', - mojom.NULLABLE_SHAREDBUFFER.spec: 'decodeSharedBufferHandle', - mojom.NULLABLE_STRING.spec: 'decodeString', - mojom.SHAREDBUFFER.spec: 'decodeSharedBufferHandle', - mojom.STRING.spec: 'decodeString', - mojom.UINT16.spec: 'decodeUint16', - mojom.UINT32.spec: 'decodeUint32', - mojom.UINT64.spec: 'decodeUint64', - mojom.UINT8.spec: 'decodeUint8', -} - -_spec_to_encode_method = { - mojom.BOOL.spec: 'encodeBool', - mojom.DCPIPE.spec: 'encodeHandle', - mojom.DOUBLE.spec: 'encodeDouble', - mojom.DPPIPE.spec: 'encodeHandle', - mojom.FLOAT.spec: 'encodeFloat', - mojom.HANDLE.spec: 'encodeHandle', - mojom.INT16.spec: 'encodeInt16', - mojom.INT32.spec: 'encodeInt32', - mojom.INT64.spec: 'encodeInt64', - mojom.INT8.spec: 'encodeInt8', - mojom.MSGPIPE.spec: 'encodeMessagePipeHandle', - mojom.NULLABLE_DCPIPE.spec: 'encodeConsumerHandle', - mojom.NULLABLE_DPPIPE.spec: 'encodeProducerHandle', - mojom.NULLABLE_HANDLE.spec: 'encodeHandle', - mojom.NULLABLE_MSGPIPE.spec: 'encodeMessagePipeHandle', - mojom.NULLABLE_SHAREDBUFFER.spec: 'encodeSharedBufferHandle', - mojom.NULLABLE_STRING.spec: 'encodeString', - mojom.SHAREDBUFFER.spec: 'encodeSharedBufferHandle', - mojom.STRING.spec: 'encodeString', - mojom.UINT16.spec: 'encodeUint16', - mojom.UINT32.spec: 'encodeUint32', - mojom.UINT64.spec: 'encodeUint64', - mojom.UINT8.spec: 'encodeUint8', -} - -def GetDartType(kind): - if kind.imported_from: - return kind.imported_from["unique_name"] + "." + kind.name - return kind.name - -def DartDefaultValue(field): - if field.default: - if mojom.IsStructKind(field.kind): - assert field.default == "default" - return "new %s()" % GetDartType(field.kind) - return ExpressionToText(field.default) - if field.kind in mojom.PRIMITIVES: - return _kind_to_dart_default_value[field.kind] - if mojom.IsStructKind(field.kind): - return "null" - if mojom.IsArrayKind(field.kind): - return "null" - if mojom.IsMapKind(field.kind): - return "null" - if mojom.IsInterfaceKind(field.kind) or \ - mojom.IsInterfaceRequestKind(field.kind): - return "null" - if mojom.IsEnumKind(field.kind): - return "0" - -def DartDeclType(kind): - if kind in mojom.PRIMITIVES: - return _kind_to_dart_decl_type[kind] - if mojom.IsStructKind(kind): - return GetDartType(kind) - if mojom.IsArrayKind(kind): - array_type = DartDeclType(kind.kind) - return "List<" + array_type + ">" - if mojom.IsMapKind(kind): - key_type = DartDeclType(kind.key_kind) - value_type = DartDeclType(kind.value_kind) - return "Map<"+ key_type + ", " + value_type + ">" - if mojom.IsInterfaceKind(kind) or \ - mojom.IsInterfaceRequestKind(kind): - return "Object" - if mojom.IsEnumKind(kind): - return "int" - -def NameToComponent(name): - # insert '_' between anything and a Title name (e.g, HTTPEntry2FooBar -> - # HTTP_Entry2_FooBar) - name = re.sub('([^_])([A-Z][^A-Z_]+)', r'\1_\2', name) - # insert '_' between non upper and start of upper blocks (e.g., - # HTTP_Entry2_FooBar -> HTTP_Entry2_Foo_Bar) - name = re.sub('([^A-Z_])([A-Z])', r'\1_\2', name) - return [x.lower() for x in name.split('_')] - -def UpperCamelCase(name): - return ''.join([x.capitalize() for x in NameToComponent(name)]) - -def CamelCase(name): - uccc = UpperCamelCase(name) - return uccc[0].lower() + uccc[1:] - -def ConstantStyle(name): - components = NameToComponent(name) - if components[0] == 'k' and len(components) > 1: - components = components[1:] - # variable cannot starts with a digit. - if components[0][0].isdigit(): - components[0] = '_' + components[0] - return '_'.join([x.upper() for x in components]) - -def GetNameForElement(element): - if (mojom.IsEnumKind(element) or mojom.IsInterfaceKind(element) or - mojom.IsStructKind(element)): - return UpperCamelCase(element.name) - if mojom.IsInterfaceRequestKind(element): - return GetNameForElement(element.kind) - if isinstance(element, (mojom.Method, - mojom.Parameter, - mojom.Field)): - return CamelCase(element.name) - if isinstance(element, mojom.EnumValue): - return (GetNameForElement(element.enum) + '.' + - ConstantStyle(element.name)) - if isinstance(element, (mojom.NamedValue, - mojom.Constant, - mojom.EnumField)): - return ConstantStyle(element.name) - raise Exception('Unexpected element: %s' % element) - -def GetInterfaceResponseName(method): - return UpperCamelCase(method.name + 'Response') - -def GetResponseStructFromMethod(method): - return generator.GetDataHeader( - False, generator.GetResponseStructFromMethod(method)) - -def GetStructFromMethod(method): - return generator.GetDataHeader( - False, generator.GetStructFromMethod(method)) - -def GetDartTrueFalse(value): - return 'true' if value else 'false' - -def GetArrayNullabilityFlags(kind): - """Returns nullability flags for an array type, see codec.dart. - - As we have dedicated decoding functions for arrays, we have to pass - nullability information about both the array itself, as well as the array - element type there. - """ - assert mojom.IsArrayKind(kind) - ARRAY_NULLABLE = 'bindings.kArrayNullable' - ELEMENT_NULLABLE = 'bindings.kElementNullable' - NOTHING_NULLABLE = 'bindings.kNothingNullable' - - flags_to_set = [] - if mojom.IsNullableKind(kind): - flags_to_set.append(ARRAY_NULLABLE) - if mojom.IsNullableKind(kind.kind): - flags_to_set.append(ELEMENT_NULLABLE) - - if not flags_to_set: - flags_to_set = [NOTHING_NULLABLE] - return ' | '.join(flags_to_set) - -def AppendDecodeParams(initial_params, kind, bit): - """ Appends standard parameters for decode calls. """ - params = list(initial_params) - if (kind == mojom.BOOL): - params.append(str(bit)) - if mojom.IsReferenceKind(kind): - if mojom.IsArrayKind(kind): - params.append(GetArrayNullabilityFlags(kind)) - else: - params.append(GetDartTrueFalse(mojom.IsNullableKind(kind))) - if mojom.IsInterfaceKind(kind): - params.append('%sClient.newFromEndpoint' % GetDartType(kind)) - if mojom.IsArrayKind(kind) and mojom.IsInterfaceKind(kind.kind): - params.append('%sClient.newFromEndpoint' % GetDartType(kind.kind)) - if mojom.IsInterfaceRequestKind(kind): - params.append('%sInterface.newFromEndpoint' % GetDartType(kind.kind)) - if mojom.IsArrayKind(kind) and mojom.IsInterfaceRequestKind(kind.kind): - params.append('%sInterface.newFromEndpoint' % GetDartType(kind.kind.kind)) - if mojom.IsArrayKind(kind): - params.append(GetArrayExpectedLength(kind)) - return params - -def AppendEncodeParams(initial_params, kind, bit): - """ Appends standard parameters shared between encode and decode calls. """ - params = list(initial_params) - if (kind == mojom.BOOL): - params.append(str(bit)) - if mojom.IsReferenceKind(kind): - if mojom.IsArrayKind(kind): - params.append(GetArrayNullabilityFlags(kind)) - else: - params.append(GetDartTrueFalse(mojom.IsNullableKind(kind))) - if mojom.IsArrayKind(kind): - params.append(GetArrayExpectedLength(kind)) - return params - -def DecodeMethod(kind, offset, bit): - def _DecodeMethodName(kind): - if mojom.IsArrayKind(kind): - return _DecodeMethodName(kind.kind) + 'Array' - if mojom.IsEnumKind(kind): - return _DecodeMethodName(mojom.INT32) - if mojom.IsInterfaceRequestKind(kind): - return 'decodeInterfaceRequest' - if mojom.IsInterfaceKind(kind): - return 'decodeServiceInterface' - return _spec_to_decode_method[kind.spec] - methodName = _DecodeMethodName(kind) - params = AppendDecodeParams([ str(offset) ], kind, bit) - return '%s(%s)' % (methodName, ', '.join(params)) - -def EncodeMethod(kind, variable, offset, bit): - def _EncodeMethodName(kind): - if mojom.IsStructKind(kind): - return 'encodeStruct' - if mojom.IsArrayKind(kind): - return _EncodeMethodName(kind.kind) + 'Array' - if mojom.IsEnumKind(kind): - return _EncodeMethodName(mojom.INT32) - if mojom.IsInterfaceRequestKind(kind): - return 'encodeInterfaceRequest' - if mojom.IsInterfaceKind(kind): - return 'encodeInterface' - return _spec_to_encode_method[kind.spec] - methodName = _EncodeMethodName(kind) - params = AppendEncodeParams([ variable, str(offset) ], kind, bit) - return '%s(%s)' % (methodName, ', '.join(params)) - -def TranslateConstants(token): - if isinstance(token, (mojom.EnumValue, mojom.NamedValue)): - # Both variable and enum constants are constructed like: - # NamespaceUid.Struct.Enum_CONSTANT_NAME - name = "" - if token.imported_from: - name = token.imported_from["unique_name"] + "." - if token.parent_kind: - name = name + token.parent_kind.name + "." - if isinstance(token, mojom.EnumValue): - name = name + token.enum.name + "_" - return name + token.name - - if isinstance(token, mojom.BuiltinValue): - if token.value == "double.INFINITY" or token.value == "float.INFINITY": - return "double.INFINITY"; - if token.value == "double.NEGATIVE_INFINITY" or \ - token.value == "float.NEGATIVE_INFINITY": - return "double.NEGATIVE_INFINITY"; - if token.value == "double.NAN" or token.value == "float.NAN": - return "double.NAN"; - - # Strip leading '+'. - if token[0] == '+': - token = token[1:] - - return token - -def ExpressionToText(value): - return TranslateConstants(value) - -def GetArrayKind(kind, size = None): - if size is None: - return mojom.Array(kind) - else: - array = mojom.Array(kind, 0) - array.dart_map_size = size - return array - -def GetArrayExpectedLength(kind): - if mojom.IsArrayKind(kind) and kind.length is not None: - return getattr(kind, 'dart_map_size', str(kind.length)) - else: - return 'bindings.kUnspecifiedArrayLength' - -def IsPointerArrayKind(kind): - if not mojom.IsArrayKind(kind): - return False - sub_kind = kind.kind - return mojom.IsObjectKind(sub_kind) - -class Generator(generator.Generator): - - dart_filters = { - 'array_expected_length': GetArrayExpectedLength, - 'array': GetArrayKind, - 'decode_method': DecodeMethod, - 'default_value': DartDefaultValue, - 'encode_method': EncodeMethod, - 'expression_to_text': ExpressionToText, - 'is_handle': mojom.IsNonInterfaceHandleKind, - 'is_map_kind': mojom.IsMapKind, - 'is_nullable_kind': mojom.IsNullableKind, - 'is_pointer_array_kind': IsPointerArrayKind, - 'is_struct_kind': mojom.IsStructKind, - 'dart_true_false': GetDartTrueFalse, - 'dart_type': DartDeclType, - 'name': GetNameForElement, - 'interface_response_name': GetInterfaceResponseName, - 'response_struct_from_method': GetResponseStructFromMethod, - 'struct_from_method': GetStructFromMethod, - 'upper_camel_case': UpperCamelCase, - 'struct_size': lambda ps: ps.GetTotalSize() + _HEADER_SIZE, - } - - def GetParameters(self): - return { - "namespace": self.module.namespace, - "imports": self.GetImports(), - "kinds": self.module.kinds, - "enums": self.module.enums, - "module": self.module, - "structs": self.GetStructs() + self.GetStructsFromMethods(), - "interfaces": self.module.interfaces, - "imported_interfaces": self.GetImportedInterfaces(), - "imported_from": self.ImportedFrom(), - } - - @UseJinja("dart_templates/module.lib.tmpl", filters=dart_filters) - def GenerateLibModule(self): - return self.GetParameters() - - def GenerateFiles(self, args): - self.Write(self.GenerateLibModule(), - self.MatchMojomFilePath("%s.dart" % self.module.name)) - - def GetImports(self): - used_names = set() - for each_import in self.module.imports: - simple_name = each_import["module_name"].split(".")[0] - - # Since each import is assigned a library in Dart, they need to have - # unique names. - unique_name = simple_name - counter = 0 - while unique_name in used_names: - counter += 1 - unique_name = simple_name + str(counter) - - used_names.add(unique_name) - each_import["unique_name"] = unique_name - counter += 1 - return self.module.imports - - def GetImportedInterfaces(self): - interface_to_import = {} - for each_import in self.module.imports: - for each_interface in each_import["module"].interfaces: - name = each_interface.name - interface_to_import[name] = each_import["unique_name"] + "." + name - return interface_to_import - - def ImportedFrom(self): - interface_to_import = {} - for each_import in self.module.imports: - for each_interface in each_import["module"].interfaces: - name = each_interface.name - interface_to_import[name] = each_import["unique_name"] + "." - return interface_to_import diff --git a/mojo/public/tools/bindings/generators/mojom_java_generator.py b/mojo/public/tools/bindings/generators/mojom_java_generator.py deleted file mode 100644 index 276d5af..0000000 --- a/mojo/public/tools/bindings/generators/mojom_java_generator.py +++ /dev/null @@ -1,531 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Generates java source files from a mojom.Module.""" - -import argparse -import ast -import contextlib -import os -import re -import shutil -import tempfile -import zipfile - -from jinja2 import contextfilter - -import mojom.generate.generator as generator -import mojom.generate.module as mojom -from mojom.generate.template_expander import UseJinja - - -GENERATOR_PREFIX = 'java' - -_HEADER_SIZE = 8 - -_spec_to_java_type = { - mojom.BOOL.spec: 'boolean', - mojom.DCPIPE.spec: 'org.chromium.mojo.system.DataPipe.ConsumerHandle', - mojom.DOUBLE.spec: 'double', - mojom.DPPIPE.spec: 'org.chromium.mojo.system.DataPipe.ProducerHandle', - mojom.FLOAT.spec: 'float', - mojom.HANDLE.spec: 'org.chromium.mojo.system.UntypedHandle', - mojom.INT16.spec: 'short', - mojom.INT32.spec: 'int', - mojom.INT64.spec: 'long', - mojom.INT8.spec: 'byte', - mojom.MSGPIPE.spec: 'org.chromium.mojo.system.MessagePipeHandle', - mojom.NULLABLE_DCPIPE.spec: - 'org.chromium.mojo.system.DataPipe.ConsumerHandle', - mojom.NULLABLE_DPPIPE.spec: - 'org.chromium.mojo.system.DataPipe.ProducerHandle', - mojom.NULLABLE_HANDLE.spec: 'org.chromium.mojo.system.UntypedHandle', - mojom.NULLABLE_MSGPIPE.spec: 'org.chromium.mojo.system.MessagePipeHandle', - mojom.NULLABLE_SHAREDBUFFER.spec: - 'org.chromium.mojo.system.SharedBufferHandle', - mojom.NULLABLE_STRING.spec: 'String', - mojom.SHAREDBUFFER.spec: 'org.chromium.mojo.system.SharedBufferHandle', - mojom.STRING.spec: 'String', - mojom.UINT16.spec: 'short', - mojom.UINT32.spec: 'int', - mojom.UINT64.spec: 'long', - mojom.UINT8.spec: 'byte', -} - -_spec_to_decode_method = { - mojom.BOOL.spec: 'readBoolean', - mojom.DCPIPE.spec: 'readConsumerHandle', - mojom.DOUBLE.spec: 'readDouble', - mojom.DPPIPE.spec: 'readProducerHandle', - mojom.FLOAT.spec: 'readFloat', - mojom.HANDLE.spec: 'readUntypedHandle', - mojom.INT16.spec: 'readShort', - mojom.INT32.spec: 'readInt', - mojom.INT64.spec: 'readLong', - mojom.INT8.spec: 'readByte', - mojom.MSGPIPE.spec: 'readMessagePipeHandle', - mojom.NULLABLE_DCPIPE.spec: 'readConsumerHandle', - mojom.NULLABLE_DPPIPE.spec: 'readProducerHandle', - mojom.NULLABLE_HANDLE.spec: 'readUntypedHandle', - mojom.NULLABLE_MSGPIPE.spec: 'readMessagePipeHandle', - mojom.NULLABLE_SHAREDBUFFER.spec: 'readSharedBufferHandle', - mojom.NULLABLE_STRING.spec: 'readString', - mojom.SHAREDBUFFER.spec: 'readSharedBufferHandle', - mojom.STRING.spec: 'readString', - mojom.UINT16.spec: 'readShort', - mojom.UINT32.spec: 'readInt', - mojom.UINT64.spec: 'readLong', - mojom.UINT8.spec: 'readByte', -} - -_java_primitive_to_boxed_type = { - 'boolean': 'Boolean', - 'byte': 'Byte', - 'double': 'Double', - 'float': 'Float', - 'int': 'Integer', - 'long': 'Long', - 'short': 'Short', -} - - -def NameToComponent(name): - # insert '_' between anything and a Title name (e.g, HTTPEntry2FooBar -> - # HTTP_Entry2_FooBar) - name = re.sub('([^_])([A-Z][^A-Z_]+)', r'\1_\2', name) - # insert '_' between non upper and start of upper blocks (e.g., - # HTTP_Entry2_FooBar -> HTTP_Entry2_Foo_Bar) - name = re.sub('([^A-Z_])([A-Z])', r'\1_\2', name) - return [x.lower() for x in name.split('_')] - -def UpperCamelCase(name): - return ''.join([x.capitalize() for x in NameToComponent(name)]) - -def CamelCase(name): - uccc = UpperCamelCase(name) - return uccc[0].lower() + uccc[1:] - -def ConstantStyle(name): - components = NameToComponent(name) - if components[0] == 'k' and len(components) > 1: - components = components[1:] - # variable cannot starts with a digit. - if components[0][0].isdigit(): - components[0] = '_' + components[0] - return '_'.join([x.upper() for x in components]) - -def GetNameForElement(element): - if (mojom.IsEnumKind(element) or mojom.IsInterfaceKind(element) or - mojom.IsStructKind(element)): - return UpperCamelCase(element.name) - if mojom.IsInterfaceRequestKind(element): - return GetNameForElement(element.kind) - if isinstance(element, (mojom.Method, - mojom.Parameter, - mojom.Field)): - return CamelCase(element.name) - if isinstance(element, mojom.EnumValue): - return (GetNameForElement(element.enum) + '.' + - ConstantStyle(element.name)) - if isinstance(element, (mojom.NamedValue, - mojom.Constant, - mojom.EnumField)): - return ConstantStyle(element.name) - raise Exception('Unexpected element: %s' % element) - -def GetInterfaceResponseName(method): - return UpperCamelCase(method.name + 'Response') - -def ParseStringAttribute(attribute): - assert isinstance(attribute, basestring) - return attribute - -def GetJavaTrueFalse(value): - return 'true' if value else 'false' - -def GetArrayNullabilityFlags(kind): - """Returns nullability flags for an array type, see Decoder.java. - - As we have dedicated decoding functions for arrays, we have to pass - nullability information about both the array itself, as well as the array - element type there. - """ - assert mojom.IsArrayKind(kind) - ARRAY_NULLABLE = \ - 'org.chromium.mojo.bindings.BindingsHelper.ARRAY_NULLABLE' - ELEMENT_NULLABLE = \ - 'org.chromium.mojo.bindings.BindingsHelper.ELEMENT_NULLABLE' - NOTHING_NULLABLE = \ - 'org.chromium.mojo.bindings.BindingsHelper.NOTHING_NULLABLE' - - flags_to_set = [] - if mojom.IsNullableKind(kind): - flags_to_set.append(ARRAY_NULLABLE) - if mojom.IsNullableKind(kind.kind): - flags_to_set.append(ELEMENT_NULLABLE) - - if not flags_to_set: - flags_to_set = [NOTHING_NULLABLE] - return ' | '.join(flags_to_set) - - -def AppendEncodeDecodeParams(initial_params, context, kind, bit): - """ Appends standard parameters shared between encode and decode calls. """ - params = list(initial_params) - if (kind == mojom.BOOL): - params.append(str(bit)) - if mojom.IsReferenceKind(kind): - if mojom.IsArrayKind(kind): - params.append(GetArrayNullabilityFlags(kind)) - else: - params.append(GetJavaTrueFalse(mojom.IsNullableKind(kind))) - if mojom.IsArrayKind(kind): - params.append(GetArrayExpectedLength(kind)) - if mojom.IsInterfaceKind(kind): - params.append('%s.MANAGER' % GetJavaType(context, kind)) - if mojom.IsArrayKind(kind) and mojom.IsInterfaceKind(kind.kind): - params.append('%s.MANAGER' % GetJavaType(context, kind.kind)) - return params - - -@contextfilter -def DecodeMethod(context, kind, offset, bit): - def _DecodeMethodName(kind): - if mojom.IsArrayKind(kind): - return _DecodeMethodName(kind.kind) + 's' - if mojom.IsEnumKind(kind): - return _DecodeMethodName(mojom.INT32) - if mojom.IsInterfaceRequestKind(kind): - return 'readInterfaceRequest' - if mojom.IsInterfaceKind(kind): - return 'readServiceInterface' - return _spec_to_decode_method[kind.spec] - methodName = _DecodeMethodName(kind) - params = AppendEncodeDecodeParams([ str(offset) ], context, kind, bit) - return '%s(%s)' % (methodName, ', '.join(params)) - -@contextfilter -def EncodeMethod(context, kind, variable, offset, bit): - params = AppendEncodeDecodeParams( - [ variable, str(offset) ], context, kind, bit) - return 'encode(%s)' % ', '.join(params) - -def GetPackage(module): - if 'JavaPackage' in module.attributes: - return ParseStringAttribute(module.attributes['JavaPackage']) - # Default package. - if module.namespace: - return 'org.chromium.mojom.' + module.namespace - return 'org.chromium.mojom' - -def GetNameForKind(context, kind): - def _GetNameHierachy(kind): - hierachy = [] - if kind.parent_kind: - hierachy = _GetNameHierachy(kind.parent_kind) - hierachy.append(GetNameForElement(kind)) - return hierachy - - module = context.resolve('module') - elements = [] - if GetPackage(module) != GetPackage(kind.module): - elements += [GetPackage(kind.module)] - elements += _GetNameHierachy(kind) - return '.'.join(elements) - -def GetBoxedJavaType(context, kind, with_generics=True): - unboxed_type = GetJavaType(context, kind, False, with_generics) - if unboxed_type in _java_primitive_to_boxed_type: - return _java_primitive_to_boxed_type[unboxed_type] - return unboxed_type - -@contextfilter -def GetJavaType(context, kind, boxed=False, with_generics=True): - if boxed: - return GetBoxedJavaType(context, kind) - if mojom.IsStructKind(kind) or mojom.IsInterfaceKind(kind): - return GetNameForKind(context, kind) - if mojom.IsInterfaceRequestKind(kind): - return ('org.chromium.mojo.bindings.InterfaceRequest<%s>' % - GetNameForKind(context, kind.kind)) - if mojom.IsMapKind(kind): - if with_generics: - return 'java.util.Map<%s, %s>' % ( - GetBoxedJavaType(context, kind.key_kind), - GetBoxedJavaType(context, kind.value_kind)) - else: - return 'java.util.Map' - if mojom.IsArrayKind(kind): - return '%s[]' % GetJavaType(context, kind.kind, boxed, with_generics) - if mojom.IsEnumKind(kind): - return 'int' - return _spec_to_java_type[kind.spec] - -@contextfilter -def DefaultValue(context, field): - assert field.default - if isinstance(field.kind, mojom.Struct): - assert field.default == 'default' - return 'new %s()' % GetJavaType(context, field.kind) - return '(%s) %s' % ( - GetJavaType(context, field.kind), - ExpressionToText(context, field.default, kind_spec=field.kind.spec)) - -@contextfilter -def ConstantValue(context, constant): - return '(%s) %s' % ( - GetJavaType(context, constant.kind), - ExpressionToText(context, constant.value, kind_spec=constant.kind.spec)) - -@contextfilter -def NewArray(context, kind, size): - if mojom.IsArrayKind(kind.kind): - return NewArray(context, kind.kind, size) + '[]' - return 'new %s[%s]' % ( - GetJavaType(context, kind.kind, boxed=False, with_generics=False), size) - -@contextfilter -def ExpressionToText(context, token, kind_spec=''): - def _TranslateNamedValue(named_value): - entity_name = GetNameForElement(named_value) - if named_value.parent_kind: - return GetJavaType(context, named_value.parent_kind) + '.' + entity_name - # Handle the case where named_value is a module level constant: - if not isinstance(named_value, mojom.EnumValue): - entity_name = (GetConstantsMainEntityName(named_value.module) + '.' + - entity_name) - if GetPackage(named_value.module) == GetPackage(context.resolve('module')): - return entity_name - return GetPackage(named_value.module) + '.' + entity_name - - if isinstance(token, mojom.NamedValue): - return _TranslateNamedValue(token) - if kind_spec.startswith('i') or kind_spec.startswith('u'): - # Add Long suffix to all integer literals. - number = ast.literal_eval(token.lstrip('+ ')) - if not isinstance(number, (int, long)): - raise ValueError('got unexpected type %r for int literal %r' % ( - type(number), token)) - # If the literal is too large to fit a signed long, convert it to the - # equivalent signed long. - if number >= 2 ** 63: - number -= 2 ** 64 - return '%dL' % number - if isinstance(token, mojom.BuiltinValue): - if token.value == 'double.INFINITY': - return 'java.lang.Double.POSITIVE_INFINITY' - if token.value == 'double.NEGATIVE_INFINITY': - return 'java.lang.Double.NEGATIVE_INFINITY' - if token.value == 'double.NAN': - return 'java.lang.Double.NaN' - if token.value == 'float.INFINITY': - return 'java.lang.Float.POSITIVE_INFINITY' - if token.value == 'float.NEGATIVE_INFINITY': - return 'java.lang.Float.NEGATIVE_INFINITY' - if token.value == 'float.NAN': - return 'java.lang.Float.NaN' - return token - -def GetArrayKind(kind, size = None): - if size is None: - return mojom.Array(kind) - else: - array = mojom.Array(kind, 0) - array.java_map_size = size - return array - -def GetArrayExpectedLength(kind): - if mojom.IsArrayKind(kind) and kind.length is not None: - return getattr(kind, 'java_map_size', str(kind.length)) - else: - return 'org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH' - -def IsPointerArrayKind(kind): - if not mojom.IsArrayKind(kind): - return False - sub_kind = kind.kind - return mojom.IsObjectKind(sub_kind) - -def GetResponseStructFromMethod(method): - return generator.GetDataHeader( - False, generator.GetResponseStructFromMethod(method)) - -def GetStructFromMethod(method): - return generator.GetDataHeader( - False, generator.GetStructFromMethod(method)) - -def GetConstantsMainEntityName(module): - if 'JavaConstantsClassName' in module.attributes: - return ParseStringAttribute(module.attributes['JavaConstantsClassName']) - # This constructs the name of the embedding classes for module level constants - # by extracting the mojom's filename and prepending it to Constants. - return (UpperCamelCase(module.path.split('/')[-1].rsplit('.', 1)[0]) + - 'Constants') - -def GetMethodOrdinalName(method): - return ConstantStyle(method.name) + '_ORDINAL' - -def HasMethodWithResponse(interface): - for method in interface.methods: - if method.response_parameters is not None: - return True - return False - -def HasMethodWithoutResponse(interface): - for method in interface.methods: - if method.response_parameters is None: - return True - return False - -@contextlib.contextmanager -def TempDir(): - dirname = tempfile.mkdtemp() - try: - yield dirname - finally: - shutil.rmtree(dirname) - -def ZipContentInto(root, zip_filename): - with zipfile.ZipFile(zip_filename, 'w') as zip_file: - for dirname, _, files in os.walk(root): - for filename in files: - path = os.path.join(dirname, filename) - path_in_archive = os.path.relpath(path, root) - zip_file.write(path, path_in_archive) - -class Generator(generator.Generator): - - java_filters = { - 'array_expected_length': GetArrayExpectedLength, - 'array': GetArrayKind, - 'constant_value': ConstantValue, - 'decode_method': DecodeMethod, - 'default_value': DefaultValue, - 'encode_method': EncodeMethod, - 'expression_to_text': ExpressionToText, - 'has_method_without_response': HasMethodWithoutResponse, - 'has_method_with_response': HasMethodWithResponse, - 'interface_response_name': GetInterfaceResponseName, - 'is_array_kind': mojom.IsArrayKind, - 'is_handle': mojom.IsNonInterfaceHandleKind, - 'is_map_kind': mojom.IsMapKind, - 'is_nullable_kind': mojom.IsNullableKind, - 'is_pointer_array_kind': IsPointerArrayKind, - 'is_reference_kind': mojom.IsReferenceKind, - 'is_struct_kind': mojom.IsStructKind, - 'java_true_false': GetJavaTrueFalse, - 'java_type': GetJavaType, - 'method_ordinal_name': GetMethodOrdinalName, - 'name': GetNameForElement, - 'new_array': NewArray, - 'response_struct_from_method': GetResponseStructFromMethod, - 'struct_from_method': GetStructFromMethod, - 'struct_size': lambda ps: ps.GetTotalSize() + _HEADER_SIZE, - } - - def GetJinjaExports(self): - return { - 'package': GetPackage(self.module), - } - - def GetJinjaExportsForInterface(self, interface): - exports = self.GetJinjaExports() - exports.update({'interface': interface}) - if interface.client: - all_interfaces = [] + self.module.interfaces - for each in self.module.imports: - all_interfaces += each['module'].interfaces - interfaces_by_name = dict((x.name, x) for x in all_interfaces) - assert interface.client in interfaces_by_name, ( - 'Unable to find interface %s declared as client of %s.' % - (interface.client, interface.name)) - exports.update({'client': interfaces_by_name[interface.client]}) - return exports - - @UseJinja('java_templates/enum.java.tmpl', filters=java_filters) - def GenerateEnumSource(self, enum): - exports = self.GetJinjaExports() - exports.update({'enum': enum}) - return exports - - @UseJinja('java_templates/struct.java.tmpl', filters=java_filters) - def GenerateStructSource(self, struct): - exports = self.GetJinjaExports() - exports.update({'struct': struct}) - return exports - - @UseJinja('java_templates/interface.java.tmpl', filters=java_filters) - def GenerateInterfaceSource(self, interface): - return self.GetJinjaExportsForInterface(interface) - - @UseJinja('java_templates/interface_internal.java.tmpl', filters=java_filters) - def GenerateInterfaceInternalSource(self, interface): - return self.GetJinjaExportsForInterface(interface) - - @UseJinja('java_templates/constants.java.tmpl', filters=java_filters) - def GenerateConstantsSource(self, module): - exports = self.GetJinjaExports() - exports.update({'main_entity': GetConstantsMainEntityName(module), - 'constants': module.constants}) - return exports - - def DoGenerateFiles(self): - if not os.path.exists(self.output_dir): - try: - os.makedirs(self.output_dir) - except: - # Ignore errors on directory creation. - pass - - # Keep this above the others as .GetStructs() changes the state of the - # module, annotating structs with required information. - for struct in self.GetStructs(): - self.Write(self.GenerateStructSource(struct), - '%s.java' % GetNameForElement(struct)) - - for enum in self.module.enums: - self.Write(self.GenerateEnumSource(enum), - '%s.java' % GetNameForElement(enum)) - - for interface in self.module.interfaces: - self.Write(self.GenerateInterfaceSource(interface), - '%s.java' % GetNameForElement(interface)) - self.Write(self.GenerateInterfaceInternalSource(interface), - '%s_Internal.java' % GetNameForElement(interface)) - - if self.module.constants: - self.Write(self.GenerateConstantsSource(self.module), - '%s.java' % GetConstantsMainEntityName(self.module)) - - def GenerateFiles(self, unparsed_args): - parser = argparse.ArgumentParser() - parser.add_argument('--java_output_directory', dest='java_output_directory') - args = parser.parse_args(unparsed_args) - package_path = GetPackage(self.module).replace('.', '/') - - # Generate the java files in a temporary directory and place a single - # srcjar in the output directory. - basename = self.MatchMojomFilePath("%s.srcjar" % self.module.name) - zip_filename = os.path.join(self.output_dir, basename) - with TempDir() as temp_java_root: - self.output_dir = os.path.join(temp_java_root, package_path) - self.DoGenerateFiles(); - ZipContentInto(temp_java_root, zip_filename) - - if args.java_output_directory: - # If requested, generate the java files directly into indicated directory. - self.output_dir = os.path.join(args.java_output_directory, package_path) - self.DoGenerateFiles(); - - def GetJinjaParameters(self): - return { - 'lstrip_blocks': True, - 'trim_blocks': True, - } - - def GetGlobals(self): - return { - 'namespace': self.module.namespace, - 'module': self.module, - } diff --git a/mojo/public/tools/bindings/generators/mojom_js_generator.py b/mojo/public/tools/bindings/generators/mojom_js_generator.py deleted file mode 100644 index 7aaeaa2..0000000 --- a/mojo/public/tools/bindings/generators/mojom_js_generator.py +++ /dev/null @@ -1,380 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Generates JavaScript source files from a mojom.Module.""" - -import mojom.generate.generator as generator -import mojom.generate.module as mojom -import mojom.generate.pack as pack -from mojom.generate.template_expander import UseJinja - -_kind_to_javascript_default_value = { - mojom.BOOL: "false", - mojom.INT8: "0", - mojom.UINT8: "0", - mojom.INT16: "0", - mojom.UINT16: "0", - mojom.INT32: "0", - mojom.UINT32: "0", - mojom.FLOAT: "0", - mojom.HANDLE: "null", - mojom.DCPIPE: "null", - mojom.DPPIPE: "null", - mojom.MSGPIPE: "null", - mojom.SHAREDBUFFER: "null", - mojom.NULLABLE_HANDLE: "null", - mojom.NULLABLE_DCPIPE: "null", - mojom.NULLABLE_DPPIPE: "null", - mojom.NULLABLE_MSGPIPE: "null", - mojom.NULLABLE_SHAREDBUFFER: "null", - mojom.INT64: "0", - mojom.UINT64: "0", - mojom.DOUBLE: "0", - mojom.STRING: "null", - mojom.NULLABLE_STRING: "null" -} - - -def JavaScriptType(kind): - if kind.imported_from: - return kind.imported_from["unique_name"] + "." + kind.name - return kind.name - - -def JavaScriptDefaultValue(field): - if field.default: - if mojom.IsStructKind(field.kind): - assert field.default == "default" - return "new %s()" % JavaScriptType(field.kind) - return ExpressionToText(field.default) - if field.kind in mojom.PRIMITIVES: - return _kind_to_javascript_default_value[field.kind] - if mojom.IsStructKind(field.kind): - return "null" - if mojom.IsArrayKind(field.kind): - return "null" - if mojom.IsMapKind(field.kind): - return "null" - if mojom.IsInterfaceKind(field.kind) or \ - mojom.IsInterfaceRequestKind(field.kind): - return _kind_to_javascript_default_value[mojom.MSGPIPE] - if mojom.IsEnumKind(field.kind): - return "0" - - -def JavaScriptPayloadSize(packed): - packed_fields = packed.packed_fields - if not packed_fields: - return 0 - last_field = packed_fields[-1] - offset = last_field.offset + last_field.size - pad = pack.GetPad(offset, 8) - return offset + pad - - -_kind_to_codec_type = { - mojom.BOOL: "codec.Uint8", - mojom.INT8: "codec.Int8", - mojom.UINT8: "codec.Uint8", - mojom.INT16: "codec.Int16", - mojom.UINT16: "codec.Uint16", - mojom.INT32: "codec.Int32", - mojom.UINT32: "codec.Uint32", - mojom.FLOAT: "codec.Float", - mojom.HANDLE: "codec.Handle", - mojom.DCPIPE: "codec.Handle", - mojom.DPPIPE: "codec.Handle", - mojom.MSGPIPE: "codec.Handle", - mojom.SHAREDBUFFER: "codec.Handle", - mojom.NULLABLE_HANDLE: "codec.NullableHandle", - mojom.NULLABLE_DCPIPE: "codec.NullableHandle", - mojom.NULLABLE_DPPIPE: "codec.NullableHandle", - mojom.NULLABLE_MSGPIPE: "codec.NullableHandle", - mojom.NULLABLE_SHAREDBUFFER: "codec.NullableHandle", - mojom.INT64: "codec.Int64", - mojom.UINT64: "codec.Uint64", - mojom.DOUBLE: "codec.Double", - mojom.STRING: "codec.String", - mojom.NULLABLE_STRING: "codec.NullableString", -} - - -def CodecType(kind): - if kind in mojom.PRIMITIVES: - return _kind_to_codec_type[kind] - if mojom.IsStructKind(kind): - pointer_type = "NullablePointerTo" if mojom.IsNullableKind(kind) \ - else "PointerTo" - return "new codec.%s(%s)" % (pointer_type, JavaScriptType(kind)) - if mojom.IsArrayKind(kind): - array_type = "NullableArrayOf" if mojom.IsNullableKind(kind) else "ArrayOf" - array_length = "" if kind.length is None else ", %d" % kind.length - element_type = ElementCodecType(kind.kind) - return "new codec.%s(%s%s)" % (array_type, element_type, array_length) - if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind): - return CodecType(mojom.MSGPIPE) - if mojom.IsEnumKind(kind): - return _kind_to_codec_type[mojom.INT32] - if mojom.IsMapKind(kind): - map_type = "NullableMapOf" if mojom.IsNullableKind(kind) else "MapOf" - key_type = ElementCodecType(kind.key_kind) - value_type = ElementCodecType(kind.value_kind) - return "new codec.%s(%s, %s)" % (map_type, key_type, value_type) - return kind - -def ElementCodecType(kind): - return "codec.PackedBool" if mojom.IsBoolKind(kind) else CodecType(kind) - -def JavaScriptDecodeSnippet(kind): - if kind in mojom.PRIMITIVES: - return "decodeStruct(%s)" % CodecType(kind) - if mojom.IsStructKind(kind): - return "decodeStructPointer(%s)" % JavaScriptType(kind) - if mojom.IsMapKind(kind): - return "decodeMapPointer(%s, %s)" % \ - (ElementCodecType(kind.key_kind), ElementCodecType(kind.value_kind)) - if mojom.IsArrayKind(kind) and mojom.IsBoolKind(kind.kind): - return "decodeArrayPointer(codec.PackedBool)" - if mojom.IsArrayKind(kind): - return "decodeArrayPointer(%s)" % CodecType(kind.kind) - if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind): - return JavaScriptDecodeSnippet(mojom.MSGPIPE) - if mojom.IsEnumKind(kind): - return JavaScriptDecodeSnippet(mojom.INT32) - - -def JavaScriptEncodeSnippet(kind): - if kind in mojom.PRIMITIVES: - return "encodeStruct(%s, " % CodecType(kind) - if mojom.IsStructKind(kind): - return "encodeStructPointer(%s, " % JavaScriptType(kind) - if mojom.IsMapKind(kind): - return "encodeMapPointer(%s, %s, " % \ - (ElementCodecType(kind.key_kind), ElementCodecType(kind.value_kind)) - if mojom.IsArrayKind(kind) and mojom.IsBoolKind(kind.kind): - return "encodeArrayPointer(codec.PackedBool, "; - if mojom.IsArrayKind(kind): - return "encodeArrayPointer(%s, " % CodecType(kind.kind) - if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind): - return JavaScriptEncodeSnippet(mojom.MSGPIPE) - if mojom.IsEnumKind(kind): - return JavaScriptEncodeSnippet(mojom.INT32) - - -def JavaScriptFieldOffset(packed_field): - return "offset + codec.kStructHeaderSize + %s" % packed_field.offset - - -def JavaScriptNullableParam(packed_field): - return "true" if mojom.IsNullableKind(packed_field.field.kind) else "false" - - -def GetArrayExpectedDimensionSizes(kind): - expected_dimension_sizes = [] - while mojom.IsArrayKind(kind): - expected_dimension_sizes.append(generator.ExpectedArraySize(kind) or 0) - kind = kind.kind - # Strings are serialized as variable-length arrays. - if (mojom.IsStringKind(kind)): - expected_dimension_sizes.append(0) - return expected_dimension_sizes - - -def JavaScriptValidateArrayParams(packed_field): - nullable = JavaScriptNullableParam(packed_field) - field_offset = JavaScriptFieldOffset(packed_field) - element_kind = packed_field.field.kind.kind - element_size = pack.PackedField.GetSizeForKind(element_kind) - expected_dimension_sizes = GetArrayExpectedDimensionSizes( - packed_field.field.kind) - element_type = ElementCodecType(element_kind) - return "%s, %s, %s, %s, %s, 0" % \ - (field_offset, element_size, element_type, nullable, - expected_dimension_sizes) - - -def JavaScriptValidateStructParams(packed_field): - nullable = JavaScriptNullableParam(packed_field) - field_offset = JavaScriptFieldOffset(packed_field) - struct_type = JavaScriptType(packed_field.field.kind) - return "%s, %s, %s" % (field_offset, struct_type, nullable) - - -def JavaScriptValidateMapParams(packed_field): - nullable = JavaScriptNullableParam(packed_field) - field_offset = JavaScriptFieldOffset(packed_field) - keys_type = ElementCodecType(packed_field.field.kind.key_kind) - values_kind = packed_field.field.kind.value_kind; - values_type = ElementCodecType(values_kind) - values_nullable = "true" if mojom.IsNullableKind(values_kind) else "false" - return "%s, %s, %s, %s, %s" % \ - (field_offset, nullable, keys_type, values_type, values_nullable) - - -def JavaScriptValidateStringParams(packed_field): - nullable = JavaScriptNullableParam(packed_field) - return "%s, %s" % (JavaScriptFieldOffset(packed_field), nullable) - - -def JavaScriptValidateHandleParams(packed_field): - nullable = JavaScriptNullableParam(packed_field) - field_offset = JavaScriptFieldOffset(packed_field) - return "%s, %s" % (field_offset, nullable) - - - - -def JavaScriptProxyMethodParameterValue(parameter): - name = parameter.name; - if (IsInterfaceParameter(parameter)): - type = JavaScriptType(parameter.kind) - return "core.isHandle(%s) ? %s : connection.bindProxyClient" \ - "(%s, %s, %s.client)" % (name, name, name, type, type) - if (IsInterfaceRequestParameter(parameter)): - type = JavaScriptType(parameter.kind.kind) - return "core.isHandle(%s) ? %s : connection.bindProxyClient" \ - "(%s, %s.client, %s)" % (name, name, name, type, type) - return name; - -def JavaScriptStubMethodParameterValue(parameter): - name = parameter.name; - if (IsInterfaceParameter(parameter)): - type = JavaScriptType(parameter.kind) - return "connection.bindProxyHandle(%s, %s.client, %s)" % (name, type, type) - if (IsInterfaceRequestParameter(parameter)): - type = JavaScriptType(parameter.kind.kind) - return "connection.bindProxyHandle(%s, %s, %s.client)" % (name, type, type) - return name; - -def TranslateConstants(token): - if isinstance(token, (mojom.EnumValue, mojom.NamedValue)): - # Both variable and enum constants are constructed like: - # NamespaceUid.Struct[.Enum].CONSTANT_NAME - name = [] - if token.imported_from: - name.append(token.imported_from["unique_name"]) - if token.parent_kind: - name.append(token.parent_kind.name) - if isinstance(token, mojom.EnumValue): - name.append(token.enum.name) - name.append(token.name) - return ".".join(name) - - if isinstance(token, mojom.BuiltinValue): - if token.value == "double.INFINITY" or token.value == "float.INFINITY": - return "Infinity"; - if token.value == "double.NEGATIVE_INFINITY" or \ - token.value == "float.NEGATIVE_INFINITY": - return "-Infinity"; - if token.value == "double.NAN" or token.value == "float.NAN": - return "NaN"; - - return token - - -def ExpressionToText(value): - return TranslateConstants(value) - -def IsArrayPointerField(field): - return mojom.IsArrayKind(field.kind) - -def IsStringPointerField(field): - return mojom.IsStringKind(field.kind) - -def IsStructPointerField(field): - return mojom.IsStructKind(field.kind) - -def IsMapPointerField(field): - return mojom.IsMapKind(field.kind) - -def IsHandleField(field): - return mojom.IsAnyHandleKind(field.kind) - -def IsInterfaceRequestParameter(parameter): - return mojom.IsInterfaceRequestKind(parameter.kind) - -def IsInterfaceParameter(parameter): - return mojom.IsInterfaceKind(parameter.kind) - - -class Generator(generator.Generator): - - js_filters = { - "default_value": JavaScriptDefaultValue, - "payload_size": JavaScriptPayloadSize, - "decode_snippet": JavaScriptDecodeSnippet, - "encode_snippet": JavaScriptEncodeSnippet, - "expression_to_text": ExpressionToText, - "field_offset": JavaScriptFieldOffset, - "has_callbacks": mojom.HasCallbacks, - "is_array_pointer_field": IsArrayPointerField, - "is_map_pointer_field": IsMapPointerField, - "is_struct_pointer_field": IsStructPointerField, - "is_string_pointer_field": IsStringPointerField, - "is_handle_field": IsHandleField, - "js_type": JavaScriptType, - "is_interface_request_parameter": IsInterfaceRequestParameter, - "is_interface_parameter": IsInterfaceParameter, - "js_proxy_method_parameter_value": JavaScriptProxyMethodParameterValue, - "js_stub_method_parameter_value": JavaScriptStubMethodParameterValue, - "stylize_method": generator.StudlyCapsToCamel, - "validate_array_params": JavaScriptValidateArrayParams, - "validate_handle_params": JavaScriptValidateHandleParams, - "validate_map_params": JavaScriptValidateMapParams, - "validate_string_params": JavaScriptValidateStringParams, - "validate_struct_params": JavaScriptValidateStructParams, - } - - def GetParameters(self): - return { - "namespace": self.module.namespace, - "imports": self.GetImports(), - "kinds": self.module.kinds, - "enums": self.module.enums, - "module": self.module, - "structs": self.GetStructs() + self.GetStructsFromMethods(), - "interfaces": self.module.interfaces, - "imported_interfaces": self.GetImportedInterfaces(), - } - - @UseJinja("js_templates/module.amd.tmpl", filters=js_filters) - def GenerateAMDModule(self): - return self.GetParameters() - - @UseJinja("js_templates/module.sky.tmpl", filters=js_filters) - def GenerateHTMLModule(self): - return self.GetParameters() - - def GenerateFiles(self, args): - self.Write(self.GenerateAMDModule(), - self.MatchMojomFilePath("%s.js" % self.module.name)) - self.Write(self.GenerateHTMLModule(), - self.MatchMojomFilePath("%s.sky" % self.module.name)) - - def GetImports(self): - used_names = set() - for each_import in self.module.imports: - simple_name = each_import["module_name"].split(".")[0] - - # Since each import is assigned a variable in JS, they need to have unique - # names. - unique_name = simple_name - counter = 0 - while unique_name in used_names: - counter += 1 - unique_name = simple_name + str(counter) - - used_names.add(unique_name) - each_import["unique_name"] = unique_name + "$" - counter += 1 - return self.module.imports - - def GetImportedInterfaces(self): - interface_to_import = {}; - for each_import in self.module.imports: - for each_interface in each_import["module"].interfaces: - name = each_interface.name - interface_to_import[name] = each_import["unique_name"] + "." + name - return interface_to_import; - diff --git a/mojo/public/tools/bindings/generators/mojom_python_generator.py b/mojo/public/tools/bindings/generators/mojom_python_generator.py deleted file mode 100644 index 33bfdd5..0000000 --- a/mojo/public/tools/bindings/generators/mojom_python_generator.py +++ /dev/null @@ -1,338 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Generates Python source files from a mojom.Module.""" - -import re -from itertools import ifilter - -import mojom.generate.generator as generator -import mojom.generate.data as data -import mojom.generate.module as mojom -from mojom.generate.template_expander import UseJinja - -_kind_to_type = { - mojom.BOOL: '_descriptor.TYPE_BOOL', - mojom.INT8: '_descriptor.TYPE_INT8', - mojom.UINT8: '_descriptor.TYPE_UINT8', - mojom.INT16: '_descriptor.TYPE_INT16', - mojom.UINT16: '_descriptor.TYPE_UINT16', - mojom.INT32: '_descriptor.TYPE_INT32', - mojom.UINT32: '_descriptor.TYPE_UINT32', - mojom.INT64: '_descriptor.TYPE_INT64', - mojom.UINT64: '_descriptor.TYPE_UINT64', - mojom.FLOAT: '_descriptor.TYPE_FLOAT', - mojom.DOUBLE: '_descriptor.TYPE_DOUBLE', - mojom.STRING: '_descriptor.TYPE_STRING', - mojom.NULLABLE_STRING: '_descriptor.TYPE_NULLABLE_STRING', - mojom.HANDLE: '_descriptor.TYPE_HANDLE', - mojom.DCPIPE: '_descriptor.TYPE_HANDLE', - mojom.DPPIPE: '_descriptor.TYPE_HANDLE', - mojom.MSGPIPE: '_descriptor.TYPE_HANDLE', - mojom.SHAREDBUFFER: '_descriptor.TYPE_HANDLE', - mojom.NULLABLE_HANDLE: '_descriptor.TYPE_NULLABLE_HANDLE', - mojom.NULLABLE_DCPIPE: '_descriptor.TYPE_NULLABLE_HANDLE', - mojom.NULLABLE_DPPIPE: '_descriptor.TYPE_NULLABLE_HANDLE', - mojom.NULLABLE_MSGPIPE: '_descriptor.TYPE_NULLABLE_HANDLE', - mojom.NULLABLE_SHAREDBUFFER: '_descriptor.TYPE_NULLABLE_HANDLE', -} - -# int64 integers are not handled by array.array. int64/uint64 array are -# supported but storage is not optimized (ie. they are plain python list, not -# array.array) -_kind_to_typecode_for_native_array = { - mojom.INT8: 'b', - mojom.UINT8: 'B', - mojom.INT16: 'h', - mojom.UINT16: 'H', - mojom.INT32: 'i', - mojom.UINT32: 'I', - mojom.FLOAT: 'f', - mojom.DOUBLE: 'd', -} - - -def NameToComponent(name): - # insert '_' between anything and a Title name (e.g, HTTPEntry2FooBar -> - # HTTP_Entry2_FooBar) - name = re.sub('([^_])([A-Z][^A-Z_]+)', r'\1_\2', name) - # insert '_' between non upper and start of upper blocks (e.g., - # HTTP_Entry2_FooBar -> HTTP_Entry2_Foo_Bar) - name = re.sub('([^A-Z_])([A-Z])', r'\1_\2', name) - return [x.lower() for x in name.split('_')] - -def UpperCamelCase(name): - return ''.join([x.capitalize() for x in NameToComponent(name)]) - -def CamelCase(name): - uccc = UpperCamelCase(name) - return uccc[0].lower() + uccc[1:] - -def ConstantStyle(name): - components = NameToComponent(name) - if components[0] == 'k': - components = components[1:] - return '_'.join([x.upper() for x in components]) - -def FieldStyle(name): - components = NameToComponent(name) - return '_'.join([x.lower() for x in components]) - -def GetNameForElement(element): - if (mojom.IsEnumKind(element) or mojom.IsInterfaceKind(element) or - mojom.IsStructKind(element) or isinstance(element, mojom.Method)): - return UpperCamelCase(element.name) - if isinstance(element, mojom.EnumValue): - return (GetNameForElement(element.enum) + '.' + - ConstantStyle(element.name)) - if isinstance(element, (mojom.NamedValue, - mojom.Constant)): - return ConstantStyle(element.name) - if isinstance(element, mojom.Field): - return FieldStyle(element.name) - raise Exception('Unexpected element: %s' % element) - -def ExpressionToText(token): - if isinstance(token, (mojom.EnumValue, mojom.NamedValue)): - return str(token.computed_value) - - if isinstance(token, mojom.BuiltinValue): - if token.value == 'double.INFINITY' or token.value == 'float.INFINITY': - return 'float(\'inf\')'; - if (token.value == 'double.NEGATIVE_INFINITY' or - token.value == 'float.NEGATIVE_INFINITY'): - return 'float(\'-inf\')' - if token.value == 'double.NAN' or token.value == 'float.NAN': - return 'float(\'nan\')'; - - if token in ['true', 'false']: - return str(token == 'true') - - return token - -def GetFullyQualifiedName(kind): - name = [] - if kind.imported_from: - name.append(kind.imported_from['python_module']) - name.append(GetNameForElement(kind)) - return '.'.join(name) - -def GetFieldType(kind, field=None): - if mojom.IsArrayKind(kind): - arguments = [] - if kind.kind in _kind_to_typecode_for_native_array: - arguments.append('%r' % _kind_to_typecode_for_native_array[kind.kind]) - elif kind.kind != mojom.BOOL: - arguments.append(GetFieldType(kind.kind)) - if mojom.IsNullableKind(kind): - arguments.append('nullable=True') - if kind.length is not None: - arguments.append('length=%d' % kind.length) - array_type = 'GenericArrayType' - if kind.kind == mojom.BOOL: - array_type = 'BooleanArrayType' - elif kind.kind in _kind_to_typecode_for_native_array: - array_type = 'NativeArrayType' - return '_descriptor.%s(%s)' % (array_type, ', '.join(arguments)) - - if mojom.IsMapKind(kind): - arguments = [ - GetFieldType(kind.key_kind), - GetFieldType(kind.value_kind), - ] - if mojom.IsNullableKind(kind): - arguments.append('nullable=True') - return '_descriptor.MapType(%s)' % ', '.join(arguments) - - if mojom.IsStructKind(kind): - arguments = [ 'lambda: %s' % GetFullyQualifiedName(kind) ] - if mojom.IsNullableKind(kind): - arguments.append('nullable=True') - return '_descriptor.StructType(%s)' % ', '.join(arguments) - - if mojom.IsEnumKind(kind): - return GetFieldType(mojom.INT32) - - if mojom.IsInterfaceKind(kind): - arguments = [ 'lambda: %s' % GetFullyQualifiedName(kind) ] - if mojom.IsNullableKind(kind): - arguments.append('nullable=True') - return '_descriptor.InterfaceType(%s)' % ', '.join(arguments) - - if mojom.IsInterfaceRequestKind(kind): - arguments = [] - if mojom.IsNullableKind(kind): - arguments.append('nullable=True') - return '_descriptor.InterfaceRequestType(%s)' % ', '.join(arguments) - - return _kind_to_type[kind] - -def GetFieldDescriptor(packed_field): - field = packed_field.field - class_name = 'SingleFieldGroup' - if field.kind == mojom.BOOL: - class_name = 'FieldDescriptor' - arguments = [ '%r' % GetNameForElement(field) ] - arguments.append(GetFieldType(field.kind, field)) - arguments.append(str(packed_field.index)) - arguments.append(str(packed_field.ordinal)) - if field.default: - if mojom.IsStructKind(field.kind): - arguments.append('default_value=True') - else: - arguments.append('default_value=%s' % ExpressionToText(field.default)) - return '_descriptor.%s(%s)' % (class_name, ', '.join(arguments)) - -def GetFieldGroup(byte): - if byte.packed_fields[0].field.kind == mojom.BOOL: - descriptors = map(GetFieldDescriptor, byte.packed_fields) - return '_descriptor.BooleanGroup([%s])' % ', '.join(descriptors) - assert len(byte.packed_fields) == 1 - return GetFieldDescriptor(byte.packed_fields[0]) - -def GetResponseStructFromMethod(method): - return generator.GetDataHeader( - False, generator.GetResponseStructFromMethod(method)) - -def GetStructFromMethod(method): - return generator.GetDataHeader( - False, generator.GetStructFromMethod(method)) - -def ComputeStaticValues(module): - in_progress = set() - computed = set() - - def GetComputedValue(named_value): - if isinstance(named_value, mojom.EnumValue): - field = next(ifilter(lambda field: field.name == named_value.name, - named_value.enum.fields), None) - if not field: - raise RuntimeError( - 'Unable to get computed value for field %s of enum %s' % - (named_value.name, named_value.enum.name)) - if field not in computed: - ResolveEnum(named_value.enum) - return field.computed_value - elif isinstance(named_value, mojom.ConstantValue): - ResolveConstant(named_value.constant) - named_value.computed_value = named_value.constant.computed_value - return named_value.computed_value - else: - print named_value - - def ResolveConstant(constant): - if constant in computed: - return - if constant in in_progress: - raise RuntimeError('Circular dependency for constant: %s' % constant.name) - in_progress.add(constant) - if isinstance(constant.value, (mojom.EnumValue, mojom.ConstantValue)): - computed_value = GetComputedValue(constant.value) - else: - computed_value = ExpressionToText(constant.value) - constant.computed_value = computed_value - in_progress.remove(constant) - computed.add(constant) - - def ResolveEnum(enum): - def ResolveEnumField(enum, field, default_value): - if field in computed: - return - if field in in_progress: - raise RuntimeError('Circular dependency for enum: %s' % enum.name) - in_progress.add(field) - if field.value: - if isinstance(field.value, mojom.EnumValue): - computed_value = GetComputedValue(field.value) - elif isinstance(field.value, str): - computed_value = int(field.value, 0) - else: - raise RuntimeError('Unexpected value: %s' % field.value) - else: - computed_value = default_value - field.computed_value = computed_value - in_progress.remove(field) - computed.add(field) - - current_value = 0 - for field in enum.fields: - ResolveEnumField(enum, field, current_value) - current_value = field.computed_value + 1 - - for constant in module.constants: - ResolveConstant(constant) - - for enum in module.enums: - ResolveEnum(enum) - - for struct in module.structs: - for constant in struct.constants: - ResolveConstant(constant) - for enum in struct.enums: - ResolveEnum(enum) - for field in struct.fields: - if isinstance(field.default, (mojom.ConstantValue, mojom.EnumValue)): - field.default.computed_value = GetComputedValue(field.default) - - return module - -def MojomToPythonImport(mojom): - return mojom.replace('.mojom', '_mojom') - -class Generator(generator.Generator): - - python_filters = { - 'expression_to_text': ExpressionToText, - 'field_group': GetFieldGroup, - 'fully_qualified_name': GetFullyQualifiedName, - 'name': GetNameForElement, - 'response_struct_from_method': GetResponseStructFromMethod, - 'struct_from_method': GetStructFromMethod, - } - - @UseJinja('python_templates/module.py.tmpl', filters=python_filters) - def GeneratePythonModule(self): - return { - 'enums': self.module.enums, - 'imports': self.GetImports(), - 'interfaces': self.GetQualifiedInterfaces(), - 'module': ComputeStaticValues(self.module), - 'structs': self.GetStructs(), - } - - def GenerateFiles(self, args): - import_path = MojomToPythonImport(self.module.name) - self.Write(self.GeneratePythonModule(), - self.MatchMojomFilePath('%s.py' % import_path)) - - def GetImports(self): - for each in self.module.imports: - each['python_module'] = MojomToPythonImport(each['module_name']) - return self.module.imports - - def GetQualifiedInterfaces(self): - """ - Returns the list of interfaces of the module. Each interface that has a - client will have a reference to the representation of the client interface - in the 'qualified_client' field. - """ - interfaces = self.module.interfaces - all_interfaces = [] + interfaces - for each in self.GetImports(): - all_interfaces += [data.KindFromImport(x, each) for x in - each['module'].interfaces]; - interfaces_by_name = dict((x.name, x) for x in all_interfaces) - for interface in interfaces: - if interface.client: - assert interface.client in interfaces_by_name, ( - 'Unable to find interface %s declared as client of %s.' % - (interface.client, interface.name)) - interface.qualified_client = interfaces_by_name[interface.client] - return sorted(interfaces, key=lambda i: (bool(i.client), i.name)) - - def GetJinjaParameters(self): - return { - 'lstrip_blocks': True, - 'trim_blocks': True, - } diff --git a/mojo/public/tools/bindings/generators/python_templates/module.py.tmpl b/mojo/public/tools/bindings/generators/python_templates/module.py.tmpl deleted file mode 100644 index 9f2f3dc..0000000 --- a/mojo/public/tools/bindings/generators/python_templates/module.py.tmpl +++ /dev/null @@ -1,57 +0,0 @@ -{% from "module_macros.tmpl" import enum_values %} -{% from "module_macros.tmpl" import struct_descriptor %} -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import mojo_bindings.descriptor as _descriptor -import mojo_bindings.reflection as _reflection -{% if imports %} - -{% for import in imports %} -import {{import.python_module}} -{% endfor %} -{% endif %} -{#--- Constants #} -{% if module.constants %} - -{% for constant in module.constants %} -{{constant|name}} = {{constant.value|expression_to_text}} -{% endfor %} -{% endif %} -{% for enum in enums %} - -class {{enum|name}}(object): - __metaclass__ = _reflection.MojoEnumType - VALUES = {{enum_values(enum)|indent(2)}} -{% endfor %} -{% for struct in structs %} - -class {{struct|name}}(object): - __metaclass__ = _reflection.MojoStructType - DESCRIPTOR = {{struct_descriptor(struct)|indent(2)}} -{% endfor %} -{% for interface in interfaces %} - -class {{interface|name}}(object): - __metaclass__ = _reflection.MojoInterfaceType - DESCRIPTOR = { -{% if interface.client %} - 'client': lambda: {{interface.qualified_client|fully_qualified_name}}, -{% endif %} - 'methods': [ -{% for method in interface.methods %} - { - 'name': '{{method|name}}', - 'ordinal': {{method.ordinal}}, -{% set request_struct = method|struct_from_method %} - 'parameters': {{struct_descriptor(request_struct)|indent(8)}}, -{% if method.response_parameters != None %} -{% set response_struct = method|response_struct_from_method %} - 'responses': {{struct_descriptor(response_struct)|indent(8)}}, -{% endif %} - }, -{% endfor %} - ], - } -{% endfor %} diff --git a/mojo/public/tools/bindings/generators/python_templates/module_macros.tmpl b/mojo/public/tools/bindings/generators/python_templates/module_macros.tmpl deleted file mode 100644 index b42fc30..0000000 --- a/mojo/public/tools/bindings/generators/python_templates/module_macros.tmpl +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{%- macro enum_values(enum) -%} -[ -{% for field in enum.fields %} - ('{{field.name}}', {{field.computed_value}}), -{% endfor %} -] -{%- endmacro -%} - -{%- macro struct_descriptor(struct) -%} -{ -{% if struct.constants %} - 'constants': { -{% for constant in struct.constants %} - '{{constant|name}}': {{constant.value|expression_to_text}}, -{% endfor %} - }, -{% endif %} -{% if struct.enums %} - 'enums': { -{% for enum in struct.enums %} - '{{enum|name}}': {{enum_values(enum)|indent(6)}}, -{% endfor %} - }, -{% endif %} -{% if struct.fields %} - 'fields': [ -{% for byte in struct.bytes %} -{% if byte.packed_fields %} - {{byte|field_group}}, -{% endif %} -{% endfor %} - ], -{% endif %} -} -{%- endmacro -%} diff --git a/mojo/public/tools/bindings/generators/run_cpp_generator.py b/mojo/public/tools/bindings/generators/run_cpp_generator.py deleted file mode 100755 index 4c6f597..0000000 --- a/mojo/public/tools/bindings/generators/run_cpp_generator.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import ast -import os -import sys - -script_dir = os.path.dirname(os.path.realpath(__file__)) -sys.path.insert(0, os.path.join(script_dir, os.pardir, "pylib")) - -from mojom.generate.data -import mojom_cpp_generator - -def ReadDict(file): - with open(file, 'r') as f: - s = f.read() - dict = ast.literal_eval(s) - return dict - -dict = ReadDict(sys.argv[1]) -module = mojom.generate.data.ModuleFromData(dict) -dir = None -if len(sys.argv) > 2: - dir = sys.argv[2] -cpp = mojom_cpp_generator.Generator(module, ".", dir) -cpp.GenerateFiles([]) |