summaryrefslogtreecommitdiff
path: root/buildscripts/idl/idl/struct_types.py
blob: 8e055fe8c453c9deac92e6432f357b5fba422608 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# Copyright (C) 2017 MongoDB Inc.
#
# This program is free software: you can redistribute it and/or  modify
# it under the terms of the GNU Affero General Public License, version 3,
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""Provide code generation information for structs and commands in a polymorphic way."""

from __future__ import absolute_import, print_function, unicode_literals

from abc import ABCMeta, abstractmethod
from typing import Optional, List

from . import ast
from . import common
from . import cpp_types
from . import writer


class ArgumentInfo(object):
    """Class that encapsulates information about an argument to a method."""

    def __init__(self, arg):
        # type: (unicode) -> None
        """Create a instance of the ArgumentInfo class by parsing the argument string."""
        parts = arg.split(' ')
        self.type = ' '.join(parts[0:-1])
        self.name = parts[-1]

    def __str__(self):
        # type: () -> str
        """Return a formatted argument string."""
        return "%s %s" % (self.type, self.name)  # type: ignore


class MethodInfo(object):
    """Class that encapslates information about a method and how to declare, define, and call it."""

    def __init__(self, class_name, method_name, args, return_type=None, static=False, const=False,
                 explicit=False):
        # type: (unicode, unicode, List[unicode], unicode, bool, bool, bool) -> None
        # pylint: disable=too-many-arguments
        """Create a MethodInfo instance."""
        self.class_name = class_name
        self.method_name = method_name
        self.args = [ArgumentInfo(arg) for arg in args]
        self.return_type = return_type
        self.static = static
        self.const = const
        self.explicit = explicit

    def get_declaration(self):
        # type: () -> unicode
        """Get a declaration for a method."""
        pre_modifiers = ''
        post_modifiers = ''
        return_type_str = ''

        if self.static:
            pre_modifiers = 'static '

        if self.const:
            post_modifiers = ' const'

        if self.explicit:
            pre_modifiers += 'explicit '

        if self.return_type:
            return_type_str = self.return_type + ' '

        return common.template_args(
            "${pre_modifiers}${return_type}${method_name}(${args})${post_modifiers};",
            pre_modifiers=pre_modifiers, return_type=return_type_str, method_name=self.method_name,
            args=', '.join([str(arg) for arg in self.args]), post_modifiers=post_modifiers)

    def get_definition(self):
        # type: () -> unicode
        """Get a definition for a method."""
        pre_modifiers = ''
        post_modifiers = ''
        return_type_str = ''

        if self.const:
            post_modifiers = ' const'

        if self.return_type:
            return_type_str = self.return_type + ' '

        return common.template_args(
            "${pre_modifiers}${return_type}${class_name}::${method_name}(${args})${post_modifiers}",
            pre_modifiers=pre_modifiers, return_type=return_type_str, class_name=self.class_name,
            method_name=self.method_name, args=', '.join(
                [str(arg) for arg in self.args]), post_modifiers=post_modifiers)

    def get_call(self, obj):
        # type: (Optional[unicode]) -> unicode
        """Generate a simply call to the method using the defined args list."""

        args = ', '.join([arg.name for arg in self.args])

        if obj:
            return common.template_args("${obj}.${method_name}(${args});", obj=obj,
                                        method_name=self.method_name, args=args)

        return common.template_args("${method_name}(${args});", method_name=self.method_name,
                                    args=args)


class StructTypeInfoBase(object):
    """Base class for struct and command code generation."""

    __metaclass__ = ABCMeta

    @abstractmethod
    def get_constructor_method(self):
        # type: () -> MethodInfo
        """Get the constructor method for a struct."""
        pass

    @abstractmethod
    def get_serializer_method(self):
        # type: () -> MethodInfo
        """Get the serializer method for a struct."""
        pass

    @abstractmethod
    def get_to_bson_method(self):
        # type: () -> MethodInfo
        """Get the to_bson method for a struct."""
        pass

    @abstractmethod
    def get_deserializer_static_method(self):
        # type: () -> MethodInfo
        """Get the public static deserializer method for a struct."""
        pass

    @abstractmethod
    def get_deserializer_method(self):
        # type: () -> MethodInfo
        """Get the protected deserializer method for a struct."""
        pass

    @abstractmethod
    def get_op_msg_request_serializer_method(self):
        # type: () -> Optional[MethodInfo]
        """Get the OpMsg serializer method for a struct."""
        # pylint: disable=invalid-name
        pass

    @abstractmethod
    def get_op_msg_request_deserializer_static_method(self):
        # type: () -> Optional[MethodInfo]
        """Get the public static OpMsg deserializer method for a struct."""
        # pylint: disable=invalid-name
        pass

    @abstractmethod
    def get_op_msg_request_deserializer_method(self):
        # type: () -> Optional[MethodInfo]
        """Get the protected OpMsg deserializer method for a struct."""
        # pylint: disable=invalid-name
        pass

    @abstractmethod
    def gen_getter_method(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        """Generate the additional methods for a class."""
        pass

    @abstractmethod
    def gen_member(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        """Generate the additional members for a class."""
        pass

    @abstractmethod
    def gen_serializer(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        """Serialize the first field of a Command."""
        pass

    @abstractmethod
    def gen_namespace_check(self, indented_writer, db_name, element):
        # type: (writer.IndentedTextWriter, unicode, unicode) -> None
        """Generate the namespace check predicate for a command."""
        pass


class _StructTypeInfo(StructTypeInfoBase):
    """Class for struct code generation."""

    def __init__(self, struct):
        # type: (ast.Struct) -> None
        """Create a _StructTypeInfo instance."""
        self._struct = struct

    def get_constructor_method(self):
        # type: () -> MethodInfo
        class_name = common.title_case(self._struct.cpp_name)
        return MethodInfo(class_name, class_name, [])

    def get_deserializer_static_method(self):
        # type: () -> MethodInfo
        class_name = common.title_case(self._struct.cpp_name)
        return MethodInfo(class_name, 'parse',
                          ['const IDLParserErrorContext& ctxt', 'const BSONObj& bsonObject'],
                          class_name, static=True)

    def get_deserializer_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'parseProtected',
            ['const IDLParserErrorContext& ctxt', 'const BSONObj& bsonObject'], 'void')

    def get_serializer_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'serialize', ['BSONObjBuilder* builder'],
            'void', const=True)

    def get_to_bson_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'toBSON', [], 'BSONObj', const=True)

    def get_op_msg_request_serializer_method(self):
        # type: () -> Optional[MethodInfo]
        return None

    def get_op_msg_request_deserializer_static_method(self):
        # type: () -> Optional[MethodInfo]
        return None

    def get_op_msg_request_deserializer_method(self):
        # type: () -> Optional[MethodInfo]
        return None

    def gen_getter_method(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        pass

    def gen_member(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        pass

    def gen_serializer(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        pass

    def gen_namespace_check(self, indented_writer, db_name, element):
        # type: (writer.IndentedTextWriter, unicode, unicode) -> None
        pass


class _CommandBaseTypeInfo(_StructTypeInfo):
    """Base class for command code generation."""

    def __init__(self, command):
        # type: (ast.Command) -> None
        """Create a _CommandBaseTypeInfo instance."""
        self._command = command

        super(_CommandBaseTypeInfo, self).__init__(command)

    def get_op_msg_request_serializer_method(self):
        # type: () -> Optional[MethodInfo]
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'serialize',
            ['const BSONObj& commandPassthroughFields'], 'OpMsgRequest', const=True)

    def get_op_msg_request_deserializer_static_method(self):
        # type: () -> Optional[MethodInfo]
        class_name = common.title_case(self._struct.cpp_name)
        return MethodInfo(class_name, 'parse',
                          ['const IDLParserErrorContext& ctxt', 'const OpMsgRequest& request'],
                          class_name, static=True)

    def get_op_msg_request_deserializer_method(self):
        # type: () -> Optional[MethodInfo]
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'parseProtected',
            ['const IDLParserErrorContext& ctxt', 'const OpMsgRequest& request'], 'void')


class _IgnoredCommandTypeInfo(_CommandBaseTypeInfo):
    """Class for command code generation."""

    def __init__(self, command):
        # type: (ast.Command) -> None
        """Create a _IgnoredCommandTypeInfo instance."""
        self._command = command

        super(_IgnoredCommandTypeInfo, self).__init__(command)

    def get_serializer_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'serialize',
            ['const BSONObj& commandPassthroughFields', 'BSONObjBuilder* builder'], 'void',
            const=True)

    def get_to_bson_method(self):
        # type: () -> MethodInfo
        # Commands that require namespaces require it as a parameter to serialize()
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'toBSON',
            ['const BSONObj& commandPassthroughFields'], 'BSONObj', const=True)

    def gen_serializer(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        indented_writer.write_line('builder->append("%s", 1);' % (self._command.name))

    def gen_namespace_check(self, indented_writer, db_name, element):
        # type: (writer.IndentedTextWriter, unicode, unicode) -> None
        pass


class _CommandFromType(_CommandBaseTypeInfo):
    """Class for command code generation for custom type."""

    def __init__(self, command):
        # type: (ast.Command) -> None
        """Create a _CommandFromType instance."""
        assert command.command_field
        self._command = command
        super(_CommandFromType, self).__init__(command)

    def get_constructor_method(self):
        # type: () -> MethodInfo
        cpp_type_info = cpp_types.get_cpp_type(self._command.command_field)
        # Use the storage type for the constructor argument since the generated code will use
        # std::move.
        member_type = cpp_type_info.get_storage_type()

        class_name = common.title_case(self._struct.cpp_name)

        arg = "const %s %s" % (member_type, common.camel_case(self._command.command_field.cpp_name))
        return MethodInfo(class_name, class_name, [arg], explicit=True)

    def get_serializer_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'serialize',
            ['const BSONObj& commandPassthroughFields', 'BSONObjBuilder* builder'], 'void',
            const=True)

    def get_to_bson_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'toBSON',
            ['const BSONObj& commandPassthroughFields'], 'BSONObj', const=True)

    def get_deserializer_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'parseProtected',
            ['const IDLParserErrorContext& ctxt', 'const BSONObj& bsonObject'], 'void')

    def gen_getter_method(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        raise NotImplementedError

    def gen_member(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        raise NotImplementedError

    def gen_serializer(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        raise NotImplementedError

    def gen_namespace_check(self, indented_writer, db_name, element):
        # type: (writer.IndentedTextWriter, unicode, unicode) -> None
        # TODO: should the name of the first element be validated??
        raise NotImplementedError


class _CommandWithNamespaceTypeInfo(_CommandBaseTypeInfo):
    """Class for command code generation."""

    def __init__(self, command):
        # type: (ast.Command) -> None
        """Create a _CommandWithNamespaceTypeInfo instance."""
        self._command = command

        super(_CommandWithNamespaceTypeInfo, self).__init__(command)

    def get_constructor_method(self):
        # type: () -> MethodInfo
        class_name = common.title_case(self._struct.cpp_name)
        return MethodInfo(class_name, class_name, ['const NamespaceString nss'], explicit=True)

    def get_serializer_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'serialize',
            ['const BSONObj& commandPassthroughFields', 'BSONObjBuilder* builder'], 'void',
            const=True)

    def get_to_bson_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'toBSON',
            ['const BSONObj& commandPassthroughFields'], 'BSONObj', const=True)

    def get_deserializer_method(self):
        # type: () -> MethodInfo
        return MethodInfo(
            common.title_case(self._struct.cpp_name), 'parseProtected',
            ['const IDLParserErrorContext& ctxt', 'const BSONObj& bsonObject'], 'void')

    def gen_getter_method(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        indented_writer.write_line('const NamespaceString& getNamespace() const { return _nss; }')

    def gen_member(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        indented_writer.write_line('NamespaceString _nss;')

    def gen_serializer(self, indented_writer):
        # type: (writer.IndentedTextWriter) -> None
        indented_writer.write_line('invariant(!_nss.isEmpty());')
        indented_writer.write_line('builder->append("%s", _nss.coll());' % (self._command.name))
        indented_writer.write_empty_line()

    def gen_namespace_check(self, indented_writer, db_name, element):
        # type: (writer.IndentedTextWriter, unicode, unicode) -> None
        # TODO: should the name of the first element be validated??
        indented_writer.write_line('invariant(_nss.isEmpty());')
        indented_writer.write_line('_nss = ctxt.parseNSCollectionRequired(%s, %s);' % (db_name,
                                                                                       element))


def get_struct_info(struct):
    # type: (ast.Struct) -> StructTypeInfoBase
    """Get type information about the struct or command to generate C++ code."""

    if isinstance(struct, ast.Command):
        if struct.namespace == common.COMMAND_NAMESPACE_IGNORED:
            return _IgnoredCommandTypeInfo(struct)
        elif struct.namespace == common.COMMAND_NAMESPACE_CONCATENATE_WITH_DB:
            return _CommandWithNamespaceTypeInfo(struct)
        return _CommandFromType(struct)

    return _StructTypeInfo(struct)