Salome HOME
Revert "Synchronize adm files"
[modules/paravis.git] / idl / pythonIDL.py
1 # -*- python -*-
2 #                           Package   : omniidl
3 # python.py                 Created on: 1999/10/29
4 #                           Author    : Duncan Grisby (dpg1)
5 #
6 #    Copyright (C) 1999 AT&T Laboratories Cambridge
7 #
8 #  This file is part of omniidl.
9 #
10 #  omniidl is free software; you can redistribute it and/or modify it
11 #  under the terms of the GNU General Public License as published by
12 #  the Free Software Foundation; either version 2 of the License, or
13 #  (at your option) any later version.
14 #
15 #  This program is distributed in the hope that it will be useful,
16 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 #  General Public License for more details.
19 #
20 #  You should have received a copy of the GNU General Public License
21 #  along with this program; if not, write to the Free Software
22 #  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23 #  02111-1307, USA.
24 #
25 # Description:
26 #   
27 #   Back-end for Python
28
29 # $Id$
30 # $Log$
31 # Revision 1.1.2.4  2009-11-18 15:56:23  vtn
32 # Trace support
33 #
34 # Revision 1.1.2.3  2009-11-17 12:15:43  vsv
35 # *** empty log message ***
36 #
37 # Revision 1.1.2.2  2009-11-05 14:57:23  vtn
38 # Added return array support.
39 #
40 # Revision 1.1.2.1  2009-11-03 13:14:05  vtn
41 # Added pathonIDL back-end for omniidl.
42 #
43 # Revision 1.33.2.13  2006/10/11 17:44:14  dgrisby
44 # None is not a keyword, but it cannot be assigned to.
45 #
46 # Revision 1.33.2.12  2006/09/29 16:48:03  dgrisby
47 # Stub changes broke use of package prefix. Thanks Teemu Torma.
48 #
49 # Revision 1.33.2.11  2006/09/07 15:28:57  dgrisby
50 # Remove obsolete check for presence of omniORB.StructBase.
51 #
52 # Revision 1.33.2.10  2006/06/21 14:46:26  dgrisby
53 # Invalid generated code for structs nested inside valuetypes.
54 #
55 # Revision 1.33.2.9  2006/01/19 17:28:44  dgrisby
56 # Merge from omnipy2_develop.
57 #
58 # Revision 1.33.2.8  2006/01/18 19:25:13  dgrisby
59 # Bug inheriting a valuetype from a typedef.
60 #
61 # Revision 1.33.2.7  2005/07/29 11:21:36  dgrisby
62 # Fix long-standing problem with module re-opening by #included files.
63 #
64 # Revision 1.33.2.6  2005/01/07 00:22:34  dgrisby
65 # Big merge from omnipy2_develop.
66 #
67 # Revision 1.33.2.5  2004/03/24 22:28:50  dgrisby
68 # TypeCodes / truncation for inherited state members were broken.
69 #
70 # Revision 1.33.2.4  2004/02/16 10:14:18  dgrisby
71 # Use stream based copy for local calls.
72 #
73 # Revision 1.33.2.3  2003/07/10 22:13:25  dgrisby
74 # Abstract interface support.
75 #
76 # Revision 1.33.2.2  2003/05/20 17:10:24  dgrisby
77 # Preliminary valuetype support.
78 #
79 # Revision 1.33.2.1  2003/03/23 21:51:56  dgrisby
80 # New omnipy3_develop branch.
81 #
82 # Revision 1.29.2.14  2002/11/25 21:31:09  dgrisby
83 # Friendly error messages with file errors, remove code to kill POA
84 # modules from pre-1.0.
85 #
86 # Revision 1.29.2.13  2002/07/04 13:14:52  dgrisby
87 # Bug with string escapes in Windows filenames.
88 #
89 # Revision 1.29.2.12  2002/05/27 01:02:37  dgrisby
90 # Fix bug with scope lookup in generated code. Fix TypeCode clean-up bug.
91 #
92 # Revision 1.29.2.11  2002/01/18 17:41:17  dpg1
93 # Support for "docstrings" in IDL.
94 #
95 # Revision 1.29.2.10  2002/01/18 15:49:45  dpg1
96 # Context support. New system exception construction. Fix None call problem.
97 #
98 # Revision 1.29.2.9  2001/12/04 12:17:08  dpg1
99 # Incorrect generated code for fixed constants.
100 #
101 # Revision 1.29.2.8  2001/08/29 11:57:16  dpg1
102 # Const fixes.
103 #
104 # Revision 1.29.2.7  2001/06/15 10:59:26  dpg1
105 # Apply fixes from omnipy1_develop.
106 #
107 # Revision 1.29.2.6  2001/06/13 11:29:04  dpg1
108 # Proper omniidl support for wchar/wstring constants.
109 #
110 # Revision 1.29.2.5  2001/05/10 15:16:03  dpg1
111 # Big update to support new omniORB 4 internals.
112 #
113 # Revision 1.29.2.4  2001/04/09 15:22:16  dpg1
114 # Fixed point support.
115 #
116 # Revision 1.29.2.3  2000/11/22 14:43:58  dpg1
117 # Support code set conversion and wchar/wstring.
118 #
119 # Revision 1.29.2.2  2000/11/01 15:29:01  dpg1
120 # Support for forward-declared structs and unions
121 # RepoIds in indirections are now resolved at the time of use
122 #
123 # Revision 1.29.2.1  2000/10/13 13:55:30  dpg1
124 # Initial support for omniORB 4.
125 #
126 # Revision 1.29  2000/10/02 17:34:58  dpg1
127 # Merge for 1.2 release
128 #
129 # Revision 1.27.2.3  2000/08/22 11:52:28  dpg1
130 # Generate inherited classes for typedef to struct/union.
131 #
132 # Revision 1.27.2.2  2000/08/07 09:19:24  dpg1
133 # Long long support
134 #
135 # Revision 1.27.2.1  2000/07/18 15:31:29  dpg1
136 # Bug with inheritance from typedef
137 #
138 # Revision 1.27  2000/07/12 14:32:13  dpg1
139 # New no_package option to omniidl backend
140 #
141 # Revision 1.26  2000/06/28 12:47:48  dpg1
142 # Proper error messages for unsupported IDL constructs.
143 #
144 # Revision 1.25  2000/06/27 15:01:48  dpg1
145 # Change from POA_M to M__POA mapping.
146 # Global module only built if necessary.
147 #
148 # Revision 1.24  2000/03/29 10:15:47  dpg1
149 # Exceptions now more closely follow the interface of
150 # exceptions.Exception.
151 #
152 # Revision 1.23  2000/03/17 12:28:09  dpg1
153 # Comma missing in nested union descriptor.
154 #
155 # Revision 1.22  2000/03/03 17:41:28  dpg1
156 # Major reorganisation to support omniORB 3.0 as well as 2.8.
157 #
158 # Revision 1.21  2000/02/23 10:20:52  dpg1
159 # Bug in descriptors for single-item enums.
160 #
161 # Revision 1.20  2000/01/04 15:29:41  dpg1
162 # Fixes to modules generated within a package.
163 #
164 # Revision 1.19  1999/12/21 16:06:15  dpg1
165 # DOH!  global= not module= !
166 #
167 # Revision 1.18  1999/12/21 16:05:11  dpg1
168 # New module= option.
169 #
170 # Revision 1.17  1999/12/17 11:39:52  dpg1
171 # New arguments to put modules and stubs in a specified package.
172 #
173 # Revision 1.16  1999/12/15 11:32:42  dpg1
174 # -Wbinline option added.
175 #
176 # Revision 1.15  1999/12/09 14:12:55  dpg1
177 # invokeOp() calls now on a single line. typedef now generates a class
178 # to be passed to CORBA.id().
179 #
180 # Revision 1.14  1999/12/07 15:35:14  dpg1
181 # Bug in currentScope handling.
182 #
183 # Revision 1.13  1999/11/30 10:41:20  dpg1
184 # Back-ends can now have their own usage string.
185 #
186 # Revision 1.12  1999/11/25 11:49:31  dpg1
187 # Minor version number bumped since server-side _is_a() required an
188 # incompatible change.
189 #
190 # Revision 1.11  1999/11/25 11:21:36  dpg1
191 # Proper support for server-side _is_a().
192 #
193 # Revision 1.10  1999/11/19 11:03:49  dpg1
194 # Extremely important spelling correction in a comment. :-)
195 #
196 # Revision 1.9  1999/11/12 15:53:48  dpg1
197 # New functions omniORB.importIDL() and omniORB.importIDLString().
198 #
199 # Revision 1.8  1999/11/11 15:55:29  dpg1
200 # Python back-end interface now supports valuetype declarations.
201 # Back-ends still don't support them, though.
202 #
203 # Revision 1.7  1999/11/10 16:08:22  dpg1
204 # Some types weren't registered properly.
205 #
206 # Revision 1.6  1999/11/04 11:46:12  dpg1
207 # Now uses our own version of the GNU C preprocessor.
208 #
209 # Revision 1.5  1999/11/02 12:17:26  dpg1
210 # Top-level module name now has a prefix of _0_ to avoid clashes with
211 # names of nested declarations.
212 #
213 # Revision 1.4  1999/11/02 10:54:01  dpg1
214 # Two small bugs in union generation.
215 #
216 # Revision 1.3  1999/11/02 10:01:46  dpg1
217 # Minor fixes.
218 #
219 # Revision 1.2  1999/11/01 20:19:55  dpg1
220 # Support for union switch types declared inside the switch statement.
221 #
222 # Revision 1.1  1999/11/01 16:40:11  dpg1
223 # First revision with new front-end.
224 #
225
226 """omniORB Python bindings"""
227
228 from omniidl import idlast, idltype, idlutil, idlvisitor, output, main
229 import sys, string, types, os.path, keyword
230
231 cpp_args = ["-D__OMNIIDL_PYTHON__"]
232 usage_string = """\
233   -Wbstdout       Send generated stubs to stdout rather than a file
234   -Wbinline       Output stubs for #included files in line with the main file
235   -Wbfactories    Register value factories for all valuetypes
236   -Wbpackage=p    Put both Python modules and stub files in package p
237   -Wbmodules=p    Put Python modules in package p
238   -Wbstubs=p      Put stub files in package p
239   -Wbextern=f:p   Assume Python stub file for file f is in package p.
240   -Wbglobal=g     Module to use for global IDL scope (default _GlobalIDL)"""
241
242 #""" Uncomment this line to get syntax highlighting on the output strings
243
244 # Output strings
245
246 pymodule_template = """\
247 # DO NOT EDIT THIS FILE!
248 #
249 # Python module @module@ generated by omniidl
250
251 import omniORB
252 omniORB.updateModule("@package@@module@")
253
254 # ** 1. Stub files contributing to this module
255
256 # ** 2. Sub-modules
257
258 # ** 3. End"""
259
260 file_start = """\
261 # Python stubs generated by omniidl from @filename@
262
263 import omniORB, _omnipy
264 from types import *
265 from omniORB import CORBA, PortableServer
266 _0_CORBA = CORBA
267
268 _omnipy.checkVersion(3,0, __file__)
269 """
270
271 file_end = """\
272 _exported_modules = ( @export_string@)
273
274 # The end."""
275
276 module_start = """
277 #
278 # Start of module "@sname@"
279 #
280 __name__ = "@package@@sname@"
281 _0_@sname@ = omniORB.openModule("@package@@sname@", r"@filename@")
282 _0_@s_sname@ = omniORB.openModule("@package@@s_sname@", r"@filename@")
283 """
284
285 module_end = """
286 #
287 # End of module "@sname@"
288 #
289 __name__ = "@package@@modname@"
290 """
291
292 import_idl_file = """\
293 # #include "@idlfile@"
294 import @ifilename@"""
295
296 open_imported_module_name = """\
297 _0_@imodname@ = omniORB.openModule("@package@@imodname@")
298 _0_@s_imodname@ = omniORB.openModule("@package@@s_imodname@")"""
299
300 forward_interface = """\
301
302 # @abstract@interface @ifid@;
303 _0_@modname@._d_@ifid@ = (omniORB.tcInternal.@tvkind@, "@repoId@", "@ifid@")
304 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@ifid@"""
305
306
307 interface_class = """\
308
309 # @abstract@interface @ifid@
310 _0_@modname@._d_@ifid@ = (omniORB.tcInternal.@tvkind@, "@repoId@", "@ifid@")
311 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@ifid@
312 _0_@modname@.@ifid@ = omniORB.newEmptyClass()
313 class @ifid@ @inherits@:
314     _NP_RepositoryId = _0_@modname@._d_@ifid@[1]
315
316     def __init__(self, *args, **kw):
317         raise RuntimeError("Cannot construct objects of this type.")
318
319     _nil = CORBA.Object._nil
320 """
321
322 interface_descriptor = """
323 _0_@modname@.@ifid@ = @ifid@
324 _0_@modname@._tc_@ifid@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@ifid@)
325 omniORB.registerType(@ifid@._NP_RepositoryId, _0_@modname@._d_@ifid@, _0_@modname@._tc_@ifid@)"""
326
327 callables_header = """
328 # @ifid@ operations and attributes"""
329
330 attribute_get_descriptor = """\
331 @ifid@._d__get_@attr@ = ((),(@descr@,),None)"""
332
333 attribute_set_descriptor = """\
334 @ifid@._d__set_@attr@ = ((@descr@,),(),None)"""
335
336 operation_descriptor = """\
337 @ifid@._d_@opname@ = (@inds@, @outds@, @excs@@options@)"""
338
339 objref_class = """\
340
341 # @ifid@ object reference
342 class _objref_@ifid@ (@inherits@):
343     _NP_RepositoryId = @ifid@._NP_RepositoryId
344
345     def __init__(self):"""
346
347 objref_inherit_init = """\
348         @inclass@.__init__(self)"""
349
350 objref_object_init = """\
351         CORBA.Object.__init__(self)"""
352
353 objref_attribute_get = """
354     def _get_@attr@(self, *args):
355         return _omnipy.invoke(self, "_get_@attr@", _0_@modname@.@ifid@._d__get_@attr@, args)"""
356 objref_attribute_set = """
357     def _set_@attr@(self, *args):
358         return _omnipy.invoke(self, "_set_@attr@", _0_@modname@.@ifid@._d__set_@attr@, args)"""
359 objref_operation = """
360     def @opname@(self, *args):
361         return _omnipy.invoke(self, "@r_opname@", _0_@modname@.@ifid@._d_@opname@, args)"""
362 objref_methods = """
363     __methods__ = @methods@"""
364
365 objref_register = """
366 omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
367 _0_@modname@._objref_@ifid@ = _objref_@ifid@
368 del @ifid@, _objref_@ifid@"""
369
370 skeleton_class = """
371 # @ifid@ skeleton
372 __name__ = "@package@@s_modname@"
373 class @ifid@ (@inherits@):
374     _NP_RepositoryId = _0_@modname@.@ifid@._NP_RepositoryId
375 """
376
377 skeleton_methodmap = """
378     _omni_op_d = @methodmap@"""
379
380 skeleton_inheritmap = """\
381     _omni_op_d.update(@inheritclass@._omni_op_d)"""
382
383 skeleton_end = """
384 @ifid@._omni_skeleton = @ifid@
385 _0_@s_modname@.@ifid@ = @ifid@
386 omniORB.registerSkeleton(@ifid@._NP_RepositoryId, @ifid@)
387 del @ifid@
388 __name__ = "@package@@modname@"\
389 """
390
391 skeleton_set_skel = """
392 @ifid@._omni_skeleton = @ifid@
393 """
394
395 constant_at_module_scope = """\
396 _0_@modname@.@cname@ = @value@"""
397
398 constant = """\
399 @cname@ = @value@"""
400
401 typedef_header = """\
402
403 # typedef ... @tdname@
404 class @tdname@:
405     _NP_RepositoryId = "@repoId@"
406     def __init__(self, *args, **kw):
407         raise RuntimeError("Cannot construct objects of this type.")"""
408
409 typedef_struct_union_header = """\
410
411 # typedef ... @tdname@
412 class @tdname@ (@parent@):
413     _NP_RepositoryId = "@repoId@"
414 """
415
416 typedef_fixed_header = """\
417 # typedef ... @tdname@
418 @tdname@ = omniORB.fixedConstructor("@repoId@", @digits@, @scale@)"""
419
420 typedef_at_module_scope = """\
421 _0_@modname@.@tdname@ = @tdname@
422 _0_@modname@._d_@tdname@  = @desc@
423 _0_@modname@._ad_@tdname@ = (omniORB.tcInternal.tv_alias, @tdname@._NP_RepositoryId, "@tdname@", @tddesc@)
424 _0_@modname@._tc_@tdname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._ad_@tdname@)
425 omniORB.registerType(@tdname@._NP_RepositoryId, _0_@modname@._ad_@tdname@, _0_@modname@._tc_@tdname@)
426 del @tdname@"""
427
428 typedef = """\
429 _d_@tdname@  = @desc@
430 _ad_@tdname@ = (omniORB.tcInternal.tv_alias, @tdname@._NP_RepositoryId, "@tdname@", @tddesc@)
431 _tc_@tdname@ = omniORB.tcInternal.createTypeCode(_ad_@tdname@)
432 omniORB.registerType(@tdname@._NP_RepositoryId, _ad_@tdname@, _tc_@tdname@)"""
433
434 forward_struct_descr_at_module_scope = """
435 # Forward struct @sname@
436 _0_@modname@._d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
437 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@sname@"""
438
439 forward_struct_descr = """
440 # Forward struct @sname@
441 _d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
442 omniORB.typeMapping["@repoId@"] = _d_@sname@"""
443
444 recursive_struct_descr_at_module_scope = """
445 # Recursive struct @sname@
446 _0_@modname@._d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
447 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@sname@"""
448
449 recursive_struct_descr = """
450 # Recursive struct @sname@
451 _d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
452 _0_@scope@._d_@sname@ = _d_@sname@
453 omniORB.typeMapping["@repoId@"] = _d_@sname@"""
454
455 struct_class = """
456 # struct @sname@
457 _0_@scopedname@ = omniORB.newEmptyClass()
458 class @sname@ (omniORB.StructBase):
459     _NP_RepositoryId = "@repoId@"
460 """
461
462 struct_class_name = """\
463     _NP_ClassName = "@cname@"
464 """
465
466 struct_class_init = """\
467     def __init__(self@mnames@):"""
468
469 struct_init_member = """\
470         self.@mname@ = @mname@"""
471
472 struct_descriptor_at_module_scope = """\
473
474 _0_@modname@.@sname@ = @sname@
475 _0_@modname@._d_@sname@  = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
476
477 struct_register_at_module_scope = """\
478 _0_@modname@._tc_@sname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@sname@)
479 omniORB.registerType(@sname@._NP_RepositoryId, _0_@modname@._d_@sname@, _0_@modname@._tc_@sname@)
480 del @sname@"""
481
482 struct_descriptor = """\
483
484 _d_@sname@  = _0_@scope@._d_@sname@ = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
485
486 struct_register = """\
487 _tc_@sname@ = omniORB.tcInternal.createTypeCode(_d_@sname@)
488 omniORB.registerType(@sname@._NP_RepositoryId, _d_@sname@, _tc_@sname@)"""
489
490 struct_module_descriptors = """
491 _0_@modname@._d_@sname@  = _d_@sname@
492 _0_@modname@._tc_@sname@ = _tc_@sname@
493 del @sname@, _d_@sname@, _tc_@sname@"""
494
495 exception_class = """\
496
497 # exception @sname@
498 _0_@scopedname@ = omniORB.newEmptyClass()
499 class @sname@ (CORBA.UserException):
500     _NP_RepositoryId = "@repoId@"
501 """
502
503 exception_class_init = """\
504     def __init__(self@mnames@):
505         CORBA.UserException.__init__(self@mnames@)"""
506
507 exception_init_member = """\
508         self.@mname@ = @mname@"""
509
510 exception_descriptor_at_module_scope = """\
511
512 _0_@modname@.@sname@ = @sname@
513 _0_@modname@._d_@sname@  = (omniORB.tcInternal.tv_except, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)
514 _0_@modname@._tc_@sname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@sname@)
515 omniORB.registerType(@sname@._NP_RepositoryId, _0_@modname@._d_@sname@, _0_@modname@._tc_@sname@)
516 del @sname@"""
517
518 exception_descriptor = """\
519
520 _d_@sname@  = (omniORB.tcInternal.tv_except, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)
521 _tc_@sname@ = omniORB.tcInternal.createTypeCode(_d_@sname@)
522 omniORB.registerType(@sname@._NP_RepositoryId, _d_@sname@, _tc_@sname@)"""
523
524 forward_union_descr_at_module_scope = """
525 # Forward union @uname@
526 _0_@modname@._d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
527 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@uname@"""
528
529 forward_union_descr = """
530 # Forward union @uname@
531 _d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
532 omniORB.typeMapping["@repoId@"] = _d_@uname@"""
533
534 recursive_union_descr_at_module_scope = """
535 # Recursive union @uname@
536 _0_@modname@._d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
537 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@uname@"""
538
539 recursive_union_descr = """
540 # Recursive union @uname@
541 _d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
542 _0_@scope@._d_@uname@ = _d_@uname@
543 omniORB.typeMapping["@repoId@"] = _d_@uname@"""
544
545 union_class = """
546 # union @uname@
547 _0_@scopedname@ = omniORB.newEmptyClass()
548 class @uname@ (omniORB.Union):
549     _NP_RepositoryId = "@repoId@"\
550 """
551
552 union_class_name = """\
553     _NP_ClassName = "@cname@"
554 """
555
556 union_descriptor_at_module_scope = """
557 _0_@modname@.@uname@ = @uname@
558
559 @uname@._m_to_d = {@m_to_d@}
560 @uname@._d_to_m = {@d_to_m@}
561 @uname@._def_m  = @def_m@
562 @uname@._def_d  = @def_d@
563
564 _0_@modname@._m_@uname@  = (@m_un@,)
565 _0_@modname@._d_@uname@  = (omniORB.tcInternal.tv_union, @uname@, @uname@._NP_RepositoryId, "@uname@", @stype@, @defpos@, _0_@modname@._m_@uname@, @m_def@, {@d_map@})"""
566
567 union_register_at_module_scope = """\
568 _0_@modname@._tc_@uname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@uname@)
569 omniORB.registerType(@uname@._NP_RepositoryId, _0_@modname@._d_@uname@, _0_@modname@._tc_@uname@)
570 del @uname@"""
571
572 union_descriptor = """
573 @uname@._m_to_d = {@m_to_d@}
574 @uname@._d_to_m = {@d_to_m@}
575 @uname@._def_m  = @def_m@
576 @uname@._def_d  = @def_d@
577
578 _m_@uname@  = (@m_un@,)
579 _d_@uname@  = _0_@scope@._d_@uname@ = (omniORB.tcInternal.tv_union, @uname@, @uname@._NP_RepositoryId, "@uname@", @stype@, @defpos@, _m_@uname@, @m_def@, {@d_map@})"""
580
581 union_register = """\
582 _tc_@uname@ = omniORB.tcInternal.createTypeCode(_d_@uname@)
583 omniORB.registerType(@uname@._NP_RepositoryId, _d_@uname@, _tc_@uname@)"""
584
585
586 enum_start = """
587 # enum @ename@\
588 """
589
590 enum_item_at_module_scope = """\
591 _0_@modname@.@eitem@ = omniORB.EnumItem("@item@", @eval@)"""
592
593 enum_object_and_descriptor_at_module_scope = """\
594 _0_@modname@.@ename@ = omniORB.Enum("@repoId@", (@eitems@,))
595
596 _0_@modname@._d_@ename@  = (omniORB.tcInternal.tv_enum, _0_@modname@.@ename@._NP_RepositoryId, "@ename@", _0_@modname@.@ename@._items)
597 _0_@modname@._tc_@ename@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@ename@)
598 omniORB.registerType(_0_@modname@.@ename@._NP_RepositoryId, _0_@modname@._d_@ename@, _0_@modname@._tc_@ename@)"""
599
600 enum_item = """\
601 @eitem@ = omniORB.EnumItem("@item@", @eval@)"""
602
603 enum_object_and_descriptor = """\
604 @ename@ = omniORB.Enum("@repoId@", (@eitems@,))
605
606 _d_@ename@  = (omniORB.tcInternal.tv_enum, @ename@._NP_RepositoryId, "@ename@", @ename@._items)
607 _tc_@ename@ = omniORB.tcInternal.createTypeCode(_d_@ename@)
608 omniORB.registerType(@ename@._NP_RepositoryId, _d_@ename@, _tc_@ename@)"""
609
610
611 value_forward_at_module_scope = """\
612 # forward valuetype @vname@
613 _0_@modname@._d_@vname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
614 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@vname@
615 """
616
617 value_class = """
618 # valuetype @vname@
619 _0_@modname@._d_@vname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
620 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@vname@
621 _0_@modname@.@vname@ = omniORB.newEmptyClass()
622
623 class @vname@ (@inherits@):
624     _NP_RepositoryId = "@repoId@"
625
626     def __init__(self, *args, **kwargs):
627         if args:
628             if len(args) != @arglen@:
629                 raise TypeError("@vname@() takes @arglen@ argument@s@ "
630                                 "(%d given)" % len(args))
631             @set_args@
632         if kwargs:
633             self.__dict__.update(kwargs)
634 """
635
636 valueabs_class = """\
637 class @vname@ (@inherits@):
638     _NP_RepositoryId = "@repoId@"
639
640     def __init__(self, *args, **kwargs):
641         raise RuntimeError("Cannot construct objects of this type.")
642 """
643
644 value_register_factory = """\
645 omniORB.registerValueFactory(@vname@._NP_RepositoryId, @vname@)
646 """
647
648 value_descriptor_at_module_scope = """\
649 _0_@modname@.@vname@ = @vname@
650 _0_@modname@._d_@vname@  = (omniORB.tcInternal.tv_value, @vname@, @vname@._NP_RepositoryId, "@vname@", @modifier@, @tbaseids@, @basedesc@, @mdescs@)
651 _0_@modname@._tc_@vname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@vname@)
652 omniORB.registerType(@vname@._NP_RepositoryId, _0_@modname@._d_@vname@, _0_@modname@._tc_@vname@)
653 del @vname@
654 """
655
656 value_objref_register = """
657 omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
658 _0_@modname@._objref_@ifid@ = _objref_@ifid@
659 del _objref_@ifid@"""
660
661
662 valuebox = """\
663
664 # valuebox @boxname@
665 class @boxname@:
666     _NP_RepositoryId = "@repoId@"
667     def __init__(self, *args, **kw):
668         raise RuntimeError("Cannot construct objects of this type.")
669
670 _0_@modname@.@boxname@ = @boxname@
671 _0_@modname@._d_@boxname@  = (omniORB.tcInternal.tv_value_box, @boxname@, @boxname@._NP_RepositoryId, "@boxname@", @boxdesc@)
672 _0_@modname@._tc_@boxname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@boxname@)
673 omniORB.registerType(@boxname@._NP_RepositoryId, _0_@modname@._d_@boxname@, _0_@modname@._tc_@boxname@)
674 omniORB.registerValueFactory(@boxname@._NP_RepositoryId, @boxname@)
675 del @boxname@
676 """
677
678
679 example_start = """\
680 #!/usr/bin/env python
681
682 # Python example implementations generated from @filename@
683
684 import CORBA, PortableServer
685
686 # Import the Python stub modules so type definitions are available.
687 """
688
689 example_import_skels = """
690 # Import the Python Skeleton modules so skeleton base classes are available.
691 """
692
693 example_import = """\
694 import @module@"""
695
696 example_classdef = """
697
698 # Implementation of interface @ccname@
699
700 class @ifname@_i (@skname@):
701 @inheritance_note@
702     def __init__(self):
703         # Initialise member variables here
704         pass
705 """
706
707 example_opdef = """\
708     # @signature@
709     def @opname@(self@args@):
710         raise CORBA.NO_IMPLEMENT(0, CORBA.COMPLETED_NO)
711         # *** Implement me
712         # Must return: @returnspec@
713 """
714
715 example_end = """
716 if __name__ == "__main__":
717     import sys
718     
719     # Initialise the ORB
720     orb = CORBA.ORB_init(sys.argv)
721     
722     # As an example, we activate an object in the Root POA
723     poa = orb.resolve_initial_references("RootPOA")
724
725     # Create an instance of a servant class
726     servant = @ifname@_i()
727
728     # Activate it in the Root POA
729     poa.activate_object(servant)
730
731     # Get the object reference to the object
732     objref = servant._this()
733     
734     # Print a stringified IOR for it
735     print orb.object_to_string(objref)
736
737     # Activate the Root POA's manager
738     poa._get_the_POAManager().activate()
739
740     # Run the ORB, blocking this thread
741     orb.run()
742 """
743
744
745 # Global state
746 imported_files   = {}
747 exported_modules = {}
748
749 # Command line options
750 output_inline    = 0
751 global_module    = "_GlobalIDL"
752 module_package   = ""
753 stub_package     = ""
754 stub_directory   = ""
755 all_factories    = 0
756 example_impl     = 0
757 extern_stub_pkgs = {}
758
759 def methgrp_index(metharr,opname):
760     for i in range(0, len(metharr)):
761         if len(opname) > 2 and metharr[i] == opname[:-2]:
762             return i
763
764     return -1
765
766 def ret_arg(p):
767     return "args["+str(p)+"]"
768
769 def is_int(p):
770     return "(type("+ret_arg(p)+") in [IntType, LongType])"
771
772 def is_boolean(p):
773     return "(type("+ret_arg(p)+") in [IntType, LongType, BooleanType])"
774
775 def is_double(p):
776     return "(type("+ret_arg(p)+") in [IntType, LongType, FloatType])"
777
778 def is_string(p):
779     return "(type("+ret_arg(p)+") in [StringType])"
780
781 def is_vtkPtr(p):
782     return "(type("+ret_arg(p)+") in [InstanceType])"
783
784 def is_list(p):
785     return "(type("+ret_arg(p)+").count('[]') > 0)"
786
787 def is_any(p):
788     return "(type("+ret_arg(p)+") in [CORBA.Any])"
789
790 def is_char(p):
791     return "((type("+ret_arg(p)+") in [StringType]) and (len(" + ret_arg(p) + ") == 1))"
792
793 def error_exit(message):
794     sys.stderr.write(main.cmdname + ": " + message + "\n")
795     sys.exit(1)
796
797 def run(tree, args):
798     global main_idl_file, imported_files, exported_modules, output_inline
799     global global_module, module_package, stub_package, stub_directory
800     global all_factories, example_impl, extern_stub_pkgs
801
802     imported_files.clear()
803     exported_modules.clear()
804
805     # Look at the args:
806     use_stdout     = 0
807     create_package = 1
808     for arg in args:
809
810         if arg == "stdout":
811             use_stdout     = 1
812             create_package = 0
813
814         elif arg == "no_package":
815             create_package = 0
816
817         elif arg == "inline":
818             output_inline = 1
819
820         elif arg == "factories":
821             all_factories = 1
822
823         elif arg[:8] == "modules=":
824             module_package = arg[8:]
825             if module_package != "":
826                 module_package = module_package + "."
827
828         elif arg[:6] == "stubs=":
829             stub_package   = arg[6:]
830             stub_directory = apply(os.path.join,
831                                    string.split(stub_package, "."))
832             if stub_package != "":
833                 stub_package = stub_package + "."
834
835         elif arg[:8] == "package=":
836             module_package = stub_package = arg[8:]
837             stub_directory = apply(os.path.join,
838                                    string.split(stub_package, "."))
839             if module_package != "":
840                 module_package = stub_package = module_package + "."
841
842         elif arg[:7] == "global=":
843             global_module = arg[7:]
844             if global_module == "":
845                 error_exit("You may not have an unnamed global module.")
846
847         elif arg == "example":
848             example_impl = 1
849
850         elif arg[:7] == "extern=":
851             f_p = string.split(arg[7:], ":", 1)
852             if len(f_p) == 1:
853                 extern_stub_pkgs[f_p[0]] = None
854             else:
855                 extern_stub_pkgs[f_p[0]] = f_p[1]
856
857         else:
858             sys.stderr.write(main.cmdname + ": Warning: Python " \
859                              "back-end does not understand argument: " + \
860                              arg + "\n")
861
862     main_idl_file = tree.file()
863
864     outpybasename = outputFileName(main_idl_file)
865     outpymodule   = stub_package + outpybasename
866     outpyname     = os.path.join(stub_directory, outpybasename + ".py")
867
868     imported_files[outpybasename] = 1
869
870     if create_package:
871         checkStubPackage(stub_package)
872
873     if use_stdout:
874         st = output.Stream(sys.stdout, 4)
875     else:
876         try:
877             st = output.Stream(open(outpyname, "w"), 4)
878         except IOError:
879             error_exit('Cannot open "%s" for writing.' % outpyname)
880
881     st.out(file_start, filename=main_idl_file)
882
883     pv = PythonVisitor(st, outpymodule)
884     tree.accept(pv)
885
886     dv = DocstringVisitor(st)
887     tree.accept(dv)
888     dv.output()
889
890     exports = exported_modules.keys()
891     exports.sort()
892     export_list = map(lambda s: '"' + module_package + s + '"', exports)
893     if len(export_list) == 1: export_list.append("")
894     export_string = string.join(export_list, ", ")
895
896     st.out(file_end, export_string=export_string)
897
898     if create_package:
899         updateModules(exports, outpymodule)
900
901     if example_impl:
902         implname = os.path.join(stub_directory, outpybasename + "_example.py")
903         exst = output.Stream(open(implname, "w"), 4)
904         exst.out(example_start, filename=main_idl_file)
905         for mod in exports:
906             exst.out(example_import, module=mod)
907         exst.out(example_import_skels)
908         for mod in exports:
909             exst.out(example_import, module=skeletonModuleName(mod))
910
911         ev = ExampleVisitor(exst)
912         tree.accept(ev)
913
914         exst.out(example_end, ifname=ev.first)
915
916
917 class PythonVisitor:
918     def __init__(self, st, outpymodule):
919         self.st          = st
920         self.outpymodule = outpymodule
921
922     def handleImported(self, node):
923         global imported_files
924
925         if node.mainFile() or output_inline:
926             return 0
927         else:
928             ifilename = outputFileName(node.file())
929             if not imported_files.has_key(ifilename):
930                 imported_files[ifilename] = 1
931                 ibasename,ext = os.path.splitext(os.path.basename(node.file()))
932                 if extern_stub_pkgs.has_key(ibasename):
933                     ipackage = extern_stub_pkgs[ibasename]
934                     if ipackage:
935                         fn = ipackage + '.' + ifilename
936                     else:
937                         fn = ifilename
938                 else:
939                     fn = stub_package + ifilename
940
941                 self.st.out(import_idl_file,
942                             idlfile=node.file(),
943                             ifilename=fn)
944             return 1
945         
946     #
947     # The global module
948     #
949     def visitAST(self, node):
950         self.at_module_scope = 1
951         self.at_global_scope = 1
952         self.currentScope    = ["_0_" + global_module]
953
954         decls_in_global_module = 0
955
956         for n in node.declarations():
957             if not isinstance(n, idlast.Module):
958                 decls_in_global_module = 1
959                 break
960
961         if decls_in_global_module:
962             self.modname = global_module
963             self.st.out(module_start,
964                         sname=global_module,
965                         s_sname=skeletonModuleName(global_module),
966                         filename=node.file(), package=module_package)
967         else:
968             self.modname = self.outpymodule
969
970         for n in node.declarations():
971             n.accept(self)
972
973         if decls_in_global_module:
974             exported_modules[global_module] = 1
975             self.st.out(module_end, modname=self.outpymodule,
976                         sname=global_module,
977                         package="")
978
979     #
980     # Module
981     #
982     def visitModule(self, node):
983         if self.handleImported(node):
984             imodname = dotName(node.scopedName())
985             ibasename,ext = os.path.splitext(os.path.basename(node.file()))
986
987             if extern_stub_pkgs.has_key(ibasename):
988                 package = extern_stub_pkgs[ibasename]
989                 if package is None:
990                     package = ""
991                 else:
992                     package = package + "."
993             else:
994                 package = module_package
995
996             self.st.out(open_imported_module_name,
997                         imodname=imodname,
998                         s_imodname=skeletonModuleName(imodname),
999                         package=package)
1000
1001         assert self.at_module_scope
1002
1003         sname = dotName(node.scopedName())
1004
1005         if node.mainFile() or output_inline:
1006             self.st.out(module_start,
1007                         sname = sname,
1008                         s_sname = skeletonModuleName(sname),
1009                         filename = node.file(), package=module_package)
1010
1011         parentmodname = self.modname
1012         self.modname  = dotName(node.scopedName())
1013
1014         ags = self.at_global_scope
1015         if ags:
1016             self.currentScope = ["_0_" + node.identifier()]
1017         else:
1018             self.currentScope.append(node.identifier())
1019
1020         self.at_global_scope = 0
1021
1022         for n in node.definitions():
1023             n.accept(self)
1024
1025         if ags:
1026             self.currentScope = ["_0_" + global_module]
1027         else:
1028             self.currentScope.pop()
1029         self.at_global_scope = ags
1030         self.modname         = parentmodname
1031
1032         if node.mainFile() or output_inline:
1033             exported_modules[sname] = 1
1034             self.st.out(module_end, modname=parentmodname, sname=sname,
1035                         package=module_package)
1036
1037     #
1038     # Forward interface
1039     #
1040     def visitForward(self, node):
1041         if self.handleImported(node): return
1042
1043         assert self.at_module_scope
1044         ifid   = mangle(node.identifier())
1045         repoId = node.repoId()
1046         if node.abstract():
1047             tvkind = "tv_abstract_interface"
1048             abstract = "abstract "
1049         else:
1050             tvkind = "tv_objref"
1051             abstract = ""
1052
1053         self.st.out(forward_interface, ifid=ifid, tvkind=tvkind,
1054                     repoId=repoId, abstract=abstract, modname=self.modname)
1055
1056     #
1057     # Interface
1058     #
1059     def visitInterface(self, node):
1060         if self.handleImported(node): return
1061
1062         assert self.at_module_scope
1063         ifid = mangle(node.identifier())
1064
1065         if len(node.inherits()) > 0:
1066             inheritl = []
1067             for i in node.inherits():
1068                 i = i.fullDecl()
1069                 inheritl.append(dotName(fixupScopedName(i.scopedName())))
1070             
1071             inherits = "(" + string.join(inheritl, ", ") + ")"
1072         else:
1073             inherits = ""
1074
1075         if node.abstract():
1076             tvkind = "tv_abstract_interface"
1077             abstract = "abstract "
1078         else:
1079             tvkind = "tv_objref"
1080             abstract = ""
1081
1082         # Class header
1083         self.st.out(interface_class, ifid=ifid, tvkind=tvkind,
1084                     inherits=inherits, repoId=node.repoId(),
1085                     abstract=abstract, modname=self.modname)
1086
1087         # Declarations within the interface
1088         if len(node.declarations()) > 0:
1089             self.st.inc_indent()
1090             self.at_module_scope = 0
1091             self.currentScope.append(node.identifier())
1092
1093             for d in node.declarations():
1094                 d.accept(self)
1095
1096             self.currentScope.pop()
1097             self.at_module_scope = 1
1098             self.st.dec_indent()
1099             self.st.out("")
1100
1101         # Descriptor and TypeCode for the interface
1102         self.st.out(interface_descriptor,
1103                     modname = self.modname, ifid = ifid)
1104
1105         # Attributes and operations
1106         # *** Was there a good reason for putting these in the class def?
1107         if len(node.callables()) > 0:
1108             self.st.out(callables_header, ifid=ifid)
1109
1110         for c in node.callables():
1111             if isinstance(c, idlast.Attribute):
1112
1113                 descr = typeToDescriptor(c.attrType())
1114
1115                 for attr in c.identifiers():
1116
1117                     self.st.out(attribute_get_descriptor,
1118                                 attr=attr, descr=descr, ifid=ifid)
1119
1120                     if not c.readonly():
1121
1122                         self.st.out(attribute_set_descriptor,
1123                                     attr=attr, descr=descr, ifid=ifid)
1124             else: # Operation
1125
1126                 inds, outds, excs, ctxts, cv = operationToDescriptors(c)
1127
1128                 options = ""
1129
1130                 if cv:
1131                     ctxts = ctxts or "None"
1132
1133                 if ctxts:
1134                     options = ", " + ctxts
1135
1136                 if cv:
1137                     options = options + ", 1"
1138
1139                 # Output the declaration
1140                 self.st.out(operation_descriptor,
1141                             opname  = mangle(c.identifier()),
1142                             inds    = inds,
1143                             outds   = outds,
1144                             excs    = excs,
1145                             options = options,
1146                             ifid    = ifid)
1147
1148         # Objref class
1149         if node.inherits():
1150             inheritl = []
1151             for i in node.inherits():
1152                 i = i.fullDecl()
1153                 sn = fixupScopedName(i.scopedName())
1154                 inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
1155                 
1156             inherits = string.join(inheritl, ", ")
1157         else:
1158             inherits = "CORBA.Object"
1159
1160         self.st.out(objref_class, ifid=ifid, inherits=inherits)
1161
1162         if node.inherits():
1163             for inclass in inheritl:
1164                 self.st.out(objref_inherit_init, inclass=inclass)
1165         else:
1166             self.st.out(objref_object_init)
1167
1168         # Operations and attributes
1169         methodl = []
1170         methadd = []
1171         methdsc = []
1172
1173         for c in node.callables():
1174
1175             if isinstance(c, idlast.Attribute):
1176
1177                 for attr in c.identifiers():
1178
1179                     self.st.out(objref_attribute_get,
1180                                 attr    = attr,
1181                                 ifid    = ifid,
1182                                 modname = self.modname)
1183                     
1184                     methodl.append('"_get_' + attr + '"')
1185
1186                     if not c.readonly():
1187
1188                         self.st.out(objref_attribute_set,
1189                                     attr    = attr,
1190                                     ifid    = ifid,
1191                                     modname = self.modname)
1192                         
1193                         methodl.append('"_set_' + attr + '"')
1194
1195             else: # Operation
1196                 opname = mangle(c.identifier())
1197                 
1198                 if len(opname) > 2 and opname[-2] == '_':
1199                     methlen = methgrp_index(methadd,opname)
1200                     if methlen < 0:
1201                         methodl.append('"' + opname[:-2] + '"')
1202
1203                         methlen = len(methadd)
1204
1205                         methadd = methadd + [opname[:-2]]
1206
1207                         methdsc = methdsc + [""]
1208                         methdsc[methlen] = "\n    def "+opname[:-2]+"(self, *args):"
1209
1210                     methdsc[methlen] = methdsc[methlen] + "\n        "
1211                         
1212                     methdsc[methlen] = methdsc[methlen] + "if len(args) == " + str(len(c.parameters()))
1213
1214                     for p in range(0,len(c.parameters())):
1215                         methdsc[methlen] = methdsc[methlen] + " and "
1216                         if c.parameters()[p].paramType().kind() in [idltype.tk_short,idltype.tk_long]:
1217                             methdsc[methlen] = methdsc[methlen] + is_int(p)
1218                         if c.parameters()[p].paramType().kind() in [idltype.tk_float,idltype.tk_double]:
1219                             methdsc[methlen] = methdsc[methlen] + is_double(p)
1220                         if c.parameters()[p].paramType().kind() in [idltype.tk_string]:
1221                             methdsc[methlen] = methdsc[methlen] + is_string(p)
1222                         if c.parameters()[p].paramType().kind() in [idltype.tk_sequence,idltype.tk_alias]:
1223                             methdsc[methlen] = methdsc[methlen] + is_list(p)
1224                         if c.parameters()[p].paramType().kind() in [idltype.tk_objref]:
1225                             methdsc[methlen] = methdsc[methlen] + is_vtkPtr(p)
1226                         if c.parameters()[p].paramType().kind() in [idltype.tk_boolean]:
1227                             methdsc[methlen] = methdsc[methlen] + is_boolean(p)
1228                         if c.parameters()[p].paramType().kind() in [idltype.tk_any]:
1229                             methdsc[methlen] = methdsc[methlen] + is_any(p)
1230                         if c.parameters()[p].paramType().kind() in [idltype.tk_char]:
1231                             methdsc[methlen] = methdsc[methlen] + is_char(p)
1232                         if c.parameters()[p].paramType().kind() not in [idltype.tk_boolean,idltype.tk_short,idltype.tk_long,idltype.tk_float,idltype.tk_double,idltype.tk_string,idltype.tk_sequence,idltype.tk_alias,idltype.tk_objref,idltype.tk_any,idltype.tk_char]:
1233                             methdsc[methlen] = methdsc[methlen] + " " + str(c.parameters()[p].paramType().kind()) + " == '' "
1234
1235                     methdsc[methlen] = methdsc[methlen] + ":"
1236                     methdsc[methlen] = methdsc[methlen] + "\n            return self."+opname+"(*args)"
1237
1238                 self.st.out(objref_operation,
1239                             opname   = opname,
1240                             r_opname = c.identifier(),
1241                             ifid     = ifid,
1242                             modname  = self.modname)
1243                 methodl.append('"' + opname + '"')
1244
1245         for p in range(0,len(methadd)):
1246             methgrp = methadd[p]
1247             methtmp = methdsc[p]
1248             methtmp = methtmp + "\n        print 'Warning: The corresponding method of " + methgrp + " group is not found for ' + str(args)"
1249             self.st.out(methtmp)
1250
1251         #self.st.out("\n    def __eq__(self,other):")
1252         #self.st.out("        return self.IsSame(other)==0")
1253
1254         # __methods__ assignment
1255         methods = "[" + string.join(methodl, ", ") + "]"
1256
1257         if node.inherits():
1258             inheritl = []
1259             for i in node.inherits():
1260                 i = i.fullDecl()
1261                 sn = fixupScopedName(i.scopedName())
1262                 methods = methods + " + " + \
1263                           dotName(sn[:-1] + ["_objref_" + sn[-1]]) + \
1264                           ".__methods__"
1265         else:
1266             methods = methods + " + CORBA.Object.__methods__"
1267
1268         self.st.out(objref_methods, methods = methods)
1269
1270         # registerObjRef()
1271         self.st.out(objref_register, ifid = ifid, modname = self.modname)
1272
1273         # Skeleton class
1274         if node.inherits():
1275             inheritl = []
1276             for i in node.inherits():
1277                 i = i.fullDecl()
1278                 fsn = fixupScopedName(i.scopedName())
1279                 dsn = dotName(fsn)
1280                 ssn = skeletonModuleName(dsn)
1281                 inheritl.append(ssn)
1282                 
1283             inherits = string.join(inheritl, ", ")
1284         else:
1285             inherits = "PortableServer.Servant"
1286
1287         self.st.out(skeleton_class,
1288                     ifid      = ifid,
1289                     inherits  = inherits,
1290                     modname   = self.modname,
1291                     s_modname = skeletonModuleName(self.modname),
1292                     package   = module_package)
1293
1294         # Operations and attributes
1295         methodl = []
1296
1297         for c in node.callables():
1298             if isinstance(c, idlast.Attribute):
1299
1300                 for attr in c.identifiers():
1301
1302                     methodl.append('"_get_' + attr + '": ' + \
1303                                    '_0_' + self.modname + '.' + \
1304                                    ifid + '.' + '_d__get_' + attr)
1305
1306                     if not c.readonly():
1307
1308                         methodl.append('"_set_' + attr + '": ' + \
1309                                        '_0_' + self.modname + '.' + \
1310                                        ifid + '.' + '_d__set_' + attr)
1311
1312             else: # Operation
1313                 opname = mangle(c.identifier())
1314                 
1315                 methodl.append('"' + opname + '": ' + '_0_' + self.modname + \
1316                                '.' + ifid + '.' + '_d_' + opname)
1317
1318         methodmap = "{" + string.join(methodl, ", ") + "}"
1319
1320         self.st.out(skeleton_methodmap, methodmap = methodmap)
1321
1322         if node.inherits():
1323             for inheritclass in inheritl:
1324                 self.st.out(skeleton_inheritmap, inheritclass = inheritclass)
1325
1326         self.st.out(skeleton_end,
1327                     ifid      = ifid,
1328                     modname   = self.modname,
1329                     s_modname = skeletonModuleName(self.modname),
1330                     package   = module_package)
1331
1332     #
1333     # Constant
1334     #
1335     def visitConst(self, node):
1336         if self.handleImported(node): return
1337
1338         cname = mangle(node.identifier())
1339
1340         if self.at_module_scope:
1341             value = valueToString(node.value(), node.constKind(), [])
1342         else:
1343             value = valueToString(node.value(), node.constKind(),
1344                                   self.currentScope)
1345         if self.at_module_scope:
1346             self.st.out(constant_at_module_scope,
1347                         cname   = cname,
1348                         value   = value,
1349                         modname = self.modname)
1350         else:
1351             self.st.out(constant,
1352                         cname   = cname,
1353                         value   = value)
1354
1355     #
1356     # Typedef
1357     #
1358     def visitTypedef(self, node):
1359         if self.handleImported(node): return
1360
1361         if node.constrType():
1362             node.aliasType().decl().accept(self)
1363
1364         for decl in node.declarators():
1365             tdname = mangle(decl.identifier())
1366             if self.at_module_scope:
1367                 desc   = typeAndDeclaratorToDescriptor(node.aliasType(),
1368                                                        decl, [])
1369                 tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
1370                                                        decl, [], 1)
1371
1372                 unaliased_type = node.aliasType().unalias()
1373
1374                 if len(decl.sizes()) == 0 and \
1375                    unaliased_type.kind() in [idltype.tk_struct,
1376                                              idltype.tk_union]:
1377
1378                     parent = dotName(fixupScopedName(unaliased_type.decl().\
1379                                                      scopedName()))
1380
1381                     self.st.out(typedef_struct_union_header,
1382                                 tdname = tdname,
1383                                 repoId = decl.repoId(),
1384                                 parent = parent)
1385
1386                 elif len(decl.sizes()) == 0 and\
1387                      unaliased_type.kind() == idltype.tk_fixed:
1388
1389                     self.st.out(typedef_fixed_header,
1390                                 tdname = tdname,
1391                                 repoId = decl.repoId(),
1392                                 digits = unaliased_type.digits(),
1393                                 scale  = unaliased_type.scale())
1394                     
1395                 else:
1396                     self.st.out(typedef_header,
1397                                 tdname  = tdname,
1398                                 repoId  = decl.repoId())
1399
1400                 self.st.out(typedef_at_module_scope,
1401                             tdname  = tdname,
1402                             desc    = desc,
1403                             tddesc  = tddesc,
1404                             modname = self.modname)
1405             else:
1406                 desc   = typeAndDeclaratorToDescriptor(node.aliasType(),
1407                                                        decl,
1408                                                        self.currentScope)
1409                 tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
1410                                                        decl,
1411                                                        self.currentScope, 1)
1412
1413                 unaliased_type = node.aliasType().unalias()
1414
1415                 if len(decl.sizes()) == 0 and \
1416                    unaliased_type.kind() in [idltype.tk_struct,
1417                                              idltype.tk_union]:
1418
1419                     psname  = unaliased_type.decl().scopedName()
1420                     myscope = decl.scopedName()[:-1]
1421
1422                     # If the struct/union definition is in the same
1423                     # scope as the typedef, we must use a relative
1424                     # name to refer to the parent class, since the
1425                     # enclosing Python class has not yet been fully
1426                     # defined.
1427
1428                     if psname[:len(myscope)] == myscope:
1429                         parent = dotName(psname[len(myscope):])
1430                     else:
1431                         parent = dotName(fixupScopedName(psname))
1432
1433                     self.st.out(typedef_struct_union_header,
1434                                 tdname = tdname,
1435                                 repoId = decl.repoId(),
1436                                 parent = parent)
1437                 else:
1438                     self.st.out(typedef_header,
1439                                 tdname  = tdname,
1440                                 repoId  = decl.repoId())
1441
1442                 self.st.out(typedef,
1443                             tdname  = tdname,
1444                             desc    = desc,
1445                             tddesc  = tddesc)
1446     #
1447     # Struct
1448     #
1449     def visitStruct(self, node):
1450         if self.handleImported(node): return
1451
1452         sname = mangle(node.identifier())
1453
1454         fscopedName = fixupScopedName(node.scopedName(), "")
1455
1456         if node.recursive():
1457             if self.at_module_scope:
1458                 self.st.out(recursive_struct_descr_at_module_scope,
1459                             sname   = sname,
1460                             repoId  = node.repoId(),
1461                             modname = self.modname)
1462             else:
1463                 self.st.out(recursive_struct_descr,
1464                             sname   = sname,
1465                             repoId  = node.repoId(),
1466                             scope   = dotName(fscopedName[:-1]))
1467
1468         self.st.out(struct_class,
1469                     sname      = sname,
1470                     repoId     = node.repoId(),
1471                     scopedname = dotName(fscopedName))
1472
1473         if not self.at_module_scope:
1474             self.st.out(struct_class_name, cname = dotName(fscopedName))
1475
1476         mnamel = []
1477         mdescl = []
1478         for mem in node.members():
1479
1480             # Deal with nested declarations
1481             if mem.constrType():
1482                 self.st.inc_indent()
1483                 ams = self.at_module_scope
1484                 self.at_module_scope = 0
1485                 self.currentScope.append(node.identifier())
1486                 
1487                 mem.memberType().decl().accept(self)
1488
1489                 self.currentScope.pop()
1490                 self.at_module_scope = ams
1491                 self.st.dec_indent()
1492                 self.st.out("")
1493
1494             for decl in mem.declarators():
1495                 mnamel.append(mangle(decl.identifier()))
1496                 mdescl.append('"' + mangle(decl.identifier()) + '"')
1497                 
1498                 if self.at_module_scope:
1499                     mdescl.append(\
1500                         typeAndDeclaratorToDescriptor(mem.memberType(),
1501                                                       decl,
1502                                                       []))
1503                 else:
1504                     mdescl.append(\
1505                         typeAndDeclaratorToDescriptor(mem.memberType(),
1506                                                       decl,
1507                                                       self.currentScope))
1508         if len(mnamel) > 0:
1509             mnames = ", " + string.join(mnamel, ", ")
1510
1511             self.st.out(struct_class_init, mnames = mnames)
1512
1513             for mname in mnamel:
1514                 self.st.out(struct_init_member, mname = mname)
1515
1516         if len(mdescl) > 0:
1517             mdescs = ", " + string.join(mdescl, ", ")
1518         else:
1519             mdescs = ""
1520
1521         if self.at_module_scope:
1522             self.st.out(struct_descriptor_at_module_scope,
1523                         sname   = sname,
1524                         mdescs  = mdescs,
1525                         modname = self.modname)
1526             
1527             self.st.out(struct_register_at_module_scope,
1528                         sname   = sname,
1529                         modname = self.modname)
1530         else:
1531             self.st.out(struct_descriptor,
1532                         sname  = sname,
1533                         mdescs = mdescs,
1534                         scope  = dotName(fscopedName[:-1]))
1535
1536             self.st.out(struct_register, sname = sname)
1537
1538     #
1539     # Forward struct
1540     #
1541     def visitStructForward(self, node):
1542         if self.handleImported(node): return
1543
1544         sname = mangle(node.identifier())
1545
1546         if self.at_module_scope:
1547             self.st.out(forward_struct_descr_at_module_scope,
1548                         sname   = sname,
1549                         repoId  = node.repoId(),
1550                         modname = self.modname)
1551         else:
1552             self.st.out(forward_struct_descr,
1553                         sname   = sname,
1554                         repoId  = node.repoId(),
1555                         modname = self.modname)
1556
1557     #
1558     # Exception
1559     #
1560     def visitException(self, node):
1561         if self.handleImported(node): return
1562
1563         sname = mangle(node.identifier())
1564         fscopedName = fixupScopedName(node.scopedName(), "")
1565         self.st.out(exception_class,
1566                     sname = sname,
1567                     repoId = node.repoId(),
1568                     scopedname = dotName(fscopedName))
1569
1570         if not self.at_module_scope:
1571             self.st.out(struct_class_name, cname = dotName(fscopedName))
1572
1573         mnamel = []
1574         mdescl = []
1575         for mem in node.members():
1576
1577             # Deal with nested declarations
1578             if mem.constrType():
1579                 self.st.inc_indent()
1580                 ams = self.at_module_scope
1581                 self.at_module_scope = 0
1582                 self.currentScope.append(node.identifier())
1583                 
1584                 mem.memberType().decl().accept(self)
1585
1586                 self.currentScope.pop()
1587                 self.at_module_scope = ams
1588                 self.st.dec_indent()
1589                 self.st.out("")
1590
1591             for decl in mem.declarators():
1592                 mnamel.append(mangle(decl.identifier()))
1593                 mdescl.append('"' + mangle(decl.identifier()) + '"')
1594
1595                 if self.at_module_scope:
1596                     mdescl.append(\
1597                         typeAndDeclaratorToDescriptor(mem.memberType(),
1598                                                       decl,
1599                                                       []))
1600                 else:
1601                     mdescl.append(\
1602                         typeAndDeclaratorToDescriptor(mem.memberType(),
1603                                                       decl,
1604                                                       self.currentScope))
1605
1606         if len(mnamel) > 0:
1607             mnames = ", " + string.join(mnamel, ", ")
1608         else:
1609             mnames = ""
1610
1611         self.st.out(exception_class_init, mnames = mnames)
1612
1613         for mname in mnamel:
1614             self.st.out(exception_init_member, mname = mname)
1615
1616         if len(mdescl) > 0:
1617             mdescs = ", " + string.join(mdescl, ", ")
1618         else:
1619             mdescs = ""
1620
1621         if self.at_module_scope:
1622             self.st.out(exception_descriptor_at_module_scope,
1623                         sname = sname, mdescs = mdescs, modname = self.modname)
1624         else:
1625             self.st.out(exception_descriptor, sname = sname, mdescs = mdescs)
1626
1627     #
1628     # Union
1629     #
1630     def visitUnion(self, node):
1631         if self.handleImported(node): return
1632
1633         uname = mangle(node.identifier())
1634         if self.at_module_scope:
1635             stype = typeToDescriptor(node.switchType(), [])
1636         else:
1637             stype = typeToDescriptor(node.switchType(), self.currentScope)
1638
1639         fscopedName = fixupScopedName(node.scopedName(), "")
1640         
1641         if node.recursive():
1642             if self.at_module_scope:
1643                 self.st.out(recursive_union_descr_at_module_scope,
1644                             uname   = uname,
1645                             repoId  = node.repoId(),
1646                             modname = self.modname)
1647             else:
1648                 self.st.out(recursive_union_descr,
1649                             uname   = uname,
1650                             repoId  = node.repoId(),
1651                             scope   = dotName(fscopedName[:-1]))
1652
1653         self.st.out(union_class,
1654                     uname      = uname,
1655                     repoId     = node.repoId(),
1656                     scopedname = dotName(fscopedName))
1657
1658         if not self.at_module_scope:
1659             self.st.out(union_class_name, cname = dotName(fscopedName))
1660
1661         if node.constrType():
1662             self.st.inc_indent()
1663             ams = self.at_module_scope
1664             self.at_module_scope = 0
1665             self.currentScope.append(node.identifier())
1666             
1667             node.switchType().decl().accept(self)
1668
1669             self.currentScope.pop()
1670             self.at_module_scope = ams
1671             self.st.dec_indent()
1672
1673         def_m    = "None"
1674         def_d    = "None"
1675         m_def    = "None"
1676         defpos   = "-1"
1677         m_to_d_l = []
1678         d_to_m_l = []
1679         m_un_l   = []
1680         d_map_l  = []
1681
1682         i = 0
1683         for case in node.cases():
1684
1685             # Deal with nested declarations
1686             if case.constrType():
1687                 self.st.inc_indent()
1688                 ams = self.at_module_scope
1689                 self.at_module_scope = 0
1690                 self.currentScope.append(node.identifier())
1691                 
1692                 case.caseType().decl().accept(self)
1693
1694                 self.currentScope.pop()
1695                 self.at_module_scope = ams
1696                 self.st.dec_indent()
1697                 self.st.out("")
1698
1699             if self.at_module_scope:
1700                 ctype = typeAndDeclaratorToDescriptor(case.caseType(),
1701                                                       case.declarator(),
1702                                                       [])
1703             else:
1704                 ctype = typeAndDeclaratorToDescriptor(case.caseType(),
1705                                                       case.declarator(),
1706                                                       self.currentScope)
1707
1708             cname = mangle(case.declarator().identifier())
1709
1710             for label in case.labels():
1711                 if label.default():
1712                     def_m  = '"' + cname + '"'
1713                     defpos = str(i)
1714                     if self.at_module_scope:
1715                         def_d  = valueToString(label.value(),
1716                                                label.labelKind(), [])
1717                         m_def  = "_0_" + self.modname + "._m_" + uname + \
1718                                  "[" + defpos + "]"
1719                     else:
1720                         def_d  = valueToString(label.value(),
1721                                                label.labelKind(),
1722                                                self.currentScope)
1723                         m_def  = "_m_" + uname + "[" + defpos + "]"
1724
1725                     m_un_l.append('(' + def_d + ', "' + cname + '", ' +\
1726                                   ctype + ')')
1727                 else:
1728                     if self.at_module_scope:
1729                         slabel = valueToString(label.value(),
1730                                                label.labelKind(), [])
1731                     else:
1732                         slabel = valueToString(label.value(),
1733                                                label.labelKind(),
1734                                                self.currentScope)
1735
1736                     m_to_d_l.append('"' + cname + '": ' + slabel)
1737                     d_to_m_l.append(slabel + ': "' + cname + '"')
1738
1739                     m_un_l.append('(' + slabel + ', "' + cname + '", ' +\
1740                                   ctype + ')')
1741
1742                     if self.at_module_scope:
1743                         d_map_l.append(slabel + ': ' + '_0_' + self.modname + \
1744                                        "._m_" + uname + "[" + str(i) + "]")
1745                     else:
1746                         d_map_l.append(slabel + ': ' + "_m_" + \
1747                                        uname + "[" + str(i) + "]")
1748                 i = i + 1
1749
1750         m_to_d = string.join(m_to_d_l, ", ")
1751         d_to_m = string.join(d_to_m_l, ", ")
1752         m_un   = string.join(m_un_l,   ", ")
1753         d_map  = string.join(d_map_l,  ", ")
1754
1755         if self.at_module_scope:
1756             self.st.out(union_descriptor_at_module_scope,
1757                         uname   = uname,
1758                         m_to_d  = m_to_d,
1759                         d_to_m  = d_to_m,
1760                         def_m   = def_m,
1761                         def_d   = def_d,
1762                         m_un    = m_un,
1763                         stype   = stype,
1764                         defpos  = defpos,
1765                         m_def   = m_def,
1766                         d_map   = d_map,
1767                         modname = self.modname)
1768             
1769             self.st.out(union_register_at_module_scope,
1770                         uname   = uname,
1771                         modname = self.modname)
1772         else:
1773             self.st.out(union_descriptor,
1774                         uname   = uname,
1775                         m_to_d  = m_to_d,
1776                         d_to_m  = d_to_m,
1777                         def_m   = def_m,
1778                         def_d   = def_d,
1779                         m_un    = m_un,
1780                         stype   = stype,
1781                         defpos  = defpos,
1782                         m_def   = m_def,
1783                         d_map   = d_map,
1784                         scope   = dotName(fscopedName[:-1]))
1785             
1786             self.st.out(union_register, uname = uname)
1787
1788     #
1789     # Forward union
1790     #
1791     def visitUnionForward(self, node):
1792         if self.handleImported(node): return
1793
1794         uname = mangle(node.identifier())
1795
1796         if self.at_module_scope:
1797             self.st.out(forward_union_descr_at_module_scope,
1798                         uname   = uname,
1799                         repoId  = node.repoId(),
1800                         modname = self.modname)
1801         else:
1802             self.st.out(forward_union_descr,
1803                         uname   = uname,
1804                         repoId  = node.repoId(),
1805                         modname = self.modname)
1806
1807     #
1808     # Enum
1809     #
1810     def visitEnum(self, node):
1811         if self.handleImported(node): return
1812
1813         ename = mangle(node.identifier())
1814         self.st.out(enum_start, ename = ename)
1815
1816         i=0
1817         elist = []
1818         for item in node.enumerators():
1819             eval = str(i)
1820
1821             if self.at_module_scope:
1822                 self.st.out(enum_item_at_module_scope,
1823                             item    = item.identifier(),
1824                             eitem   = mangle(item.identifier()),
1825                             eval    = eval,
1826                             modname = self.modname)
1827             else:
1828                 self.st.out(enum_item,
1829                             item    = item.identifier(),
1830                             eitem   = mangle(item.identifier()),
1831                             eval    = eval)
1832
1833             if self.at_module_scope:
1834                 elist.append(dotName(fixupScopedName(item.scopedName())))
1835             else:
1836                 elist.append(mangle(item.identifier()))
1837
1838             i = i + 1
1839
1840         eitems = string.join(elist, ", ")
1841
1842         if self.at_module_scope:
1843             self.st.out(enum_object_and_descriptor_at_module_scope,
1844                         ename   = ename,
1845                         repoId  = node.repoId(),
1846                         eitems  = eitems,
1847                         modname = self.modname)
1848         else:
1849             self.st.out(enum_object_and_descriptor,
1850                         ename   = ename,
1851                         repoId  = node.repoId(),
1852                         eitems  = eitems)
1853
1854     def visitNative(self, node):
1855         if self.handleImported(node): return
1856
1857         sys.stderr.write(main.cmdname + \
1858                          ": Warning: ignoring declaration of native " + \
1859                          node.identifier() + "\n")
1860
1861     def visitValueForward(self, node):
1862         if self.handleImported(node): return
1863
1864         vname = mangle(node.identifier())
1865
1866         self.st.out(value_forward_at_module_scope,
1867                     vname=vname, repoId=node.repoId(), modname=self.modname)
1868
1869
1870     def visitValueBox(self, node):
1871         if self.handleImported(node): return
1872
1873         boxname = mangle(node.identifier())
1874         boxdesc = typeToDescriptor(node.boxedType())
1875
1876         self.st.out(valuebox, boxname=boxname, repoId=node.repoId(),
1877                     boxdesc=boxdesc, modname=self.modname)
1878
1879
1880     def visitValueAbs(self, node):
1881         if self.handleImported(node): return
1882
1883         vname = mangle(node.identifier())
1884
1885         fscopedName = fixupScopedName(node.scopedName(), "")
1886         scopedname  = dotName(fscopedName)
1887
1888         if node.inherits():
1889             inheritl = []
1890             for i in node.inherits():
1891                 i = i.fullDecl()
1892                 inheritl.append(dotName(fixupScopedName(i.scopedName())))
1893             
1894             inherits = string.join(inheritl, ", ")
1895         else:
1896             inherits = "_0_CORBA.ValueBase"
1897
1898         self.st.out(valueabs_class,
1899                     vname=vname, scopedname=scopedname, repoId=node.repoId(),
1900                     inherits=inherits, modname=self.modname)
1901
1902         # Declarations within the value
1903         if len(node.declarations()) > 0:
1904             self.st.inc_indent()
1905             self.at_module_scope = 0
1906             self.currentScope.append(node.identifier())
1907
1908             for d in node.declarations():
1909                 d.accept(self)
1910
1911             self.currentScope.pop()
1912             self.at_module_scope = 1
1913             self.st.dec_indent()
1914             self.st.out("")
1915
1916         basedesc = "_0_CORBA.tcInternal.tv_null"
1917
1918         self.st.out(value_descriptor_at_module_scope,
1919                     vname=vname, modifier="_0_CORBA.VM_ABSTRACT",
1920                     tbaseids="None", basedesc=basedesc, mdescs="",
1921                     modname=self.modname)
1922
1923
1924     def visitValue(self, node):
1925         if self.handleImported(node): return
1926
1927         vname = mangle(node.identifier())
1928
1929         fscopedName = fixupScopedName(node.scopedName(), "")
1930         scopedname  = dotName(fscopedName)
1931
1932         if node.inherits():
1933             inheritl = []
1934             for i in node.inherits():
1935                 i = i.fullDecl()
1936                 inheritl.append(dotName(fixupScopedName(i.scopedName())))
1937             
1938         else:
1939             inheritl = ["_0_CORBA.ValueBase"]
1940
1941         skeleton_opl = []
1942         for i in node.supports():
1943             i = i.fullDecl()
1944             sn = fixupScopedName(i.scopedName())
1945             sn[0] = sn[0] + "__POA"
1946             dn = dotName(sn)
1947             inheritl.append(dn)
1948             skeleton_opl.append(dn)
1949
1950         inherits = string.join(inheritl, ", ")
1951
1952         # Go up the chain of inherited interfaces, picking out the
1953         # state members
1954         members = []
1955         ilist   = []
1956         cnode   = node
1957         
1958         while 1:
1959             cin = cnode.inherits()
1960             if not cin:
1961                 break
1962             i = cin[0].fullDecl()
1963             if not isinstance(i, idlast.Value):
1964                 break
1965             ilist.append(i)
1966             cnode = i
1967
1968         ilist.reverse()
1969         ilist.append(node)
1970         
1971         for i in ilist:
1972             members.extend(i.statemembers())
1973
1974         set_argl = []
1975
1976         for i in range(len(members)):
1977             member = members[i]
1978             for d in member.declarators():
1979                 set_argl.append("self.%s = args[%d]" %
1980                                 (mangle(d.identifier()),i))
1981
1982         if set_argl:
1983             set_args = string.join(set_argl, "\n")
1984         else:
1985             set_args = "pass"
1986
1987         if len(set_argl) == 1:
1988             s = ""
1989         else:
1990             s = "s"
1991
1992         self.st.out(value_class,
1993                     vname=vname, scopedname=scopedname, repoId=node.repoId(),
1994                     inherits=inherits, set_args=set_args, arglen=len(set_argl),
1995                     s=s, modname=self.modname)
1996
1997         # Declarations within the value
1998         if len(node.declarations()) > 0:
1999             self.st.inc_indent()
2000             self.at_module_scope = 0
2001             self.currentScope.append(node.identifier())
2002
2003             for d in node.declarations():
2004                 d.accept(self)
2005
2006             self.currentScope.pop()
2007             self.at_module_scope = 1
2008             self.st.dec_indent()
2009             self.st.out("")
2010
2011         # Skeleton operation declarations if necessary
2012         if node.supports():
2013             self.st.out(skeleton_methodmap, methodmap="{}")
2014             for i in skeleton_opl:
2015                 self.st.out(skeleton_inheritmap, inheritclass=i)
2016
2017             self.st.out(skeleton_set_skel, ifid=vname)
2018
2019         # Register factory if no callables or factories
2020         register_factory = 1
2021
2022         if not all_factories:
2023             cnode = node
2024             while 1:
2025                 if cnode.callables() or cnode.factories() or cnode.supports():
2026                     register_factory = 0
2027                     break
2028                 cin = cnode.inherits()
2029                 if not cin:
2030                     break
2031                 for n in cin:
2032                     n = n.fullDecl()
2033                     if not isinstance(n, idlast.Value):
2034                         register_factory = 0
2035                         break
2036                 cnode = cin[0].fullDecl()
2037
2038         if register_factory:
2039             self.st.out(value_register_factory, vname=vname)
2040         
2041         # If value supports some interfaces, output an objref class for it
2042         if node.supports():
2043             inheritl = []
2044             methodl  = []
2045             for i in node.supports():
2046                 i = i.fullDecl()
2047                 sn = fixupScopedName(i.scopedName())
2048                 inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
2049                 methodl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]) +
2050                                ".__methods__")
2051                 
2052             inherits = string.join(inheritl, ", ")
2053
2054             self.st.out(objref_class, ifid=vname, inherits=inherits)
2055
2056             for inclass in inheritl:
2057                 self.st.out(objref_inherit_init, inclass=inclass)
2058
2059             methods = string.join(methodl, " + ")
2060             self.st.out(objref_methods, methods = methods)
2061
2062             # registerObjRef()
2063             self.st.out(value_objref_register,
2064                         ifid=vname, modname=self.modname)
2065
2066         # Modifier
2067         if node.custom():
2068             modifier = "_0_CORBA.VM_CUSTOM"
2069         elif node.truncatable():
2070             modifier = "_0_CORBA.VM_TRUNCATABLE"
2071         else:
2072             modifier = "_0_CORBA.VM_NONE"
2073
2074         # Truncatable bases
2075         tbasel = []
2076         cnode  = node
2077         while 1:
2078             cin = cnode.inherits()
2079             if not cin:
2080                 break
2081             i = cin[0]
2082             i = i.fullDecl()
2083             if not isinstance(i, idlast.Value):
2084                 break
2085             if cnode.truncatable():
2086                 sn = fixupScopedName(i.scopedName())
2087                 tbasel.append(dotName(sn) + "._NP_RepositoryId")
2088             else:
2089                 break
2090             cnode = i
2091
2092         if tbasel:
2093             tbaseids = "(%s._NP_RepositoryId, %s)" % (vname,
2094                                                      string.join(tbasel, ", "))
2095         else:
2096             tbaseids = "None"
2097
2098         basedesc = None
2099         if node.inherits():
2100             i = node.inherits()[0].fullDecl()
2101             if isinstance(i, idlast.Value):
2102                 sn = i.scopedName()[:]
2103                 sn[-1] = "_d_" + sn[-1]
2104                 basedesc = dotName(fixupScopedName(sn))
2105
2106         if basedesc is None:
2107             basedesc = "_0_CORBA.tcInternal.tv_null"
2108
2109         mlist = []
2110         for m in node.statemembers():
2111             for d in m.declarators():
2112                 mlist.append('"%s"' % mangle(d.identifier()))
2113                 mlist.append(typeAndDeclaratorToDescriptor(m.memberType(),
2114                                                            d, []))
2115                 if m.memberAccess() == 1:
2116                     mlist.append("_0_CORBA.PRIVATE_MEMBER")
2117                 else:
2118                     mlist.append("_0_CORBA.PUBLIC_MEMBER")
2119                     
2120         mdescs = string.join(mlist, ", ")
2121         self.st.out(value_descriptor_at_module_scope,
2122                     vname=vname, modifier=modifier, tbaseids=tbaseids,
2123                     basedesc=basedesc, mdescs=mdescs, modname=self.modname)
2124
2125
2126
2127 def docConst(node):
2128     if isinstance(node, idlast.Const)        and \
2129        node.constKind() == idltype.tk_string and \
2130        node.identifier()[-7:] == "__doc__":
2131         return node.identifier()[:-7]
2132     else:
2133         return None
2134
2135 def nodeId(node):
2136     if hasattr(node, "identifier"):
2137         return node.identifier()
2138     else:
2139         return None
2140
2141 def docWarning(node):
2142     sys.stderr.write(main.cmdname + \
2143                      ": Warning: Constant '" + node.identifier() + "' looks "
2144                      "like a Python docstring, but there is no declaration "
2145                      "named '" + node.identifier()[:-7] + "'.\n")
2146     
2147 class DocstringVisitor (idlvisitor.AstVisitor):
2148     def __init__(self, st):
2149         self.docs = []
2150         self.st   = st
2151
2152     def output(self):
2153         if self.docs:
2154             self.st.out("""\
2155 #
2156 # Docstrings
2157 #
2158 """)
2159         for nsn, dsn in self.docs:
2160             nsn = fixupScopedName(nsn)
2161             dsn = fixupScopedName(dsn)
2162
2163             self.st.out("@node@.__doc__ = @doc@",
2164                         node=dotName(nsn), doc=dotName(dsn))
2165             
2166         if self.docs:
2167             self.st.out("")
2168
2169     def visitAST(self, node):
2170         for n in node.declarations():
2171             if not output_inline and not n.mainFile(): continue
2172             
2173             d = docConst(n)
2174             if d:
2175                 ok = 0
2176                 for o in node.declarations():
2177                     if nodeId(o) == d:
2178                         self.docs.append((o.scopedName(), n.scopedName()))
2179                         if isinstance(o, idlast.Interface):
2180                             sn = o.scopedName()[:]
2181                             sn[-1] = "_objref_" + sn[-1]
2182                             self.docs.append((sn, n.scopedName()))
2183                         ok = 1
2184                         break
2185                 if not ok:
2186                     docWarning(n)
2187             n.accept(self)
2188
2189     def visitModule(self, node):
2190         for n in node.definitions():
2191             d = docConst(n)
2192             if d:
2193                 if d == node.identifier():
2194                     self.docs.append((node.scopedName(), n.scopedName()))
2195                 else:
2196                     ok = 0
2197                     for o in node.definitions():
2198                         if nodeId(o) == d:
2199                             self.docs.append((o.scopedName(), n.scopedName()))
2200                             if isinstance(o, idlast.Interface):
2201                                 sn = o.scopedName()[:]
2202                                 sn[-1] = "_objref_" + sn[-1]
2203                                 self.docs.append((sn, n.scopedName()))
2204                             ok = 1
2205                             break
2206                     if not ok:
2207                         docWarning(n)
2208             n.accept(self)
2209
2210     def visitInterface(self, node):
2211         for n in node.declarations():
2212             d = docConst(n)
2213             if d:
2214                 if d == node.identifier():
2215                     self.docs.append((node.scopedName(), n.scopedName()))
2216                     sn = node.scopedName()[:]
2217                     sn[-1] = "_objref_" + sn[-1]
2218                     self.docs.append((sn, n.scopedName()))
2219                 else:
2220                     ok = 0
2221                     for o in node.declarations():
2222                         if nodeId(o) == d:
2223                             self.docs.append((o.scopedName(), n.scopedName()))
2224                             ok = 1
2225                             break
2226                                 
2227                     if ok:
2228                         continue
2229
2230                     for o in node.callables():
2231                         self.target_id   = d
2232                         self.target_node = n
2233                         self.ok          = 0
2234                         o.accept(self)
2235                         if self.ok:
2236                             break
2237                     
2238                     if not self.ok:    
2239                         docWarning(n)
2240
2241     def visitOperation(self, node):
2242         if node.identifier() == self.target_id:
2243             sn = node.scopedName() + ["im_func"]
2244             sn[-3] = "_objref_" + sn[-3]
2245             self.docs.append((sn, self.target_node.scopedName()))
2246             self.ok = 1
2247
2248     def visitAttribute(self, node):
2249         for n in node.declarators():
2250             if n.identifier() == self.target_id:
2251                 sn = n.scopedName() + ["im_func"]
2252                 sn[-3] = "_objref_" + sn[-3]
2253                 sn[-2] = "_get_"    + sn[-2]
2254                 self.docs.append((sn, self.target_node.scopedName()))
2255                 if not node.readonly():
2256                     sn = sn[:]
2257                     sn[-2] = "_set_" + n.identifier()
2258                     self.docs.append((sn, self.target_node.scopedName()))
2259                 self.ok = 1
2260
2261
2262 class ExampleVisitor (idlvisitor.AstVisitor, idlvisitor.TypeVisitor):
2263     def __init__(self, st):
2264         self.st = st
2265         self.first = None
2266
2267     def visitAST(self, node):
2268         for n in node.declarations():
2269             if not output_inline and not n.mainFile(): continue
2270
2271             if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
2272                 n.accept(self)
2273
2274     def visitModule(self, node):
2275         for n in node.definitions():
2276             if not output_inline and not n.mainFile(): continue
2277
2278             if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
2279                 n.accept(self)
2280
2281     def visitInterface(self, node):
2282         ifname = mangle(node.identifier())
2283         sname  = node.scopedName()
2284         ccname = idlutil.ccolonName(sname)
2285         fsname = fixupScopedName(sname, prefix="")
2286         dname  = dotName(fsname)
2287         skname = skeletonModuleName(dname)
2288
2289         if self.first is None:
2290             self.first = ifname
2291
2292         if len(node.inherits()) == 1:
2293             inheritance_note = """
2294     # Note: this interface inherits from another interface. You must
2295     # either multiply inherit from the servant class implementing the
2296     # base interface, or explicitly implement the inherited operations
2297     # here.
2298     #
2299     # Inherited interface:
2300     #
2301 """
2302         elif node.inherits():
2303             inheritance_note = """
2304     # Note: this interface inherits from other interfaces. You must either
2305     # multiply inherit from the servant classes implementing the base
2306     # interfaces, or explicitly implement the inherited operations here.
2307     #
2308     # Inherited interfaces:
2309     #
2310 """
2311         else:
2312             inheritance_note = ""
2313
2314         for inh in node.inherits():
2315             iname = idlutil.ccolonName(inh.fullDecl().scopedName())
2316             inheritance_note = inheritance_note + "    #   %s\n" % iname
2317         
2318         self.st.out(example_classdef, ifname=ifname,
2319                     ccname=ccname, skname=skname,
2320                     inheritance_note = inheritance_note)
2321
2322         for c in node.callables():
2323
2324             if isinstance(c, idlast.Attribute):
2325
2326                 c.attrType().accept(self)
2327                 attrtype = self.__result_type
2328
2329                 for attr in c.identifiers():
2330
2331                     signature = "attribute %s %s" % (attrtype, attr)
2332
2333                     if c.readonly():
2334                         signature = "readonly " + signature
2335
2336                     if not c.readonly():
2337                         self.st.out(example_opdef,
2338                                     signature = signature,
2339                                     opname = "_set_" + attr,
2340                                     args = ", value",
2341                                     returnspec = "None")
2342
2343                     self.st.out(example_opdef,
2344                                 signature = signature,
2345                                 opname = "_get_" + attr,
2346                                 args = "",
2347                                 returnspec = "attribute value")
2348             else:
2349                 # Operation
2350                 innames  = []
2351                 outnames = []
2352                 siglist  = []
2353
2354                 c.returnType().accept(self)
2355                 rettype = self.__result_type
2356
2357                 if c.returnType().kind() != idltype.tk_void:
2358                     outnames.append("result")
2359
2360                 for p in c.parameters():
2361                     if p.is_in():
2362                         innames.append(p.identifier())
2363                     if p.is_out():
2364                         outnames.append(p.identifier())
2365
2366                     direction = {0:"in", 1:"out", 2:"inout"}[p.direction()]
2367
2368                     p.paramType().accept(self)
2369                     siglist.append("%s %s %s" % (direction,
2370                                                  self.__result_type,
2371                                                  p.identifier()))
2372
2373                 signature = "%s %s(%s)" % (rettype, c.identifier(),
2374                                            string.join(siglist, ", "))
2375
2376                 if innames:
2377                     args = ", " + string.join(innames, ", ")
2378                 else:
2379                     args = ""
2380
2381                 if outnames:
2382                     returnspec = string.join(outnames, ", ")
2383                 else:
2384                     returnspec = "None"
2385
2386                 self.st.out(example_opdef,
2387                             signature = signature,
2388                             opname = c.identifier(),
2389                             args = args,
2390                             returnspec = returnspec)
2391
2392
2393
2394     ttsMap = {
2395         idltype.tk_void:       "void",
2396         idltype.tk_short:      "short",
2397         idltype.tk_long:       "long",
2398         idltype.tk_ushort:     "unsigned short",
2399         idltype.tk_ulong:      "unsigned long",
2400         idltype.tk_float:      "float",
2401         idltype.tk_double:     "double",
2402         idltype.tk_boolean:    "boolean",
2403         idltype.tk_char:       "char",
2404         idltype.tk_octet:      "octet",
2405         idltype.tk_any:        "any",
2406         idltype.tk_TypeCode:   "CORBA::TypeCode",
2407         idltype.tk_Principal:  "CORBA::Principal",
2408         idltype.tk_longlong:   "long long",
2409         idltype.tk_ulonglong:  "unsigned long long",
2410         idltype.tk_longdouble: "long double",
2411         idltype.tk_wchar:      "wchar"
2412         }
2413
2414     def visitBaseType(self, type):
2415         self.__result_type = self.ttsMap[type.kind()]
2416
2417     def visitStringType(self, type):
2418         if type.bound() == 0:
2419             self.__result_type = "string"
2420         else:
2421             self.__result_type = "string<" + str(type.bound()) + ">"
2422
2423     def visitWStringType(self, type):
2424         if type.bound() == 0:
2425             self.__result_type = "wstring"
2426         else:
2427             self.__result_type = "wstring<" + str(type.bound()) + ">"
2428
2429
2430     def visitDeclaredType(self, type):
2431         self.__result_type = idlutil.ccolonName(type.decl().scopedName())
2432
2433
2434
2435
2436
2437 def operationToDescriptors(op):
2438     """Return the descriptors for an operation.
2439
2440     Returns a tuple containing strings of (in descriptor, out
2441     descriptor, exception map, context list, contains values)
2442     """
2443
2444     indl  = []
2445     outdl = []
2446     cv    = 0
2447
2448     if op.returnType() is not None and \
2449        op.returnType().kind() != idltype.tk_void:
2450
2451         outdl.append(typeToDescriptor(op.returnType()))
2452         cv = idltype.containsValueType(op.returnType())
2453
2454     # Make the lists of in and out parameters
2455     for p in op.parameters():
2456
2457         if p.is_in():
2458             indl.append(typeToDescriptor(p.paramType()))
2459         if p.is_out():
2460             outdl.append(typeToDescriptor(p.paramType()))
2461
2462         cv = cv or idltype.containsValueType(p.paramType())
2463
2464     # Fudge single-item lists so that single item tuples work
2465     if len(indl)  == 1: indl.append("")
2466     if len(outdl) == 1: outdl.append("")
2467
2468     inds = "(" + string.join(indl, ", ") + ")"
2469     if op.oneway():
2470         outds = "None"
2471     else:
2472         outds = "(" + string.join(outdl, ", ") + ")"
2473
2474     # Exceptions
2475     excl = []
2476
2477     for e in op.raises():
2478         sn = fixupScopedName(e.scopedName())
2479         ename = dotName(sn)
2480         edesc = dotName(sn[:-1] + [ "_d_" + sn[-1]])
2481         excl.append(ename + "._NP_RepositoryId: " + edesc)
2482
2483     if len(excl) > 0:
2484         excs = "{" + string.join(excl, ", ") + "}"
2485     else:
2486         excs = "None"
2487
2488     if op.contexts():
2489         ctxts = "[" + string.join(map(repr, op.contexts()), ", ") + "]"
2490     else:
2491         ctxts = None
2492
2493     return inds, outds, excs, ctxts, cv
2494
2495
2496
2497 ttdMap = {
2498     idltype.tk_short:      "omniORB.tcInternal.tv_short",
2499     idltype.tk_long:       "omniORB.tcInternal.tv_long",
2500     idltype.tk_ushort:     "omniORB.tcInternal.tv_ushort",
2501     idltype.tk_ulong:      "omniORB.tcInternal.tv_ulong",
2502     idltype.tk_float:      "omniORB.tcInternal.tv_float",
2503     idltype.tk_double:     "omniORB.tcInternal.tv_double",
2504     idltype.tk_boolean:    "omniORB.tcInternal.tv_boolean",
2505     idltype.tk_char:       "omniORB.tcInternal.tv_char",
2506     idltype.tk_octet:      "omniORB.tcInternal.tv_octet",
2507     idltype.tk_any:        "omniORB.tcInternal.tv_any",
2508     idltype.tk_TypeCode:   "omniORB.tcInternal.tv_TypeCode",
2509     idltype.tk_Principal:  "omniORB.tcInternal.tv_Principal",
2510     idltype.tk_longlong:   "omniORB.tcInternal.tv_longlong",
2511     idltype.tk_ulonglong:  "omniORB.tcInternal.tv_ulonglong",
2512     idltype.tk_wchar:      "omniORB.tcInternal.tv_wchar"
2513 }
2514
2515 unsupportedMap = {
2516     idltype.tk_longdouble: "long double",
2517 }
2518
2519 def typeToDescriptor(tspec, from_scope=[], is_typedef=0):
2520     if hasattr(tspec, "python_desc"):
2521         return tspec.python_desc
2522
2523     if ttdMap.has_key(tspec.kind()):
2524         tspec.python_desc = ttdMap[tspec.kind()]
2525         return tspec.python_desc
2526
2527     if unsupportedMap.has_key(tspec.kind()):
2528         error_exit("omniORBpy does not support the %s type." %
2529                    unsupportedMap[tspec.kind()])
2530
2531     if tspec.kind() == idltype.tk_string:
2532         ret = "(omniORB.tcInternal.tv_string," + str(tspec.bound()) + ")"
2533
2534     elif tspec.kind() == idltype.tk_wstring:
2535         ret = "(omniORB.tcInternal.tv_wstring," + str(tspec.bound()) + ")"
2536
2537     elif tspec.kind() == idltype.tk_sequence:
2538         ret = "(omniORB.tcInternal.tv_sequence, " + \
2539               typeToDescriptor(tspec.seqType(), from_scope) + \
2540               ", " + str(tspec.bound()) + ")"
2541
2542     elif tspec.kind() == idltype.tk_fixed:
2543         ret = "(omniORB.tcInternal.tv_fixed, " + \
2544               str(tspec.digits()) + ", " + str(tspec.scale()) + ")"
2545
2546     elif tspec.kind() == idltype.tk_alias:
2547         sn = fixupScopedName(tspec.scopedName())
2548         if is_typedef:
2549             return 'omniORB.typeCodeMapping["%s"]._d' % tspec.decl().repoId()
2550         else:
2551             return 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
2552
2553     else:
2554         ret = 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
2555
2556     tspec.python_desc = ret
2557     return ret
2558
2559
2560 def typeAndDeclaratorToDescriptor(tspec, decl, from_scope, is_typedef=0):
2561     desc = typeToDescriptor(tspec, from_scope, is_typedef)
2562
2563     if len(decl.sizes()) > 0:
2564         sizes = decl.sizes()[:]
2565         sizes.reverse()
2566         for size in sizes:
2567             desc = "(omniORB.tcInternal.tv_array, " + \
2568                    desc + ", " + str(size) + ")"
2569     return desc
2570
2571 def skeletonModuleName(mname):
2572     """Convert a scoped name string into the corresponding skeleton
2573 module name. e.g. M1.M2.I -> M1__POA.M2.I"""
2574     l = string.split(mname, ".")
2575     l[0] = l[0] + "__POA"
2576     return string.join(l, ".")
2577
2578 def dotName(scopedName, our_scope=[]):
2579     if scopedName[:len(our_scope)] == our_scope:
2580         l = map(mangle, scopedName[len(our_scope):])
2581     else:
2582         l = map(mangle, scopedName)
2583     return string.join(l, ".")
2584
2585 def mangle(name):
2586     if keyword.iskeyword(name): return "_" + name
2587
2588     # None is a pseudo-keyword that cannot be assigned to.
2589     if name == "None": return "_None"
2590
2591     return name
2592
2593 def fixupScopedName(scopedName, prefix="_0_"):
2594     """Add a prefix and _GlobalIDL to the front of a ScopedName if necessary"""
2595
2596     try:
2597         decl = idlast.findDecl([scopedName[0]])
2598     except idlast.DeclNotFound:
2599         decl = None
2600
2601     if isinstance(decl, idlast.Module):
2602         scopedName = [prefix + mangle(scopedName[0])] + scopedName[1:]
2603     else:
2604         scopedName = [prefix + global_module] + scopedName
2605     return scopedName
2606
2607 def valueToString(val, kind, scope=[]):
2608     if kind == idltype.tk_enum:
2609         return dotName(fixupScopedName(val.scopedName()), scope)
2610
2611     elif kind in [idltype.tk_string, idltype.tk_char]:
2612         return '"' + idlutil.escapifyString(val) + '"'
2613
2614     elif kind == idltype.tk_wstring:
2615         return 'u"' + idlutil.escapifyWString(val) + '"'
2616
2617     elif kind == idltype.tk_wchar:
2618         return 'u"' + idlutil.escapifyWString([val]) + '"'
2619
2620     elif kind == idltype.tk_long and val == -2147483647 - 1:
2621         return "-2147483647 - 1"
2622
2623     elif kind in [idltype.tk_float, idltype.tk_double, idltype.tk_longdouble]:
2624         return idlutil.reprFloat(val)
2625
2626     elif kind == idltype.tk_fixed:
2627         return "CORBA.fixed('" + val + "')"
2628
2629     else:
2630         return str(val)
2631
2632 __translate_table = string.maketrans(" -.,", "____")
2633
2634 def outputFileName(idlname):
2635     global __translate_table
2636     return string.translate(os.path.basename(idlname), __translate_table)
2637
2638 def checkStubPackage(package):
2639     """Check the given package name for use as a stub directory
2640
2641     Make sure all fragments of the package name are directories, or
2642     create them. Make __init__.py files in all directories."""
2643
2644     if len(package) == 0:
2645         return
2646
2647     if package[-1] == ".":
2648         package = package[:-1]
2649
2650     path = ""
2651     for name in string.split(package, "."):
2652         path = os.path.join(path, name)
2653         
2654         if os.path.exists(path):
2655             if not os.path.isdir(path):
2656                 error_exit('Output error: "%s" exists and is not '
2657                            'a directory.' % path)
2658         else:
2659             try:
2660                 os.mkdir(path)
2661             except:
2662                 error_exit('Cannot create directory "%s".\n' % path)
2663
2664         initfile = os.path.join(path, "__init__.py")
2665
2666         if os.path.exists(initfile):
2667             if not os.path.isfile(initfile):
2668                 error_exit('Output error: "%s" exists and is not a file.' %
2669                            initfile)
2670         else:
2671             try:
2672                 open(initfile, "w").write("# omniORB stub directory\n")
2673             except:
2674                 error_exit('Cannot create "%s".' % initfile)
2675
2676
2677 def updateModules(modules, pymodule):
2678     """Create or update the Python modules corresponding to the IDL
2679     module names"""
2680
2681     checkStubPackage(module_package)
2682
2683     poamodules = map(skeletonModuleName, modules)
2684
2685     real_updateModules(modules,    pymodule)
2686     real_updateModules(poamodules, pymodule)
2687
2688
2689 def real_updateModules(modules, pymodule):
2690
2691     for module in modules:
2692         modlist = string.split(module_package, ".") + string.split(module, ".")
2693         modpath = apply(os.path.join, modlist)
2694         modfile = os.path.join(modpath, "__init__.py")
2695         tmpfile = os.path.join(modpath, "new__init__.py")
2696
2697         if not os.path.exists(modpath):
2698             try:
2699                 os.makedirs(modpath)
2700             except:
2701                 error_exit('Cannot create path "%s".' % modpath)
2702
2703         # Make the __init__.py file if it does not already exist
2704         if not os.path.exists(modfile):
2705             try:
2706                 f = open(modfile, "w")
2707             except:
2708                 error_exit('Cannot create "%s".' % modfile)
2709             
2710             st = output.Stream(f, 4)
2711
2712             st.out(pymodule_template, module=module, package=module_package)
2713
2714             f.close()
2715             del f, st
2716
2717         if not os.path.isfile(modfile):
2718             error_exit('Output error: "%s" exists but is not a file.' %
2719                        modfile)
2720
2721         # Insert the import line for the current IDL file
2722         try:
2723             inf = open(modfile, "r")
2724         except:
2725             error_exit('Cannot open "%s" for reading.' % modfile)
2726
2727         try:
2728             outf = open(tmpfile, "w")
2729         except:
2730             error_exit('Cannot open "%s" for writing.' % tmpfile)
2731
2732         line = ""
2733         while line[:7] != "# ** 1.":
2734             line = inf.readline()
2735             if line == "":
2736                 error_exit('Output error: "%s" ended before I found a '
2737                            '"# ** 1." tag.\n'
2738                            'Have you left behind some files from a '
2739                            'different Python ORB?' % modfile)
2740                 
2741             outf.write(line)
2742             
2743         already    = 0
2744         outputline = "import " + pymodule + "\n"
2745
2746         while line != "\n":
2747             line = inf.readline()
2748             if line == "":
2749                 error_exit('Output error: "%s" ended while I was '
2750                            'looking at imports.' % modfile)
2751
2752             if line != "\n":
2753                 outf.write(line)
2754                 if line == outputline:
2755                     already = 1
2756
2757         if not already:
2758             outf.write(outputline)
2759
2760         outf.write("\n")
2761
2762         # Output the rest of the file
2763         while line != "":
2764             line = inf.readline()
2765             outf.write(line)
2766
2767         inf.close()
2768         outf.close()
2769
2770         try:
2771             os.remove(modfile)
2772         except:
2773             error_exit('Cannot remove "%s".' % modfile)
2774         try:
2775             os.rename(tmpfile, modfile)
2776         except:
2777             error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))
2778
2779     # Go round again, importing sub-modules from their parent modules
2780     for module in modules:
2781         modlist = string.split(module, ".")
2782
2783         if len(modlist) == 1:
2784             continue
2785
2786         modlist = string.split(module_package, ".") + modlist
2787         submod  = modlist[-1]
2788         modpath = apply(os.path.join, modlist[:-1])
2789         modfile = os.path.join(modpath, "__init__.py")
2790         tmpfile = os.path.join(modpath, "new__init__.py")
2791
2792         # Insert the import line for the sub-module
2793         try:
2794             inf = open(modfile, "r")
2795         except:
2796             error_exit('Cannot open "%s" for reading.' % modfile)
2797
2798         try:
2799             outf = open(tmpfile, "w")
2800         except:
2801             error_exit('Cannot open "%s" for writing.' % tmpfile)
2802
2803         line = ""
2804         while line[:7] != "# ** 2.":
2805             line = inf.readline()
2806             if line == "":
2807                 error_exit('Output error: "%s" ended before I found a '
2808                            '"# ** 1." tag.\n'
2809                            'Have you left behind some files from a '
2810                            'different Python ORB?' % modfile)
2811                 
2812             outf.write(line)
2813             
2814         already    = 0
2815         outputline = "import " + submod + "\n"
2816
2817         while line != "\n":
2818             line = inf.readline()
2819             if line == "":
2820                 error_exit('Output error: "%s" ended while I was '
2821                            'looking at imports.' % modfile)
2822
2823             if line != "\n":
2824                 outf.write(line)
2825                 if line == outputline:
2826                     already = 1
2827
2828         if not already:
2829             outf.write(outputline)
2830
2831         outf.write("\n")
2832
2833         # Output the rest of the file
2834         while line != "":
2835             line = inf.readline()
2836             outf.write(line)
2837
2838         inf.close()
2839         outf.close()
2840
2841         try:
2842             os.remove(modfile)
2843         except:
2844             error_exit('Cannot remove "%s".' % modfile)
2845         try:
2846             os.rename(tmpfile, modfile)
2847         except:
2848             error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))