-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_structures.py
executable file
·3273 lines (2702 loc) · 118 KB
/
data_structures.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
#!/usr/bin/python
## @package data_structures
#
# Configurator data structures.
#
# The data structures are basically one-to-one with corresponding
# XML file data structures.
#
# Due to the nature of Python, the code generation code currently
# hangs off individual the individual class objects.
import os
import sys
import stat
import re
import xml.etree.ElementTree as ET
## @class Node
#
# Base class for tree displayable objects.
#
# The *Node* class is a common base class used for sub-classes that
# need to be displayable in the GUI as a part of a tree widget.
class Node:
## @brief *Node* Constructor
# @param self *Node* object being initialized.
# @param class_name *str* The textual name of the sub-class.
# @param text *str* Text to show on tree widget
# @param icon_name *str* Name of the icon to show next to object (or None).
# @param sub_nodes *list* The list of sub-class object under this *Node*.
# @param style *Style* object used for formatting.
#
# This method initializes *Node* with the *class_name* (e.g.
# "Module_Use", "Selection", etc.), the icon name from the
# Icons directory, *sub_nodes* which is a list of *Node*
# object that constitute the children of *self*, and *style*
# which is a *Style* object that specifies the format of
# generated code.
def __init__(self, class_name, text, icon_name, sub_nodes, style):
# Check argument types:
assert isinstance(class_name, str)
assert isinstance(text, str)
assert icon_name == None or isinstance(icon_name, str)
assert sub_nodes == None or isinstance(sub_nodes, list)
assert isinstance(style, Style)
if sub_nodes != None:
for sub_node in sub_nodes:
assert isinstance(sub_node, Node)
# Load up *self*:
self.class_name = class_name
self.icon_name = icon_name
self.text = text
self.style = style
self.sub_nodes = sub_nodes
## @brief Recursively find parent of *self* starting from *root_node*.
# @param self *Node* object to find parent of.
# @param root_node *Node* object to start search from
# @result The parent *Node* object (or *None* if not found.)
#
# Since the *Node* class does not maintain parent back pointers,
# finding a parent object actually requires a recursive search
# from the top most root *Node*.
def parent_index_find(self, root_node):
# Check argument types:
assert isinstance(root_node, Node)
result_node = None
result_index = -1
sub_nodes = root_node.sub_nodes
if sub_nodes != None:
for index in range(len(sub_nodes)):
sub_node = sub_nodes[index]
# We are done if *sub_node* matches:
if sub_node == self:
result_node = root_node
result_index = index
# We are done if one nodes under *sub_node* matches:
sub_node, sub_index = self.parent_index_find(sub_node)
if sub_node != None:
result_node = sub_node
result_index = sub_index
result_name = "<none>"
if result_node != None:
result_name = result_node.name
#print "parent_index_find({0}, {1})=>{2}, {3}". \
# format(self.name, root_node.name, result_name, result_index)
return result_node, result_index
## @brief Method print *self* indented by *indent*.
# @param self *Node* object to write out.
# @param indent *int* that specifies how much to indent by.
#
# This provides a quick and dirty interface for debugging.
def show(self, indent):
# Check argument types:
assert isinstance(indent, int)
print("{0}{1}:{2}".format(" " * indent, self.class_name, self.name))
sub_nodes = self.sub_nodes
if sub_nodes != None:
for sub_node in sub_nodes:
sub_node.show(indent + 1)
## @brief Append *sub_node* to the children sub nodes of *self*.
# @param self *Node* to whose children to append to
# @param sub_node *Node* to append children sub nodes
#
# This method will append *sub_node* to the end of the list of children
# sub nodes of *self*.
def sub_node_append(self, sub_node):
# Check argument types:
assert isinstance(sub_node, Node)
sub_nodes = self.sub_nodes
if sub_nodes == None:
sub_nodes = []
self.sub_nodes = sub_nodes
sub_nodes.append(sub_node)
## @brief Method writes *self* to *out_stream* indented by *indent*.
# @param self *Node* object to write out.
# @param indent *int* that specifies how much to indent by.
# @param out_stream *file* that specifies an output stream to write to.
#
# This method will write *self* in XML format to *out_stream* indented by
# *indent*. This method should be overridden to provide the correct
# tags and attributes .
def xml_write(self, indent, out_stream):
# Check argument types:
assert isinstance(indent, int)
assert isinstance(out_stream, file)
print(self)
assert False, "No write method for {0} Node". format(str(type(self)))
## @class Classification
#
# One Classification path for module
#
# A module can be shown in the "Selections" window in multiple locations.
# Each location is defined by a *Classification*. A *Classification*
# corresponds to the <Classification ... /> tag in module XML file.
# The attributes of the <Classification ... /> tag are *Level1*,
# *Level2*, etc. The *Level1* attribute is typically one of "Buses",
# "Categories", or "Vendors". Each level subsequent level nests one
# level deeper in the nesting tree.
class Classification():
## @brief *Classification* constructor
# @param self *Classification* object to initialize
# @param classification_element *Element* tree element to read from
# @param style *Style* object to control generated code formatting.
#
# This method will extract the classification information from
# the XML *classification_element* and store the result into *self*.
def __init__(self, classification_element, style):
# Check argument types:
assert isinstance(classification_element, ET.Element)
assert classification_element.tag == "Classification"
assert isinstance(style, Style)
# Get the attributes
attributes = classification_element.attrib
# Iterate through each of the 10 possible level attributes
# and append the values to *levels*:
levels = []
for index in range(1, 10):
level_name = "Level{0}".format(index)
if level_name in attributes:
# Found one, append it to *levels*
levels.append(attributes[level_name])
else:
# No more Level attributes, we are done:
break
# Stash the values away in to *self*:
self.levels = levels
self.style = style
## @class Description
#
# A Description of module function or register
#
# Each module has a textual description in its defining XML file.
# This class captures the descriptive text. This corresponds to:
#
# <Description>
# Text that describes function or register goes here.
# </Description>
#
# in the XML file.
class Description:
## @brief *Description* Constructor
# @param description_element *Element* that contains the Description XML
# @param style *Style* object that specifies how to format generate code.
#
# Initialize a *Description* object using *description_element*
# for the XML information and *style* for the formatting style.
def __init__(self, description_element, style):
# Check argument types:
assert isinstance(description_element, ET.Element)
assert description_element.tag == "Description", \
"Need <Description> tag"
assert isinstance(style, Style)
# Load up *self*:
self.style = style
self.text = description_element.text
## @brief Return the *Description* object from *parent_element*
# @param parent_element *Element* parent containing XML description
# @param style *Style* object that specifies how to format generate code.
# @result *Description* extracted from *parent_element*
#
# This static method is responsible for ensuring that there is one
# and only one <Description ...> tag underneight *parent_element*.
# The resulting *Description* is returned.
@staticmethod
def extract(parent_element, style):
# Extract all *descriptions* from *parent_element*:
descriptions = []
for description_element in parent_element.findall("Description"):
descriptions.append(Description(description_element, style))
# Make sure there is exacty one *description*:
if len(descriptions) == 1:
# We have exactly one; return it:
description = descriptions[0]
else:
# We either have none, or more than one, generate error message:
description = None
print("{0}:<{1} Name='{2}'...> has {3} <Description> tags". \
format(XML.line_number(parent_element), parent_element.tag,
parent_element.attrib["Name"], len(descriptions)))
return description
## @class Function
#
# One Function of a module
#
# A module can have one or more functions that can be invoked via
# a remote procedure call. A function has zero, one, or more parameters
# and zero, one, or more results. This shows up in the XML files as:
#
# <Function Name="..." Number="..." Brief="...">
# <Description>
# *Description goes here*
# </Description>
# <Parameter Name="..." Type="..." Brief="..." />
# ...
# <Result Name="..." Type="..." Brief="..." />
# ...
# </Function>
class Function(Node):
## @brief Function constructor
# @param self *Function* object to initialize
# @param function_element *Element* containing XML to extract from
# @param style *Style* object that specifies how to format generate code.
#
# This method extacts information about a remote procedure call
# function from *function_element* and stuffs it into *self*.
def __init__(self, function_element, style):
""" *Function*: """
# Check argument type:
assert isinstance(function_element, ET.Element)
assert isinstance(style, Style)
assert function_element.tag == "Function"
# Extract the <Function ...> attributes:
attributes = function_element.attrib
name = attributes["Name"]
brief = attributes["Brief"]
number = int(attributes["Number"])
# We need to have *style* loaded into *self* for *format*() to work.
self.name = name
self.style = style
# Build a signature for the function:
signature = "{0:r}(".format(self)
# Iterate over all the parameters:
prefix = ""
parameters = []
for parameter_element in function_element.findall("Parameter"):
parameter = Parameter(parameter_element, style)
parameters.append(parameter)
signature += prefix + parameter.name
prefix = ", "
signature += ")"
# Iteratate over all the results:
prefix = " => "
results = []
for result_element in function_element.findall("Result"):
result = Result(result_element, style)
results.append(result)
signature += prefix + result.name
# Load up the rest of *self*:
self.brief = brief
self.description = Description.extract(function_element, style)
self.number = number
self.parameters = parameters
self.results = results
# Initalize the parent *Node* base class.
Node.__init__(self, "Function", signature, None, None, style)
## @brief Format *self* using *fmt* string.
# @param self *Function* to use for formatting.
# @param fmt *str* that specifies the format to use
# @result *str* Formatted string is returned
#
# Format *self* using *fmt* to control formatting and return the
# formatted string. The allowed formatting strings are:
#
# * 'r' returns just the routine name in the appropriate style
# * 'S' returns C/C++ output signature.
# * 'Sxxx' returns the C/C++ output signature with 'xxx' spliced
# in before the routine name. This is used to splice a class
# name in front of the routine name. For example, 'SClass_Name::'
# will return "Class_name::{routine_name}(...)".
# * 's' returns a simplified signature that has just the a
# routine name, parameter name and result names in the form
# "routine_name(parameter_names, ...) => result_names, ...
def __format__(self, fmt):
""" *Function*: """
# Check argument types:
assert isinstance(fmt, str)
# Dispatch on *fmt*:
style = self.style
if fmt == "":
# Error:
result = "@Function@"
elif fmt == 'r':
# Routine name:
result = style.routine_name(self.name)
elif fmt[0] == 'S':
# Signature:
lexemes = []
# Figure out the return type:
results = self.results
results_length = len(results)
return_type = "void"
if results_length != 0:
return_type = results[0].type
# Generate return type
lexemes.append("{0} {1}{2:r}(".format(return_type, fmt[1:], self))
# Output the parameters:
prefix = ""
for parameter in self.parameters:
lexemes.append("{0}{1:c}".format(prefix, parameter))
prefix = ", "
# If there are more than 1 return result, add them to the
# parameter list as well:
if results_length >= 2:
for index in range(1, results_length):
result = results[index]
lexemes.append("{0}{1:t} *{1:n}".format(prefix, result))
prefix = ", "
# Wrap up:
lexemes.append(")");
result = "".join(lexemes)
elif fmt[0] == 's':
# Start with the routine name:
result = "{0:r}(".format(self)
# Append the parameters:
prefix = ""
for parameter in self.parameters:
result += "{0}{1:n}".format(prefix, parameter)
prefix = ", "
result += ")"
# Append the return results:
results = self.results
prefix = " => "
for result_node in self.results:
result += "{0}{1:n}".format(prefix, result_node)
prefix = ", "
else:
# Error:
result = "@Function:{0}@".format(fmt)
return result
## @brief Write the C++ method declaration for *self* to *out_stream*.
# @param self *Function* object to use for information
# @param module *Module* (Currently unused)
# @param out_stream *file* output stream to output to
#
# This routine will output a chunk of C++ code to *out_stream*
# that corresponds to method declaration in C++ class definition:
# The code looks roughly as follows:
#
# // BRIEF
# RT1 FUNCTION(PT1 PN1,...,PTn PNn,RT2 RN2,...,RTn RNn);
#
# where
#
# * FUNCTION is the function name
# * BRIEF is the 1 line comment brief
# * PNi is the i'th Parameter Name
# * PTi is the i'th Parameter Type
# * RNi is the i'th Result Name
# * RTi is the i'th Result Type
def cpp_header_write(self, module, out_stream):
""" *Function*: """
# Check argument types:
assert isinstance(module, Module)
assert isinstance(out_stream, file)
# Output: "// BRIEF"
style = self.style
out_stream.write("{0:i}// {1}\n".format(style, self.brief))
# Output: "RT1 FUNCTION(PT1 PN1,...,PTn PNn,RT2 RN2,...,RTn RNn);"
out_stream.write("{0:i}{1:S};\n\n".format(style, self))
## @brief Write local C++ RPC code for *self* to *out_stream*.
# @param self *Function* to use for parameters and return results
# @param module *Module* to use for module name and the like.
# @param out_stream *file* to write everything out to.
#
# This method will output the local remote procedure call C++ code
# for *function out to *out_stream*. The code looks basically
# like this:
#
# // FUNCTION: BRIEF
# RT1 MODULE::FUNCTION(PT1 PN1,...,PTn PNn, RT2 *RN2,...,RTn *RNn) {
# RT1 RN1;
# ...
# RTn RNn;
# //////// Edit begins here: {FUNCTION_NAME}
# //////// Edit ends here: {FUNCTION_NAME}
# return RN1;
# }
#
# where
#
# * FUNCTION is the function name
# * BRIEF is the 1 line comment brief
# * MODULE is the module name
# * PNi is the i'th Parameter Name
# * PTi is the i'th Parameter Type
# * RNi is the i'th Result Name
# * RTi is the i'th Result Type
def cpp_local_source_write(self, module, out_stream):
""" *Function*: """
# Check argument types:
assert isinstance(module, Module)
assert isinstance(out_stream, file)
# Grab some values from *self*:
style = self.style
name = self.name
results = self.results
results_length = len(results)
# Output "// FUNCTION: BRIEF"
out_stream.write("// {0:r}: {1}\n".format(self, self.brief))
# Output:
# "RT1 MODULE::FUNC(PT1 PN1,...,PTn PNn, RT2 *RN2,...,RTn *RNn) {"
# Compute the signature with {class_name}:: prepended to function name:
module_type_name = "{0:t}".format(module)
format_string = "{0:S" + module_type_name + "::}{1:b}"
#print "format_string='{0}'".format(format_string)
out_stream.write(format_string.format(self, style))
# Output variables for all the results:
for result in results:
# Output: "RTi RNi;"
out_stream.write("{0:i}{1:t} {1:n};\n".format(style, result))
# Output the code fence::
# //////// Edit begins here: {FUNCTION_NAME}
# //////// Edit ends here: {FUNCTION_NAME}
module.fence_write("{0:r}".format(self).upper(), out_stream)
# Output: "return RN1;":
if results_length != 0:
out_stream.write("{0:i}return {1};\n". \
format(style, self.results[0].name))
# Output: "}":
out_stream.write("{0:e}\n".format(style))
## @brief Write C++ code for RPC request handing for *self* to *out_stream*
# @param self *Function* to process
# @param offset *int* offset to use for function
# @param module_name *str* Module name to use
# @param out_stream *file* to write output to
#
# This method will output *self* to *out_stream* as a **case** clause
# as part of a **switch** statement. The basic format of the code
# that is generated looks as follows:
#
# case NUMBER: {
# // FUNCTION_NAME: BRIEF
# PN1 = maker_bus->PT1_get();
# ...
# PNn = maker_bus->PTn_get();
# RT1 RN1;
# ...
# RTn RNn;
# if (execute_mode) {
# RN1 = FUNCTION_NAME(PN1,...PNn,&RN2,...,&RNn);
# maker_bus->RT2_put(RN2);
# ...
# maker_bus->RTn_put(RNn);
# break;
# }
# }
#
# where
#
# * NUMBER is the RPC number
# * FUNCTION_NAME is the function name
# * BRIEF is the 1 line comment brief
# * PNi is the i'th Parameter Name
# * PTi is the i'th Parameter Type
# * RNi is the i'th Result Name
# * RTi is the i'th Result Type
def ino_slave_write(self, offset, variable_name, out_stream):
""" *Function*: """
# Check argument types:
assert isinstance(offset, int)
assert isinstance(variable_name, str)
assert isinstance(out_stream, file)
# Grab some values out of *self*:
brief = self.brief
name = self.name
number = self.number
parameters = self.parameters
results = self.results
results_length = len(results)
style = self.style
# Output: "case NUMBER: {"
out_stream.write("{0:i}case {1}:{0:b}".format(style, offset + number))
# Output: "// FUNCTION_NAME: BRIEF"
out_stream.write("{0:i}// {1:r}: {2}\n".format(style, self, brief))
# Fetch the each *parameter* value and stuff into a local variable:
for parameter in parameters:
# Output "PNi = maker_bus->PTi_get();"
parameter_type = parameter.type
out_stream.write("{0:i}{1:c} = maker_bus->{2}_get();\n". \
format(style, parameter, parameter_type.lower()))
# Define the variables needed for return values:
for result in results:
# Output: "RT1 RN1;"
out_stream.write("{0:i}{1:c};\n".format(style, result))
# Output: "if (execute_mode) {"
out_stream.write("{0:i}if (execute_mode){0:b}".format(style))
# Output: "RN1 = " (if needed):
out_stream.write("{0:i}".format(style))
if results_length >= 1:
out_stream.write("{0:n} = ".format(results[0]))
# Output: "FUNCTION_NAME(":
out_stream.write("{0}.{1:r}(".format(variable_name.lower(), self))
# Output: "PN1,...PNn" (if available):
prefix = ""
for parameter in parameters:
out_stream.write("{0}{1:n}".format(prefix, parameter))
prefix = ", "
# Output: ",&RN2,...,&RNn" (if necessary):
if results_length > 1:
for index in range(1, results_length):
result = results[index]
out_stream.write("{0}&{1:n};\n".format(prefix, result))
prefix = ", "
# Output: ");"
out_stream.write(");\n")
# Send any results to the send buffer:
for result in results:
# Output: "maker_bus->RTi_put(RNi);"
out_stream.write("{0:i}maker_bus->{1}_put({2:n});\n". \
format(style, result.type.lower(), result))
# Output: "}"
out_stream.write("{0:e}".format(style))
# Output: "break;"
out_stream.write("{0:i}break;\n".format(style))
# Output: "}"
out_stream.write("{0:e}".format(style))
## @brief Write remote side RPC code for *self* to *out_stream*.
# @param self *Function* to output RPC code for
# @param module *Module* to use for module name
# @param out_stream *file* to output code to
#
# The routine will look something like:
#
# // NAME: BRIEF
# RT1 MODULE::FUNCTION(PT1 PN1,...,PTn PNn,RT2 *RN2,...,RTn *RNn) {
# Bus_Module::command_begin(NUMBER);
# Bus_Module::PT1_put(P1);
# ...
# Bus_Module::PTn_put(Pn);
# RT1 R1 = Bus_Module::RT1_get();
# *RN2 = Bus_Module::RT2_get();
# ...
# *RNn = Bus_Module::RTn_get();
# Bus_Module::command_end();
# return RN1;
# }
#
# where
#
# * NUMBER is the RPC number
# * FUNCTION_NAME is the function name
# * BRIEF is the 1 line comment brief
# * PNi is the i'th Parameter Name
# * PTi is the i'th Parameter Type
# * RNi is the i'th Result Name
# * RTi is the i'th Result Type
def cpp_remote_source_write(self, module, out_stream):
""" *Function*: """
# Check argument types:
assert isinstance(module, Module)
assert isinstance(out_stream, file)
# Grab some values from *self*:
style = self.style
name = self.name
number = self.number
parameters = self.parameters
results = self.results
results_length = len(results)
# Output: "// NAME: BRIEF"
out_stream.write("// {0:r}: {1}\n".format(self, self.brief))
# Output:
# "T1 MODULE::FUNCTION(PT1 PN1,...,PTn PNn,RT2 *RN2,...,RTn *RNn) {":
format_string = "{0:S" + module.name + "::}{1:b}"
#print "format_string='{0}'".format(format_string)
out_stream.write(format_string.format(self, style))
# Output: "Bus_Module::command_begin(NUMBER);"
out_stream.write("{0:i}Bus_Module::command_begin({1});\n". \
format(style, number))
# Output the code to send the parameters over to the module:
for parameter in parameters:
# Output: Bus_Module::PTi_put(PNi);
out_stream.write("{0:i}Bus_Module::{1}_put({2:n});\n". \
format(style, parameter.type.lower(), parameter))
# Deal with RPC returned results:
for index in range(results_length):
result = results[index]
if index == 0:
# Output: "RT1 RN1 = Bus_Module::RT1_get();"
out_stream.write("{0:i}{1} {2} = ". \
format(style, result.type, result.name.lower()))
else:
# Output: "*RNi = Bus_Module::RTi_get();"
out_stream.write("{0:i}*{1} = ". \
format(style, result.type, result.name.lower()))
out_stream.write("Bus_Module::{0}_get();\n". \
format(result.type.lower()))
# Output: Bus_Module::command_end();
out_stream.write("{0:i}Bus_Module::command_end();\n". \
format(style))
# Output: "return RN1;"
if results_length != 0:
out_stream.write("{0:i}return {1};\n". \
format(style, results[0].name.lower()))
# Output: "}"
out_stream.write("{0:e}\n".format(style))
## @brief Output Python RPC code for *self* to *out_stream*
# @param self *Function* to output Python code for
# @param out_stream *file* to output Python code to
#
# This routine will output remote procedure call code for *self*
# to *out_stream*. The code looks as follows:
#
# def FUNCTION(self, PN1, ..., PNn):
# # BRIEF
# self.request_begin(NUMBER)
# self.request_PT1_put(PN1)
# ...
# self.request_PTn_put(PNn)
# self.request_end()
# RN1 = self.request_RT1_get()
# ...
# RNn = self.request_RTn_get()
# return RN1, ..., RNn
#
# where:
#
# * FUNCTION is the function name
# * BRIEF is the 1 line comment brief
# * PNi is the i'th Parameter Name
# * PTi is the i'th Parameter Type
# * RNi is the i'th Result Name
# * RTi is the i'th Result Type
def python_write(self, out_stream):
""" *Function*: """
# Check argument types:
assert isinstance(out_stream, file)
# Grab some values from *self*:
brief = self.brief
name = self.name
number = self.number
parameters = self.parameters
results = self.results
style = self.style
# Output: "def FUNCTION(self, PN1, ..., PNn):":
out_stream.write("{0:i}def {1:r}(self".format(style, self))
for parameter in parameters:
out_stream.write(", {0:n}".format(parameter))
out_stream.write("):\n")
# Indent code body:
style.indent_adjust(1)
# Output: "// BRIEF"
out_stream.write("{0:i}# {1}\n\n".format(style, brief))
# Output: "self.request_begin(NUMBER)"
out_stream.write("{0:i}self.request_begin({1})\n". \
format(style, number))
# Send each Parameter:
for parameter in parameters:
# Output: "self.request_PTx_put(PNx)
out_stream.write("{0:i}self.request_{1}_put({2:n})\n". \
format(style, parameter.type.lower(), parameter))
# Output: "self.request_end()"
out_stream.write("{0:i}self.request_end()\n".format(style))
# Get all return values:
for result in results:
# Output: "RNx = self.request_RTx_get()"
out_stream.write("{0:i}{1} = self.response_{2}_get()\n". \
format(style, result.name.lower(), result.type.lower()))
# Output: "return RN1, ..., RNn" (if necessary):
if len(results) != 0:
out_stream.write("{0:i}return ".format(style))
prefix = ""
for result in results:
out_stream.write("{0}{1:n}".format(prefix, result))
prefix = ", "
out_stream.write("\n")
out_stream.write("\n")
# Restore indentation:
style.indent_adjust(-1)
## @class Include
#
# One include file name for a module
#
# More needed here.
class Include():
## @brief *Include* constructor
# @param self *Include* object to initialize
# @param include_element *Element* tree element to read from
# @param style *Style* object to control generated code formatting.
#
# This method will extract the include information from
# the XML *include_element* and store the result into *self*.
def __init__(self, include_element, style):
# Check argument types:
assert isinstance(include_element, ET.Element)
assert include_element.tag == "Include"
assert isinstance(style, Style)
# Get the attributes
attributes = include_element.attrib
# Fill in *self*:
self.file_name = attributes["File_Name"]
## @class Module
#
# One Module device
#
# A *Module* corresponds to an electronic device that can be plugged
# together. The overall structure of a Module corresponds to an
# <Module ...> tag in an XML file:
#
# <Module Name="..." Vendor="..." Brief="...">
# <Overview>
# Module overview text goes here.
# </Overview>
# <Classification /> ...
# <Register /> ...
# <Function /> ...
# </Module>
class Module(Node):
## @brief Module constructor
# @param self *Module* to initialize
# @param module_element *ET.Element* to initialize from
# @param path *str* file path to .xml file read in
# @param style *Style* object that specifies how to format generate code.
#
# This method will initialize the contents of *self* by read the
# associated XML infromation from *module_element.
def __init__(self, module_element, path, style):
# Check arugment types:
assert isinstance(module_element, ET.Element) and \
module_element.tag == "Module"
assert isinstance(style, Style)
# Extract all classifications from <Classification ...> tags:
classifications = []
for classification_element in module_element.findall("Classification"):
classification = Classification(classification_element, style)
classifications.append(classification)
# Extract all of the includes from <Include ...> tags:
includes = []
for include_element in module_element.findall("Include"):
includes.append(Include(include_element, style))
# Extract all of the registers from <Register ...> tags:
registers = []
for register_element in module_element.findall("Register"):
registers.append(Register(register_element, style))
# Extract all of the functions from <Function ...> tags:
functions = []
for function_element in module_element.findall("Function"):
functions.append(Function(function_element, style))
# Extract overview form <Overview> tag:
overview = Overview.extract(module_element, style)
# Extract required attributes:
attributes = module_element.attrib
name = attributes["Name"]
vendor = attributes["Vendor"]
# Deal with optional attributes:
address_re = ""
if "Address_RE" in attributes:
address_re = attributes["Address_RE"]
address_type = ""
if "Address_Type" in attributes:
address_type = attributes["Address_Type"]
sub_class = None
if "Sub_Class" in attributes:
sub_class = attributes["Sub_Class"]
generate = ""
if "Generate" in attributes:
generate = attributes["Generate"]
# Fill in the contents of *self*:
self.classifications = classifications
self.address_re = address_re
self.address_type = address_type
self.fence_begin = " //////// Edit begins here:"
self.fence_end = " //////// Edit ends here:"
self.functions = functions
self.generate = generate
self.includes = includes
self.name = name
self.registers = registers
self.fences = {}
self.overview = overview
self.path = path
self.style = style
self.sub_class = sub_class
self.vendor = vendor
# Construct a sorted list of functions and registers:
functions_and_registers = []
for function in functions:
functions_and_registers.append(function)
for register in registers:
functions_and_registers.append(register)
functions_and_registers.sort(key=lambda fr: fr.name)
if len(functions_and_registers) == 0:
functions_and_registers = None
# Initilize the parent *Node* object:
Node.__init__(self,
"Module", name, None, functions_and_registers, style)
## @brief Return formatted version of *self* using *fmt* for format control.
# @param self *Module* to format
# @param fmt A *str* that controls formatting
# @result *str* formatted result string
#
# This mehod will return a formated version of *self* using *fmt* to
# control the formatting. *fmt* must be one of:
#
# * 'n' returns the module name.
# * 't' returns the module as a C/C++ type name
def __format__(self, fmt):
# Check argument types:
assert isinstance(fmt, str)
# Dispatch on *fmt*:
if fmt == 'n':
result = self.name
elif fmt == 't':
result = self.name.replace(" ", "_")
else:
result = "@Module:{0}@".format(fmt)
return result
## @brief Write C++ header file for *self* out to *file_name*.
# @param self *Module* to generate C++ for
# @param file_name *str* file name to open and write C++ into
# @param with_fences *bool* if *True*, causes fences to be written as well
#
# This method will write out a C++ header file that contains declarations
# for all the functions and registers associated with *module*.
def cpp_header_write(self, file_name, with_fences):
# Grab some values from *self*: