forked from dropbox/dropbox-sdk-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsharp.py
2120 lines (1792 loc) · 85.3 KB
/
csharp.py
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import itertools
import os
import re
import shutil
from collections import defaultdict, namedtuple
from contextlib import contextmanager
from stone.ir.data_types import (
Float32,
Float64,
Int32,
Int64,
UInt32,
UInt64,
is_bytes_type,
is_boolean_type,
is_user_defined_type,
is_list_type,
is_nullable_type,
is_numeric_type,
is_string_type,
is_struct_type,
is_tag_ref,
is_timestamp_type,
is_union_type,
is_void_type,
)
from stone.backend import CodeBackend
def memo_one(fn):
"""
Memorize a single argument instance method.
"""
cache = {}
def wrapper(self, arg):
value = cache.get(arg)
if value is not None:
return value
value = fn(self, arg)
cache[arg] = value
return value
return wrapper
ConstructorArg = namedtuple('ConstructorArg', ('type', 'name', 'arg', 'doc'))
class _CSharpGenerator(CodeBackend):
_CAMEL_CASE_RE = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
_CSHARP_KEYWORDS = frozenset({
'abstract', 'add', 'alias', 'as', 'ascending', 'async', 'await',
'base', 'bool', 'break', 'byte', 'case', 'catch', 'char', 'checked',
'class', 'const', 'continue', 'decimal', 'default', 'delegate',
'descending', 'do', 'double', 'dynamic', 'else', 'enum', 'event',
'explicit', 'extern', 'false', 'finally', 'fixed', 'float', 'for',
'foreach', 'from', 'get', 'global', 'goto', 'group', 'if', 'implicit',
'in', 'int', 'interface', 'internal', 'into', 'is', 'join', 'let',
'lock', 'long', 'namespace', 'new', 'null', 'object', 'operator',
'orderby', 'out', 'override', 'params', 'partial', 'private',
'protected', 'public', 'readonly', 'ref', 'remove', 'return', 'sbyte',
'sealed', 'select', 'set', 'short', 'sizeof', 'stackalloc', 'static',
'string', 'struct', 'switch', 'this', 'throw', 'true', 'try', 'typeof',
'uint', 'ulong', 'unchecked', 'unsafe', 'ushort', 'using', 'value',
'var', 'virtual', 'void', 'volatile', 'where', 'while', 'yield',
})
def __init__(self, namespace_name, app_name, *args, **kwargs):
"""
Initializes a new instance of CSharpGenerator.
Args:
namespace_name: The namespace name for all generated files.
app_name: The app name which will be used as prefix for all client classes.
*args:
**kwargs:
Returns:
"""
super().__init__(*args, **kwargs)
self._prefixes = []
self._prefix = ''
self._name_list = []
self._prevent_collisions = set()
self._generated_files = []
self._tag_context = None
self._namespace_name = namespace_name
self._app_name = app_name
def generate(self, api):
self._generate_route_auth_map(api)
for namespace in api.namespaces.values():
self._compute_related_types(namespace)
self._generate_namespace(namespace)
self._generate_client(api, '{}Client'.format(self._app_name), 'user')
self._generate_client(api, '{}TeamClient'.format(self._app_name), 'team')
self._generate_client(api, '{}AppClient'.format(self._app_name), 'app')
self._generate(api)
def _generate(self, api, generated_files):
"""
Override by derived generator to handle project specific logic.
Args:
generated_files:
Returns:
"""
raise NotImplementedError
@contextmanager
def cs_block(self, **kwargs):
"""
Context manager for an allman style block, which is more common
style for c#
"""
kwargs['allman'] = True
with self.block(**kwargs):
yield
@contextmanager
def region(self, label):
"""
Context manager for a c# region. All code emitted within the context
is within the region.
Args:
label (Union[str, unicode]): The region label
"""
self.emit('#region {}'.format(label))
self.emit()
yield
self.emit()
self.emit('#endregion')
def if_(self, condition):
"""
Context manager for an `if` statement. All code emitted within the context
is within the if statement.
Args:
condition (Union[str, unicode]): The if condition
"""
return self.cs_block(before='if ({})'.format(condition))
def else_(self):
"""
Context manager for an else statement. All code emitted within the context
is within the else statement.
"""
return self.cs_block(before='else')
def else_if(self, condition):
"""
Context manager for an `else if` statement. All code emitted within the
context is within the `else if` statement.
Args:
condition (Union[str, unicode]): The else if condition.
"""
return self.cs_block(before='else if ({})'.format(condition))
def namespace(self, name=None):
"""
Context manager for a `namespace` statement. All code emitted within the
context is within the namespace.
"""
ns_name = '{}.{}'.format(self._namespace_name, name) if name else self._namespace_name
return self.cs_block(before='namespace {}'.format(ns_name))
def class_(self, name, inherits=None, access=''):
"""
Context manager for a class. All code emitted within the context is part of
the class.
Args:
name (Union[str, unicode]): The name of the class.
inherits (str|iterable): The base types for the class, if any. If
this is a string it is added to the code verbatim, if an
iterable, then joined with ', '
access (Union[str, unicode]): The access modifierd of the class.
"""
elements = []
if access:
elements.append(access)
elements.append('class')
elements.append(name)
if inherits:
elements.append(':')
if isinstance(inherits, str):
elements.append(inherits)
else:
elements.append(', '.join(inherits))
return self.cs_block(before=' '.join(elements))
def using(self, declaration):
"""
Context manager for a `using` block. All code emitted within the context
is within the using block.
Args:
declaration (Union[str, unicode]): The using declaration.
"""
return self.cs_block(before='using ({})'.format(declaration))
def emit(self, text=''):
"""
Wraps the regular generator emit() method.
This is used by the prefix() and doc_comment() methods to prepend a
fixed string to each line emitted within those contexts.
Args:
text (Union[str, unicode]): The text to emit
"""
if text and self._prefix:
super().emit(self._prefix + text)
else:
super().emit(text)
def output_to_relative_path(self, filename, folder='Generated'):
"""
Wraps the regular generator output_to_relative_path() method.
This is used to keep track of the set of all files that are generated.
Args:
filename (Union[str, unicode]): The name of the file to generate.
folder (unicode): The folder for output files.
"""
filename = os.path.join(folder, filename)
self._generated_files.append(filename)
return super().output_to_relative_path(filename)
@contextmanager
def prefix(self, prefix):
"""
Context manager that prepends the supplied prefix to every line of text
that is emitted within the context.
Args:
prefix (Union[str, unicode]): The prefix to prepend to every line.
"""
self._prefixes.append(prefix)
self._prefix = ''.join(self._prefixes)
yield
self._prefixes.pop()
self._prefix = ''.join(self._prefixes)
@contextmanager
def doc_comment(self, data_type=None, is_constructor=False):
"""
Context manager that treats all lines of text emitted within the
context as part of a doc comment (i.e. prefixed with '///').
Args:
data_type (stone.data_type.DataType): The type for which this
documentation is being generated. This helps resolve references
in the _tag_handler method.
is_constructor (bool): Indicated whether this doc comment if for
a constructor - also used when resolving references.
"""
self._tag_context = (data_type, is_constructor)
with self.prefix('/// '):
yield
self._tag_context = None
def auto_generated(self):
"""
Generates a standard comment for the head of every file. This prevents
StyleCop from measuring the contents of the file.
"""
with self.prefix('// '):
self.emit('<auto-generated>')
self.emit('Auto-generated by StoneAPI, do not modify.')
self.emit('</auto-generated>')
self.emit()
def emit_wrapped_text(self, s, **kwargs):
"""
Wraps the regular generator emit_wrapped_text() method.
This does three things.
1. It ensures consistend prefix behavior with the modified emit method
2. It sets a default width of 95
3. It calls self.process_doc on the input string if the process keyword
is present
Args:
s (Union[str, unicode]): The string to emit and wrap.
process (callable): The function to handle tags in the emitted text.
"""
kwargs['prefix'] = self._prefix + kwargs.get('prefix', '')
if 'width' not in kwargs:
kwargs['width'] = 95
if 'process' in kwargs:
process = kwargs.pop('process')
s = self.process_doc(s, process)
super().emit_wrapped_text(s, **kwargs)
@contextmanager
def switch(self, expression):
"""
Context manager for a `switch` statement.
Args:
expression (Union[str, unicode]): The expression to switch on.
"""
self.emit('switch ({})'.format(expression))
self.emit('{')
yield
self.emit('}')
@contextmanager
def case(self, constant=None, needs_break=True):
"""
Context manager for a `case` statement.
Args:
constant (Union[str, unicode]): If this is not provided, then this is generated as
the default case.
need_break (bool): Indicates whether a break statement should
automatically be appended with the case statement ends.
"""
with self.indent():
self.emit('case {}:'.format(constant) if constant else 'default:')
with self.indent():
yield
if needs_break:
self.emit('break;')
@contextmanager
def _local_names(self, names):
"""
This context manager is used to help resolve names if there are
collisions between struct or union members and top level type names
within the namespace.
Args:
names (iterable of str): The local names.
"""
self._name_list.append(list(names))
self._prevent_collisions = set(itertools.chain(*self._name_list))
yield
self._name_list.pop()
self._prevent_collisions = set(itertools.chain(*self._name_list))
def emit_xml(self, doc, tag, **attrs):
"""
Emits an xml element.
Args:
doc (Union[str, unicode]): The contents of the xml element, if this is `None` then
the element is emitted in self closed form
tag (Union[str, unicode]): The xml element tag name.
attrs (dict): The attributes (if any) for the element
"""
tag_start = '<' + tag
if attrs:
tag_start += ' ' + ' '.join('{}="{}"'.format(k, v) for k,v in attrs.items())
if doc is None:
self.emit(tag_start + ' />')
else:
self.emit_wrapped_text('{}>{}</{}>'.format(tag_start, doc, tag),
process=self._get_tag_handler(self._ns))
@contextmanager
def xml_block(self, tag, **attrs):
"""
Context manager that includes all emitted code within an xml element
Args:
tag (Union[str, unicode]): The xml element tag name
attrs (dict): The xml element attributes, if any.
"""
if attrs:
attributes = ' '.join('{}="{}"'.format(k, v) for k,v in attrs.items())
self.emit('<{} {}>'.format(tag, attributes))
else:
self.emit('<{}>'.format(tag))
if self._prefixes:
yield
else:
with self.indent():
yield
self.emit('</{}>'.format(tag))
@contextmanager
def encoder_block(self, class_name):
"""
Context manager that emit the private decoder class
Args:
class_name (Union[str, unicode]): The class name for this decoder.
inherit (Union[str, unicode]): The base type for this decoder.
"""
self.emit()
with self.region('Encoder class'):
with self.doc_comment():
self.emit_summary('Encoder for <see cref="{}" />.'.format(class_name))
with self.class_(class_name + 'Encoder', inherits=['enc.StructEncoder<{}>'.format(class_name)],
access='private'):
with self.doc_comment():
self.emit_summary('Encode fields of given value.')
self.emit_xml('The value.', 'param', name='value')
self.emit_xml('The writer.', 'param', name='writer')
with self.cs_block(before='public override void EncodeFields({} value, enc.IJsonWriter writer)'.format(class_name)):
yield
@contextmanager
def decoder_block(self, class_name, inherit, is_void):
"""
Context manager that emit the private decoder class
Args:
class_name (Union[str, unicode]): The class name for this decoder.
inherit (Union[str, unicode]): The base type for this decoder.
"""
self.emit()
with self.region('Decoder class'):
with self.doc_comment():
self.emit_summary('Decoder for <see cref="{}" />.'.format(class_name))
with self.class_(class_name + 'Decoder', inherits=['enc.{}<{}>'.format(inherit, class_name)],
access='private'):
with self.doc_comment():
self.emit_summary('Create a new instance of type <see cref="{}" />.'.format(class_name))
self.emit_xml('The struct instance.', 'returns')
with self.cs_block(before='protected override {} Create()'.format(class_name)):
if is_void:
self.emit('return {}.Instance;'.format(class_name))
else:
self.emit('return new {}();'.format(class_name))
self.emit()
yield
@contextmanager
def decoder_decode_fields_block(self, class_name):
"""
Context manager that emit the DecodeFields override.
Args:
class_name (Union[str, unicode]): The class name for this decoder.
"""
with self.doc_comment():
self.emit_summary('Decode fields without ensuring start and end object.')
self.emit_xml('The json reader.', 'param', name='reader')
self.emit_xml('The decoded object.', 'returns')
with self.cs_block(before='public override {} DecodeFields(enc.IJsonReader reader)'.format(class_name)):
yield
@contextmanager
def decoder_set_field_block(self, class_name):
"""
Context manager that emit the SetField override block for struct decoder.
Args:
class_name (Union[str, unicode]): The class name for this decoder.
"""
with self.doc_comment():
self.emit_summary('Set given field.')
self.emit_xml('The field value.', 'param', name='value')
self.emit_xml('The field name.', 'param', name='fieldName')
self.emit_xml('The json reader.', 'param', name='reader')
with self.cs_block(
before='protected override void SetField({} value, string fieldName, enc.IJsonReader reader)'
.format(class_name)):
with self.switch('fieldName'):
yield
with self.case(needs_break=True):
self.emit('reader.Skip();')
@contextmanager
def decoder_tag_block(self, class_name):
"""
Context manager that emit the Decode(tag) override block for union decoder.
Args:
class_name (Union[str, unicode]): The class name for this decoder.
"""
with self.doc_comment():
self.emit_summary('Decode based on given tag.')
self.emit_xml('The tag.', 'param', name='tag')
self.emit_xml('The json reader.', 'param', name='reader')
self.emit_xml('The decoded object.', 'returns')
with self.cs_block(before='protected override {} Decode(string tag, enc.IJsonReader reader)'.format(class_name)):
yield
def emit_summary(self, doc=""):
"""
Emits the supplied documentation as a summary element.
Args:
doc (Union[str, unicode]): The documentation to emit, if this is multi-line, then
each line is wrapped in a `para` element.
"""
lines = doc.splitlines()
if len(lines) > 0:
with self.xml_block('summary'):
for line in lines:
self.emit_xml(line, 'para')
else:
self.emit_xml(doc, 'summary')
def emit_ctor_summary(self, class_name):
self.emit_summary('Initializes a new instance of the <see cref="{}" /> '
'class.'.format(class_name))
def _get_tag_handler(self, ns):
def tag_handler(tag, value):
"""
Passed as to the process_doc() method to handle tags that are found in
the documentation string
Args:
tag (Union[str, unicode]): The tag type, one of 'field|link|route|type|val'
value (Union[str, unicode]): The value of the tag.
"""
if tag == 'field':
if '.' in value:
parts = map(self._public_name, value.split('.'))
return '<see cref="{}.{}.{}" />'.format(self._namespace_name, ns, '.'.join(parts))
elif self._tag_context:
data_type, is_constructor = self._tag_context
if is_constructor:
return '<paramref name="{}" />'.format(self._arg_name(value, is_doc=True))
else:
return '<see cref="{}" />'.format(self._public_name(value))
else:
return '<paramref name="{}" />'.format(self._arg_name(value, is_doc=True))
elif tag == 'link':
parts = value.split(' ')
uri = parts[-1]
text = ' '.join(parts[:-1])
return '<a href="{}">{}</a>'.format(uri, text)
elif tag == 'route':
if '.' in value:
ns_name, route_name = value.split('.')
ns_name = self._public_name(ns_name)
else:
ns_name, route_name = ns, value
if ':' in route_name:
route_name, version_str = route_name.split(':')
version = int(version_str)
else:
route_name, version = route_name, 1
route_name = self._public_route_name(route_name, version)
auth_type = self._route_auth_map[(ns_name, route_name)]
links = []
for auth in auth_type:
links.append('<see cref="{0}.{1}.Routes.{1}{2}Routes.{3}Async" />'.format(
self._namespace_name, ns_name, self._public_name(auth), route_name))
return " ".join(links)
elif tag == 'type':
return '<see cref="{}" />'.format(self._public_name(value))
elif tag == 'val':
return '<c>{}</c>'.format(value.strip('`'))
else:
assert False, 'Unknown tag: {}:{}'.format(tag, value)
return tag_handler
def _typename(self, data_type, void=None, is_property=False, is_response=False, include_namespace=False):
"""
Generates a C# type from a data_type
The translations for the primitive types are the exact equivalent
C# value types. For composite types, the type name is represented using
CamelCase. The list type is handled slightly differently for the
property and constructor cases where it is an IList or IEnumerable
respectively.j
Args:
data_type (stone.data_type.DataType): The type to translate.
void (Union[str, unicode]): If supplied, this is the value to return if data_type
is void.
is_property (bool): Indicates whether the type translation is for
a property type. Lists have different types expressed for
properties than in other places.
is_response (bool): Indicates whether the type translation is for
a response type. Lists need to concrete list class in order to
be created by Apm.
include_namespace (bool): Indicates wheather the type translation includes
namespace. Sometimes this needs to be true to avoild colliding with property name.
"""
if is_nullable_type(data_type):
nullable = True
data_type = data_type.data_type
else:
nullable = False
name = data_type.name
if is_user_defined_type(data_type):
public = self._public_name(name)
type_ns = self._public_name(data_type.namespace.name)
if type_ns != self._ns or public in self._prevent_collisions or include_namespace:
return 'global::{}.{}.{}'.format(self._namespace_name, type_ns, public)
else:
return public
elif is_list_type(data_type):
if is_property:
return 'col.IList<{}>'.format(self._typename(data_type.data_type, is_property=True))
elif is_response:
return 'col.List<{}>'.format(self._typename(data_type.data_type, is_response=True))
else:
return 'col.IEnumerable<{}>'.format(self._typename(data_type.data_type))
elif is_string_type(data_type):
return 'string'
elif is_bytes_type(data_type):
return 'byte[]'
else:
suffix = '?' if nullable else ''
if is_boolean_type(data_type):
typename = 'bool'
elif isinstance(data_type, Int32):
typename = 'int'
elif isinstance(data_type, UInt32):
typename = 'uint'
elif isinstance(data_type, Int64):
typename = 'long'
elif isinstance(data_type, UInt64):
typename = 'ulong'
elif isinstance(data_type, Float32):
typename = 'float'
elif isinstance(data_type, Float64):
typename = 'double'
elif is_timestamp_type(data_type):
typename = 'sys.DateTime'
elif is_void_type(data_type):
return void or 'void'
else:
assert False, 'Unknown data type %r' % data_type
return typename + suffix
@staticmethod
def _process_literal(literal):
"""
Translate literal values used in defaults
Args:
literal: The literal value.
"""
if isinstance(literal, bool):
return 'true' if literal else 'false'
elif isinstance(literal, str):
return '\"{}\"'.format(literal)
return literal
@staticmethod
def _type_literal_suffix(data_type):
"""
Returns the suffix needed to make a numeric literal values type explicit.
Args:
data_type (stone.data_type.DataType): The type in question.
"""
if not is_numeric_type(data_type) or isinstance(data_type, Int32):
return ''
elif isinstance(data_type, UInt32):
return 'U'
elif isinstance(data_type, Int64):
return 'L'
elif isinstance(data_type, UInt64):
return 'UL'
elif isinstance(data_type, Float32):
return 'F'
elif isinstance(data_type, Float64):
return 'D'
else:
assert False, 'Unknown numeric data type %r' % data_type
@staticmethod
def _could_be_null(data_type):
"""
Returns true if 'data_type' could be null, i.e. if it is not a value type
Args:
data_type (stone.data_type.DataType): The type in question.
"""
return is_user_defined_type(data_type) or is_string_type(data_type) or is_list_type(data_type)
@staticmethod
def _verbatim_string(string):
"""
Creates a C# verbatim string (way easier than dealing with escapes)
Args:
string (Union[str, unicode]): The string to represent.
"""
return '@"{}"'.format(string.replace('"', '""'))
def _process_composite_default(self, field, include_null_check=True):
"""
Generate code to initialize a default value for a composite field.
Note: This is not implemented for fields that are structs.
Args:
field: (stone.data_type.Field): The field to initialize.
include_null_check (bool): Indicates whether a check for an
argument being null should be emitted.
"""
if is_struct_type(field.data_type):
raise NotImplementedError()
elif is_union_type(field.data_type):
self._process_union_default(field, include_null_check)
else:
assert False, 'field is neither struct nor union: {}.'.format(field)
def _process_union_default(self, field, include_null_check):
"""
Generate code to initialize a default value for a field that is a union.
Note: This only works for union fields that don't have arguments.
Args:
field: (stone.data_type.Field): The field to initialize.
include_null_check (bool): Indicates whether a check for an
argument being null should be emitted.
"""
assert is_tag_ref(field.default), (
'Default union value is not a tag ref: {}'.format(field.default))
union = field.default.union_data_type
default = field.default.tag_name
arg_name = (self._arg_name(field.name) if include_null_check else
'this.{}'.format(self._public_name(field.name)))
assign_default = '{} = {}.{}.Instance;'.format(
arg_name, self._typename(union, include_namespace=True),
self._public_name(default))
if include_null_check:
with self.if_('{} == null'.format(arg_name)):
self.emit(assign_default)
else:
self.emit(assign_default)
def _check_constraints(self, name, data_type, has_null_check):
"""
Emits code to checks the validity of a field when constructing an
object.
Args:
name (Union[str, unicode]): The field name.
data_type (stone.data_type.DataType): The type of the field
has_null_check (bool): Indicates whether prior code has already
generated a null check for this field - this happens if a
composite field has a default.
"""
if is_nullable_type(data_type):
nullable = True
data_type = data_type.data_type
else:
nullable = False
checks = []
if is_numeric_type(data_type):
suffix = self._type_literal_suffix(data_type)
if data_type.min_value is not None:
checks.append(('{} < {}{}'.format(name, data_type.min_value, suffix),
'"Value should be greater or equal than {}"'.format(data_type.min_value)))
if data_type.max_value is not None:
checks.append(('{} > {}{}'.format(name, data_type.max_value, suffix),
'"Value should be less of equal than {}"'.format(data_type.max_value)))
elif is_string_type(data_type):
if data_type.min_length is not None:
checks.append(('{}.Length < {}'.format(name, data_type.min_length),
'"Length should be at least {}"'.format(data_type.min_length)))
if data_type.max_length is not None:
checks.append(('{}.Length > {}'.format(name, data_type.max_length),
'"Length should be at most {}"'.format(data_type.max_length)))
if data_type.pattern is not None:
# patterns must match entire input sequence:
pattern = '\\A(?:{})\\z'.format(data_type.pattern)
checks.append(('!re.Regex.IsMatch({}, {})'.format(name, self._verbatim_string(pattern)),
self._verbatim_string("Value should match pattern '{}'".format(pattern))))
elif is_list_type(data_type):
list_name = name + 'List'
self.emit('var {} = enc.Util.ToList({});'.format(list_name, name))
self.emit()
if data_type.min_items is not None:
checks.append(('{}.Count < {}'.format(list_name, data_type.min_items),
'"List should at at least {} items"'.format(data_type.min_items)))
if data_type.max_items is not None:
checks.append(('{}.Count > {}'.format(list_name, data_type.max_items),
'"List should at at most {} items"'.format(data_type.max_items)))
has_checks = len(checks) > 0
def apply_checks():
for check, message in checks:
with self.if_('{}'.format(check)):
self.emit('throw new sys.ArgumentOutOfRangeException("{}", {});'.format(name, message))
if nullable:
if has_checks:
with self.if_('{} != null'.format(name)):
apply_checks()
else:
if self._could_be_null(data_type) and not has_null_check:
with self.if_('{} == null'.format(name)):
self.emit('throw new sys.ArgumentNullException("{}");'.format(name))
has_checks = True
apply_checks()
if has_checks:
self.emit()
def _arg_name(self, name, is_doc=False):
"""
Creates an initial lowercase camelCase representation of name.
This performs the following transformations.
foo_bar -> fooBar
fooBar -> fooBar
FooBar -> fooBar
Args:
name (Union[str, unicode]): The name to transform
is_doc (bool): If the arg name is in doc.
"""
public = self._public_name(name)
arg_name = public[0].lower() + public[1:]
if arg_name in _CSharpGenerator._CSHARP_KEYWORDS and not is_doc:
return '@' + arg_name
return arg_name
def _route_url(self, ns_name, route_name, route_version):
"""
Get url path for given route.
Args:
ns_name (Union[str, unicode]): The name of the namespace.
route_name (Union[str, unicode]): The name of the route.
route_version (int): The version of the route.
"""
route_url = '/{}/{}'.format(ns_name, route_name)
if route_version != 1:
route_url = "{}_v{}".format(route_url, route_version)
return '"{}"'.format(route_url)
def _public_route_name(self, name, version):
"""
Creates an initial capitalize CamelCase representation of a route name with optional version suffix.
This performs the following transformations.
foo_bar -> FooBar
foo_bar:2 -> FooBarV2
Args:
route (Union[str, unicode]): Name of the route.
version (int): Version number
"""
route_name = self._public_name(name)
if version != 1:
route_name = '{}V{}'.format(route_name, version)
return route_name
@memo_one
def _segment_name(self, name):
"""
Segments a name into a list of lowercase components.
Names are segmented on '/' or '_' characters and also on CamelCase boundaries.
Args:
name (Union[str, unicode]): The name to segment.
"""
name = name.replace('/', '_')
name = _CSharpGenerator._CAMEL_CASE_RE.sub(r'_\1', name).lower()
return name.split('_')
@memo_one
def _public_name(self, name):
"""
Creates an initial capitalize CamelCase representation of name.
This performs the following transformations.
foo_bar -> FooBar
fooBar -> FooBar
FooBar -> FooBar
Args:
name (Union[str, unicode]): The name to transform
"""
return ''.join(x.capitalize() for x in self._segment_name(name))
@memo_one
def _name_words(self, name):
"""
Creates a space separated sequence of words from a name.
This performs the following transformation.
foo_bar -> 'foo bar'
fooBar -> 'foo bar'
FooBar -> 'foo bar'
Args:
name (Union[str, unicode]): The name to transform
"""
return ' '.join(self._segment_name(name))
def _generate_client(self, api, client_name, auth_type):
"""
Generates a partial class for client name with given auth type only includes
the route declarations and the route initialization, the rest of the
class can be hand written separately.
Args:
api (stone.api.Api): The API specification.
client_name (Union[str, unicode]): The name of the client. e.g. XXXClient, XXXTeamClient
auth_type (Union[str, unicode]): The expected auth type for the client. e.g. User, Team
"""
with self.output_to_relative_path('{}.cs'.format(client_name)):
self.auto_generated()
with self.namespace():
self.emit('using sys = System;')
self.emit()
self.emit('using {}.Stone;'.format(self._namespace_name))
def enumerate_ns():
for ns in api.namespaces.values():
name = self._public_name(ns.name)
for auth, _ in self._get_routes(ns).items():
if auth == auth_type:
yield name
for ns_name in enumerate_ns():
self.emit('using {}.{}.Routes;'.format(self._namespace_name,
self._public_name(ns_name)))
self.emit()
auth_name = self._public_name(auth_type)
with self.class_(client_name, access='public sealed partial'):
first = True
for ns_name in enumerate_ns():
if first:
first = False
else:
self.emit()
with self.doc_comment():
self.emit_summary('Gets the {} routes.'.format(ns_name))
self.emit('public {0}{1}Routes {0} {{ get; private set; }}'
.format(ns_name, auth_name))
self.emit()
with self.doc_comment():
self.emit_summary('Initializes the routes.')
self.emit_xml('The transport.', 'returns')
with self.cs_block(before='internal override void InitializeRoutes(ITransport transport)'):
for ns_name in enumerate_ns():
self.emit('this.{0} = new {0}{1}Routes(transport);'.format(ns_name, auth_name))
def _compute_related_types(self, ns):
"""
This creates a map of supertype-subtype relationships.
This is used to generate `seealso` documentation, because the
specification type hierarchy is not always present in the generated
code.
"""
related_types = defaultdict(set)
for data_type in ns.data_types:
if not is_struct_type(data_type):
continue
struct_name = data_type.name
if data_type.parent_type:
related_types[data_type.parent_type.name].add(struct_name)
related_types[struct_name].add(self._typename(data_type.parent_type))
for field in data_type.all_fields:
if not is_struct_type(field.data_type):
continue
related_types[field.data_type.name].add(struct_name)