3 # python.py Created on: 1999/10/29
4 # Author : Duncan Grisby (dpg1)
6 # Copyright (C) 1999 AT&T Laboratories Cambridge
8 # This file is part of omniidl.
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.
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.
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
31 # Revision 1.1.2.4 2009-11-18 15:56:23 vtn
34 # Revision 1.1.2.3 2009-11-17 12:15:43 vsv
35 # *** empty log message ***
37 # Revision 1.1.2.2 2009-11-05 14:57:23 vtn
38 # Added return array support.
40 # Revision 1.1.2.1 2009-11-03 13:14:05 vtn
41 # Added pathonIDL back-end for omniidl.
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.
46 # Revision 1.33.2.12 2006/09/29 16:48:03 dgrisby
47 # Stub changes broke use of package prefix. Thanks Teemu Torma.
49 # Revision 1.33.2.11 2006/09/07 15:28:57 dgrisby
50 # Remove obsolete check for presence of omniORB.StructBase.
52 # Revision 1.33.2.10 2006/06/21 14:46:26 dgrisby
53 # Invalid generated code for structs nested inside valuetypes.
55 # Revision 1.33.2.9 2006/01/19 17:28:44 dgrisby
56 # Merge from omnipy2_develop.
58 # Revision 1.33.2.8 2006/01/18 19:25:13 dgrisby
59 # Bug inheriting a valuetype from a typedef.
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.
64 # Revision 1.33.2.6 2005/01/07 00:22:34 dgrisby
65 # Big merge from omnipy2_develop.
67 # Revision 1.33.2.5 2004/03/24 22:28:50 dgrisby
68 # TypeCodes / truncation for inherited state members were broken.
70 # Revision 1.33.2.4 2004/02/16 10:14:18 dgrisby
71 # Use stream based copy for local calls.
73 # Revision 1.33.2.3 2003/07/10 22:13:25 dgrisby
74 # Abstract interface support.
76 # Revision 1.33.2.2 2003/05/20 17:10:24 dgrisby
77 # Preliminary valuetype support.
79 # Revision 1.33.2.1 2003/03/23 21:51:56 dgrisby
80 # New omnipy3_develop branch.
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.
86 # Revision 1.29.2.13 2002/07/04 13:14:52 dgrisby
87 # Bug with string escapes in Windows filenames.
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.
92 # Revision 1.29.2.11 2002/01/18 17:41:17 dpg1
93 # Support for "docstrings" in IDL.
95 # Revision 1.29.2.10 2002/01/18 15:49:45 dpg1
96 # Context support. New system exception construction. Fix None call problem.
98 # Revision 1.29.2.9 2001/12/04 12:17:08 dpg1
99 # Incorrect generated code for fixed constants.
101 # Revision 1.29.2.8 2001/08/29 11:57:16 dpg1
104 # Revision 1.29.2.7 2001/06/15 10:59:26 dpg1
105 # Apply fixes from omnipy1_develop.
107 # Revision 1.29.2.6 2001/06/13 11:29:04 dpg1
108 # Proper omniidl support for wchar/wstring constants.
110 # Revision 1.29.2.5 2001/05/10 15:16:03 dpg1
111 # Big update to support new omniORB 4 internals.
113 # Revision 1.29.2.4 2001/04/09 15:22:16 dpg1
114 # Fixed point support.
116 # Revision 1.29.2.3 2000/11/22 14:43:58 dpg1
117 # Support code set conversion and wchar/wstring.
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
123 # Revision 1.29.2.1 2000/10/13 13:55:30 dpg1
124 # Initial support for omniORB 4.
126 # Revision 1.29 2000/10/02 17:34:58 dpg1
127 # Merge for 1.2 release
129 # Revision 1.27.2.3 2000/08/22 11:52:28 dpg1
130 # Generate inherited classes for typedef to struct/union.
132 # Revision 1.27.2.2 2000/08/07 09:19:24 dpg1
135 # Revision 1.27.2.1 2000/07/18 15:31:29 dpg1
136 # Bug with inheritance from typedef
138 # Revision 1.27 2000/07/12 14:32:13 dpg1
139 # New no_package option to omniidl backend
141 # Revision 1.26 2000/06/28 12:47:48 dpg1
142 # Proper error messages for unsupported IDL constructs.
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.
148 # Revision 1.24 2000/03/29 10:15:47 dpg1
149 # Exceptions now more closely follow the interface of
150 # exceptions.Exception.
152 # Revision 1.23 2000/03/17 12:28:09 dpg1
153 # Comma missing in nested union descriptor.
155 # Revision 1.22 2000/03/03 17:41:28 dpg1
156 # Major reorganisation to support omniORB 3.0 as well as 2.8.
158 # Revision 1.21 2000/02/23 10:20:52 dpg1
159 # Bug in descriptors for single-item enums.
161 # Revision 1.20 2000/01/04 15:29:41 dpg1
162 # Fixes to modules generated within a package.
164 # Revision 1.19 1999/12/21 16:06:15 dpg1
165 # DOH! global= not module= !
167 # Revision 1.18 1999/12/21 16:05:11 dpg1
168 # New module= option.
170 # Revision 1.17 1999/12/17 11:39:52 dpg1
171 # New arguments to put modules and stubs in a specified package.
173 # Revision 1.16 1999/12/15 11:32:42 dpg1
174 # -Wbinline option added.
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().
180 # Revision 1.14 1999/12/07 15:35:14 dpg1
181 # Bug in currentScope handling.
183 # Revision 1.13 1999/11/30 10:41:20 dpg1
184 # Back-ends can now have their own usage string.
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.
190 # Revision 1.11 1999/11/25 11:21:36 dpg1
191 # Proper support for server-side _is_a().
193 # Revision 1.10 1999/11/19 11:03:49 dpg1
194 # Extremely important spelling correction in a comment. :-)
196 # Revision 1.9 1999/11/12 15:53:48 dpg1
197 # New functions omniORB.importIDL() and omniORB.importIDLString().
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.
203 # Revision 1.7 1999/11/10 16:08:22 dpg1
204 # Some types weren't registered properly.
206 # Revision 1.6 1999/11/04 11:46:12 dpg1
207 # Now uses our own version of the GNU C preprocessor.
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.
213 # Revision 1.4 1999/11/02 10:54:01 dpg1
214 # Two small bugs in union generation.
216 # Revision 1.3 1999/11/02 10:01:46 dpg1
219 # Revision 1.2 1999/11/01 20:19:55 dpg1
220 # Support for union switch types declared inside the switch statement.
222 # Revision 1.1 1999/11/01 16:40:11 dpg1
223 # First revision with new front-end.
226 """omniORB Python bindings"""
228 from omniidl import idlast, idltype, idlutil, idlvisitor, output, main
229 import sys, string, types, os.path, keyword
231 cpp_args = ["-D__OMNIIDL_PYTHON__"]
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)"""
242 #""" Uncomment this line to get syntax highlighting on the output strings
246 pymodule_template = """\
247 # DO NOT EDIT THIS FILE!
249 # Python module @module@ generated by omniidl
252 omniORB.updateModule("@package@@module@")
254 # ** 1. Stub files contributing to this module
261 # Python stubs generated by omniidl from @filename@
263 import omniORB, _omnipy
265 from omniORB import CORBA, PortableServer
268 _omnipy.checkVersion(3,0, __file__)
272 _exported_modules = ( @export_string@)
278 # Start of module "@sname@"
280 __name__ = "@package@@sname@"
281 _0_@sname@ = omniORB.openModule("@package@@sname@", r"@filename@")
282 _0_@s_sname@ = omniORB.openModule("@package@@s_sname@", r"@filename@")
287 # End of module "@sname@"
289 __name__ = "@package@@modname@"
292 import_idl_file = """\
293 # #include "@idlfile@"
294 import @ifilename@"""
296 open_imported_module_name = """\
297 _0_@imodname@ = omniORB.openModule("@package@@imodname@")
298 _0_@s_imodname@ = omniORB.openModule("@package@@s_imodname@")"""
300 forward_interface = """\
302 # @abstract@interface @ifid@;
303 _0_@modname@._d_@ifid@ = (omniORB.tcInternal.@tvkind@, "@repoId@", "@ifid@")
304 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@ifid@"""
307 interface_class = """\
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]
316 def __init__(self, *args, **kw):
317 raise RuntimeError("Cannot construct objects of this type.")
319 _nil = CORBA.Object._nil
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@)"""
327 callables_header = """
328 # @ifid@ operations and attributes"""
330 attribute_get_descriptor = """\
331 @ifid@._d__get_@attr@ = ((),(@descr@,),None)"""
333 attribute_set_descriptor = """\
334 @ifid@._d__set_@attr@ = ((@descr@,),(),None)"""
336 operation_descriptor = """\
337 @ifid@._d_@opname@ = (@inds@, @outds@, @excs@@options@)"""
341 # @ifid@ object reference
342 class _objref_@ifid@ (@inherits@):
343 _NP_RepositoryId = @ifid@._NP_RepositoryId
345 def __init__(self):"""
347 objref_inherit_init = """\
348 @inclass@.__init__(self)"""
350 objref_object_init = """\
351 CORBA.Object.__init__(self)"""
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)"""
363 __methods__ = @methods@"""
365 objref_register = """
366 omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
367 _0_@modname@._objref_@ifid@ = _objref_@ifid@
368 del @ifid@, _objref_@ifid@"""
372 __name__ = "@package@@s_modname@"
373 class @ifid@ (@inherits@):
374 _NP_RepositoryId = _0_@modname@.@ifid@._NP_RepositoryId
377 skeleton_methodmap = """
378 _omni_op_d = @methodmap@"""
380 skeleton_inheritmap = """\
381 _omni_op_d.update(@inheritclass@._omni_op_d)"""
384 @ifid@._omni_skeleton = @ifid@
385 _0_@s_modname@.@ifid@ = @ifid@
386 omniORB.registerSkeleton(@ifid@._NP_RepositoryId, @ifid@)
388 __name__ = "@package@@modname@"\
391 skeleton_set_skel = """
392 @ifid@._omni_skeleton = @ifid@
395 constant_at_module_scope = """\
396 _0_@modname@.@cname@ = @value@"""
401 typedef_header = """\
403 # typedef ... @tdname@
405 _NP_RepositoryId = "@repoId@"
406 def __init__(self, *args, **kw):
407 raise RuntimeError("Cannot construct objects of this type.")"""
409 typedef_struct_union_header = """\
411 # typedef ... @tdname@
412 class @tdname@ (@parent@):
413 _NP_RepositoryId = "@repoId@"
416 typedef_fixed_header = """\
417 # typedef ... @tdname@
418 @tdname@ = omniORB.fixedConstructor("@repoId@", @digits@, @scale@)"""
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@)
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@)"""
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@"""
439 forward_struct_descr = """
440 # Forward struct @sname@
441 _d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
442 omniORB.typeMapping["@repoId@"] = _d_@sname@"""
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@"""
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@"""
457 _0_@scopedname@ = omniORB.newEmptyClass()
458 class @sname@ (omniORB.StructBase):
459 _NP_RepositoryId = "@repoId@"
462 struct_class_name = """\
463 _NP_ClassName = "@cname@"
466 struct_class_init = """\
467 def __init__(self@mnames@):"""
469 struct_init_member = """\
470 self.@mname@ = @mname@"""
472 struct_descriptor_at_module_scope = """\
474 _0_@modname@.@sname@ = @sname@
475 _0_@modname@._d_@sname@ = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
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@)
482 struct_descriptor = """\
484 _d_@sname@ = _0_@scope@._d_@sname@ = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
486 struct_register = """\
487 _tc_@sname@ = omniORB.tcInternal.createTypeCode(_d_@sname@)
488 omniORB.registerType(@sname@._NP_RepositoryId, _d_@sname@, _tc_@sname@)"""
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@"""
495 exception_class = """\
498 _0_@scopedname@ = omniORB.newEmptyClass()
499 class @sname@ (CORBA.UserException):
500 _NP_RepositoryId = "@repoId@"
503 exception_class_init = """\
504 def __init__(self@mnames@):
505 CORBA.UserException.__init__(self@mnames@)"""
507 exception_init_member = """\
508 self.@mname@ = @mname@"""
510 exception_descriptor_at_module_scope = """\
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@)
518 exception_descriptor = """\
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@)"""
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@"""
529 forward_union_descr = """
530 # Forward union @uname@
531 _d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
532 omniORB.typeMapping["@repoId@"] = _d_@uname@"""
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@"""
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@"""
547 _0_@scopedname@ = omniORB.newEmptyClass()
548 class @uname@ (omniORB.Union):
549 _NP_RepositoryId = "@repoId@"\
552 union_class_name = """\
553 _NP_ClassName = "@cname@"
556 union_descriptor_at_module_scope = """
557 _0_@modname@.@uname@ = @uname@
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@
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@})"""
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@)
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@
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@})"""
581 union_register = """\
582 _tc_@uname@ = omniORB.tcInternal.createTypeCode(_d_@uname@)
583 omniORB.registerType(@uname@._NP_RepositoryId, _d_@uname@, _tc_@uname@)"""
590 enum_item_at_module_scope = """\
591 _0_@modname@.@eitem@ = omniORB.EnumItem("@item@", @eval@)"""
593 enum_object_and_descriptor_at_module_scope = """\
594 _0_@modname@.@ename@ = omniORB.Enum("@repoId@", (@eitems@,))
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@)"""
601 @eitem@ = omniORB.EnumItem("@item@", @eval@)"""
603 enum_object_and_descriptor = """\
604 @ename@ = omniORB.Enum("@repoId@", (@eitems@,))
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@)"""
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@
619 _0_@modname@._d_@vname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
620 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@vname@
621 _0_@modname@.@vname@ = omniORB.newEmptyClass()
623 class @vname@ (@inherits@):
624 _NP_RepositoryId = "@repoId@"
626 def __init__(self, *args, **kwargs):
628 if len(args) != @arglen@:
629 raise TypeError("@vname@() takes @arglen@ argument@s@ "
630 "(%d given)" % len(args))
633 self.__dict__.update(kwargs)
636 valueabs_class = """\
637 class @vname@ (@inherits@):
638 _NP_RepositoryId = "@repoId@"
640 def __init__(self, *args, **kwargs):
641 raise RuntimeError("Cannot construct objects of this type.")
644 value_register_factory = """\
645 omniORB.registerValueFactory(@vname@._NP_RepositoryId, @vname@)
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@)
656 value_objref_register = """
657 omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
658 _0_@modname@._objref_@ifid@ = _objref_@ifid@
659 del _objref_@ifid@"""
666 _NP_RepositoryId = "@repoId@"
667 def __init__(self, *args, **kw):
668 raise RuntimeError("Cannot construct objects of this type.")
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@)
680 #!/usr/bin/env python
682 # Python example implementations generated from @filename@
684 import CORBA, PortableServer
686 # Import the Python stub modules so type definitions are available.
689 example_import_skels = """
690 # Import the Python Skeleton modules so skeleton base classes are available.
693 example_import = """\
696 example_classdef = """
698 # Implementation of interface @ccname@
700 class @ifname@_i (@skname@):
703 # Initialise member variables here
709 def @opname@(self@args@):
710 raise CORBA.NO_IMPLEMENT(0, CORBA.COMPLETED_NO)
712 # Must return: @returnspec@
716 if __name__ == "__main__":
720 orb = CORBA.ORB_init(sys.argv)
722 # As an example, we activate an object in the Root POA
723 poa = orb.resolve_initial_references("RootPOA")
725 # Create an instance of a servant class
726 servant = @ifname@_i()
728 # Activate it in the Root POA
729 poa.activate_object(servant)
731 # Get the object reference to the object
732 objref = servant._this()
734 # Print a stringified IOR for it
735 print orb.object_to_string(objref)
737 # Activate the Root POA's manager
738 poa._get_the_POAManager().activate()
740 # Run the ORB, blocking this thread
747 exported_modules = {}
749 # Command line options
751 global_module = "_GlobalIDL"
757 extern_stub_pkgs = {}
759 def methgrp_index(metharr,opname):
760 for i in range(0, len(metharr)):
761 if len(opname) > 2 and metharr[i] == opname[:-2]:
767 return "args["+str(p)+"]"
770 return "(type("+ret_arg(p)+") in [IntType, LongType])"
773 return "(type("+ret_arg(p)+") in [IntType, LongType, BooleanType])"
776 return "(type("+ret_arg(p)+") in [IntType, LongType, FloatType])"
779 return "(type("+ret_arg(p)+") in [StringType])"
782 return "(type("+ret_arg(p)+") in [InstanceType])"
785 return "(type("+ret_arg(p)+").count('[]') > 0)"
788 return "(type("+ret_arg(p)+") in [CORBA.Any])"
791 return "((type("+ret_arg(p)+") in [StringType]) and (len(" + ret_arg(p) + ") == 1))"
793 def error_exit(message):
794 sys.stderr.write(main.cmdname + ": " + message + "\n")
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
802 imported_files.clear()
803 exported_modules.clear()
814 elif arg == "no_package":
817 elif arg == "inline":
820 elif arg == "factories":
823 elif arg[:8] == "modules=":
824 module_package = arg[8:]
825 if module_package != "":
826 module_package = module_package + "."
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 + "."
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 + "."
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.")
847 elif arg == "example":
850 elif arg[:7] == "extern=":
851 f_p = string.split(arg[7:], ":", 1)
853 extern_stub_pkgs[f_p[0]] = None
855 extern_stub_pkgs[f_p[0]] = f_p[1]
858 sys.stderr.write(main.cmdname + ": Warning: Python " \
859 "back-end does not understand argument: " + \
862 main_idl_file = tree.file()
864 outpybasename = outputFileName(main_idl_file)
865 outpymodule = stub_package + outpybasename
866 outpyname = os.path.join(stub_directory, outpybasename + ".py")
868 imported_files[outpybasename] = 1
871 checkStubPackage(stub_package)
874 st = output.Stream(sys.stdout, 4)
877 st = output.Stream(open(outpyname, "w"), 4)
879 error_exit('Cannot open "%s" for writing.' % outpyname)
881 st.out(file_start, filename=main_idl_file)
883 pv = PythonVisitor(st, outpymodule)
886 dv = DocstringVisitor(st)
890 exports = exported_modules.keys()
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, ", ")
896 st.out(file_end, export_string=export_string)
899 updateModules(exports, outpymodule)
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)
906 exst.out(example_import, module=mod)
907 exst.out(example_import_skels)
909 exst.out(example_import, module=skeletonModuleName(mod))
911 ev = ExampleVisitor(exst)
914 exst.out(example_end, ifname=ev.first)
918 def __init__(self, st, outpymodule):
920 self.outpymodule = outpymodule
922 def handleImported(self, node):
923 global imported_files
925 if node.mainFile() or output_inline:
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]
935 fn = ipackage + '.' + ifilename
939 fn = stub_package + ifilename
941 self.st.out(import_idl_file,
949 def visitAST(self, node):
950 self.at_module_scope = 1
951 self.at_global_scope = 1
952 self.currentScope = ["_0_" + global_module]
954 decls_in_global_module = 0
956 for n in node.declarations():
957 if not isinstance(n, idlast.Module):
958 decls_in_global_module = 1
961 if decls_in_global_module:
962 self.modname = global_module
963 self.st.out(module_start,
965 s_sname=skeletonModuleName(global_module),
966 filename=node.file(), package=module_package)
968 self.modname = self.outpymodule
970 for n in node.declarations():
973 if decls_in_global_module:
974 exported_modules[global_module] = 1
975 self.st.out(module_end, modname=self.outpymodule,
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()))
987 if extern_stub_pkgs.has_key(ibasename):
988 package = extern_stub_pkgs[ibasename]
992 package = package + "."
994 package = module_package
996 self.st.out(open_imported_module_name,
998 s_imodname=skeletonModuleName(imodname),
1001 assert self.at_module_scope
1003 sname = dotName(node.scopedName())
1005 if node.mainFile() or output_inline:
1006 self.st.out(module_start,
1008 s_sname = skeletonModuleName(sname),
1009 filename = node.file(), package=module_package)
1011 parentmodname = self.modname
1012 self.modname = dotName(node.scopedName())
1014 ags = self.at_global_scope
1016 self.currentScope = ["_0_" + node.identifier()]
1018 self.currentScope.append(node.identifier())
1020 self.at_global_scope = 0
1022 for n in node.definitions():
1026 self.currentScope = ["_0_" + global_module]
1028 self.currentScope.pop()
1029 self.at_global_scope = ags
1030 self.modname = parentmodname
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)
1040 def visitForward(self, node):
1041 if self.handleImported(node): return
1043 assert self.at_module_scope
1044 ifid = mangle(node.identifier())
1045 repoId = node.repoId()
1047 tvkind = "tv_abstract_interface"
1048 abstract = "abstract "
1050 tvkind = "tv_objref"
1053 self.st.out(forward_interface, ifid=ifid, tvkind=tvkind,
1054 repoId=repoId, abstract=abstract, modname=self.modname)
1059 def visitInterface(self, node):
1060 if self.handleImported(node): return
1062 assert self.at_module_scope
1063 ifid = mangle(node.identifier())
1065 if len(node.inherits()) > 0:
1067 for i in node.inherits():
1069 inheritl.append(dotName(fixupScopedName(i.scopedName())))
1071 inherits = "(" + string.join(inheritl, ", ") + ")"
1076 tvkind = "tv_abstract_interface"
1077 abstract = "abstract "
1079 tvkind = "tv_objref"
1083 self.st.out(interface_class, ifid=ifid, tvkind=tvkind,
1084 inherits=inherits, repoId=node.repoId(),
1085 abstract=abstract, modname=self.modname)
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())
1093 for d in node.declarations():
1096 self.currentScope.pop()
1097 self.at_module_scope = 1
1098 self.st.dec_indent()
1101 # Descriptor and TypeCode for the interface
1102 self.st.out(interface_descriptor,
1103 modname = self.modname, ifid = ifid)
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)
1110 for c in node.callables():
1111 if isinstance(c, idlast.Attribute):
1113 descr = typeToDescriptor(c.attrType())
1115 for attr in c.identifiers():
1117 self.st.out(attribute_get_descriptor,
1118 attr=attr, descr=descr, ifid=ifid)
1120 if not c.readonly():
1122 self.st.out(attribute_set_descriptor,
1123 attr=attr, descr=descr, ifid=ifid)
1126 inds, outds, excs, ctxts, cv = operationToDescriptors(c)
1131 ctxts = ctxts or "None"
1134 options = ", " + ctxts
1137 options = options + ", 1"
1139 # Output the declaration
1140 self.st.out(operation_descriptor,
1141 opname = mangle(c.identifier()),
1151 for i in node.inherits():
1153 sn = fixupScopedName(i.scopedName())
1154 inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
1156 inherits = string.join(inheritl, ", ")
1158 inherits = "CORBA.Object"
1160 self.st.out(objref_class, ifid=ifid, inherits=inherits)
1163 for inclass in inheritl:
1164 self.st.out(objref_inherit_init, inclass=inclass)
1166 self.st.out(objref_object_init)
1168 # Operations and attributes
1173 for c in node.callables():
1175 if isinstance(c, idlast.Attribute):
1177 for attr in c.identifiers():
1179 self.st.out(objref_attribute_get,
1182 modname = self.modname)
1184 methodl.append('"_get_' + attr + '"')
1186 if not c.readonly():
1188 self.st.out(objref_attribute_set,
1191 modname = self.modname)
1193 methodl.append('"_set_' + attr + '"')
1196 opname = mangle(c.identifier())
1198 if len(opname) > 2 and opname[-2] == '_':
1199 methlen = methgrp_index(methadd,opname)
1201 methodl.append('"' + opname[:-2] + '"')
1203 methlen = len(methadd)
1205 methadd = methadd + [opname[:-2]]
1207 methdsc = methdsc + [""]
1208 methdsc[methlen] = "\n def "+opname[:-2]+"(self, *args):"
1210 methdsc[methlen] = methdsc[methlen] + "\n "
1212 methdsc[methlen] = methdsc[methlen] + "if len(args) == " + str(len(c.parameters()))
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()) + " == '' "
1235 methdsc[methlen] = methdsc[methlen] + ":"
1236 methdsc[methlen] = methdsc[methlen] + "\n return self."+opname+"(*args)"
1238 self.st.out(objref_operation,
1240 r_opname = c.identifier(),
1242 modname = self.modname)
1243 methodl.append('"' + opname + '"')
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)
1251 #self.st.out("\n def __eq__(self,other):")
1252 #self.st.out(" return self.IsSame(other)==0")
1254 # __methods__ assignment
1255 methods = "[" + string.join(methodl, ", ") + "]"
1259 for i in node.inherits():
1261 sn = fixupScopedName(i.scopedName())
1262 methods = methods + " + " + \
1263 dotName(sn[:-1] + ["_objref_" + sn[-1]]) + \
1266 methods = methods + " + CORBA.Object.__methods__"
1268 self.st.out(objref_methods, methods = methods)
1271 self.st.out(objref_register, ifid = ifid, modname = self.modname)
1276 for i in node.inherits():
1278 fsn = fixupScopedName(i.scopedName())
1280 ssn = skeletonModuleName(dsn)
1281 inheritl.append(ssn)
1283 inherits = string.join(inheritl, ", ")
1285 inherits = "PortableServer.Servant"
1287 self.st.out(skeleton_class,
1289 inherits = inherits,
1290 modname = self.modname,
1291 s_modname = skeletonModuleName(self.modname),
1292 package = module_package)
1294 # Operations and attributes
1297 for c in node.callables():
1298 if isinstance(c, idlast.Attribute):
1300 for attr in c.identifiers():
1302 methodl.append('"_get_' + attr + '": ' + \
1303 '_0_' + self.modname + '.' + \
1304 ifid + '.' + '_d__get_' + attr)
1306 if not c.readonly():
1308 methodl.append('"_set_' + attr + '": ' + \
1309 '_0_' + self.modname + '.' + \
1310 ifid + '.' + '_d__set_' + attr)
1313 opname = mangle(c.identifier())
1315 methodl.append('"' + opname + '": ' + '_0_' + self.modname + \
1316 '.' + ifid + '.' + '_d_' + opname)
1318 methodmap = "{" + string.join(methodl, ", ") + "}"
1320 self.st.out(skeleton_methodmap, methodmap = methodmap)
1323 for inheritclass in inheritl:
1324 self.st.out(skeleton_inheritmap, inheritclass = inheritclass)
1326 self.st.out(skeleton_end,
1328 modname = self.modname,
1329 s_modname = skeletonModuleName(self.modname),
1330 package = module_package)
1335 def visitConst(self, node):
1336 if self.handleImported(node): return
1338 cname = mangle(node.identifier())
1340 if self.at_module_scope:
1341 value = valueToString(node.value(), node.constKind(), [])
1343 value = valueToString(node.value(), node.constKind(),
1345 if self.at_module_scope:
1346 self.st.out(constant_at_module_scope,
1349 modname = self.modname)
1351 self.st.out(constant,
1358 def visitTypedef(self, node):
1359 if self.handleImported(node): return
1361 if node.constrType():
1362 node.aliasType().decl().accept(self)
1364 for decl in node.declarators():
1365 tdname = mangle(decl.identifier())
1366 if self.at_module_scope:
1367 desc = typeAndDeclaratorToDescriptor(node.aliasType(),
1369 tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
1372 unaliased_type = node.aliasType().unalias()
1374 if len(decl.sizes()) == 0 and \
1375 unaliased_type.kind() in [idltype.tk_struct,
1378 parent = dotName(fixupScopedName(unaliased_type.decl().\
1381 self.st.out(typedef_struct_union_header,
1383 repoId = decl.repoId(),
1386 elif len(decl.sizes()) == 0 and\
1387 unaliased_type.kind() == idltype.tk_fixed:
1389 self.st.out(typedef_fixed_header,
1391 repoId = decl.repoId(),
1392 digits = unaliased_type.digits(),
1393 scale = unaliased_type.scale())
1396 self.st.out(typedef_header,
1398 repoId = decl.repoId())
1400 self.st.out(typedef_at_module_scope,
1404 modname = self.modname)
1406 desc = typeAndDeclaratorToDescriptor(node.aliasType(),
1409 tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
1411 self.currentScope, 1)
1413 unaliased_type = node.aliasType().unalias()
1415 if len(decl.sizes()) == 0 and \
1416 unaliased_type.kind() in [idltype.tk_struct,
1419 psname = unaliased_type.decl().scopedName()
1420 myscope = decl.scopedName()[:-1]
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
1428 if psname[:len(myscope)] == myscope:
1429 parent = dotName(psname[len(myscope):])
1431 parent = dotName(fixupScopedName(psname))
1433 self.st.out(typedef_struct_union_header,
1435 repoId = decl.repoId(),
1438 self.st.out(typedef_header,
1440 repoId = decl.repoId())
1442 self.st.out(typedef,
1449 def visitStruct(self, node):
1450 if self.handleImported(node): return
1452 sname = mangle(node.identifier())
1454 fscopedName = fixupScopedName(node.scopedName(), "")
1456 if node.recursive():
1457 if self.at_module_scope:
1458 self.st.out(recursive_struct_descr_at_module_scope,
1460 repoId = node.repoId(),
1461 modname = self.modname)
1463 self.st.out(recursive_struct_descr,
1465 repoId = node.repoId(),
1466 scope = dotName(fscopedName[:-1]))
1468 self.st.out(struct_class,
1470 repoId = node.repoId(),
1471 scopedname = dotName(fscopedName))
1473 if not self.at_module_scope:
1474 self.st.out(struct_class_name, cname = dotName(fscopedName))
1478 for mem in node.members():
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())
1487 mem.memberType().decl().accept(self)
1489 self.currentScope.pop()
1490 self.at_module_scope = ams
1491 self.st.dec_indent()
1494 for decl in mem.declarators():
1495 mnamel.append(mangle(decl.identifier()))
1496 mdescl.append('"' + mangle(decl.identifier()) + '"')
1498 if self.at_module_scope:
1500 typeAndDeclaratorToDescriptor(mem.memberType(),
1505 typeAndDeclaratorToDescriptor(mem.memberType(),
1509 mnames = ", " + string.join(mnamel, ", ")
1511 self.st.out(struct_class_init, mnames = mnames)
1513 for mname in mnamel:
1514 self.st.out(struct_init_member, mname = mname)
1517 mdescs = ", " + string.join(mdescl, ", ")
1521 if self.at_module_scope:
1522 self.st.out(struct_descriptor_at_module_scope,
1525 modname = self.modname)
1527 self.st.out(struct_register_at_module_scope,
1529 modname = self.modname)
1531 self.st.out(struct_descriptor,
1534 scope = dotName(fscopedName[:-1]))
1536 self.st.out(struct_register, sname = sname)
1541 def visitStructForward(self, node):
1542 if self.handleImported(node): return
1544 sname = mangle(node.identifier())
1546 if self.at_module_scope:
1547 self.st.out(forward_struct_descr_at_module_scope,
1549 repoId = node.repoId(),
1550 modname = self.modname)
1552 self.st.out(forward_struct_descr,
1554 repoId = node.repoId(),
1555 modname = self.modname)
1560 def visitException(self, node):
1561 if self.handleImported(node): return
1563 sname = mangle(node.identifier())
1564 fscopedName = fixupScopedName(node.scopedName(), "")
1565 self.st.out(exception_class,
1567 repoId = node.repoId(),
1568 scopedname = dotName(fscopedName))
1570 if not self.at_module_scope:
1571 self.st.out(struct_class_name, cname = dotName(fscopedName))
1575 for mem in node.members():
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())
1584 mem.memberType().decl().accept(self)
1586 self.currentScope.pop()
1587 self.at_module_scope = ams
1588 self.st.dec_indent()
1591 for decl in mem.declarators():
1592 mnamel.append(mangle(decl.identifier()))
1593 mdescl.append('"' + mangle(decl.identifier()) + '"')
1595 if self.at_module_scope:
1597 typeAndDeclaratorToDescriptor(mem.memberType(),
1602 typeAndDeclaratorToDescriptor(mem.memberType(),
1607 mnames = ", " + string.join(mnamel, ", ")
1611 self.st.out(exception_class_init, mnames = mnames)
1613 for mname in mnamel:
1614 self.st.out(exception_init_member, mname = mname)
1617 mdescs = ", " + string.join(mdescl, ", ")
1621 if self.at_module_scope:
1622 self.st.out(exception_descriptor_at_module_scope,
1623 sname = sname, mdescs = mdescs, modname = self.modname)
1625 self.st.out(exception_descriptor, sname = sname, mdescs = mdescs)
1630 def visitUnion(self, node):
1631 if self.handleImported(node): return
1633 uname = mangle(node.identifier())
1634 if self.at_module_scope:
1635 stype = typeToDescriptor(node.switchType(), [])
1637 stype = typeToDescriptor(node.switchType(), self.currentScope)
1639 fscopedName = fixupScopedName(node.scopedName(), "")
1641 if node.recursive():
1642 if self.at_module_scope:
1643 self.st.out(recursive_union_descr_at_module_scope,
1645 repoId = node.repoId(),
1646 modname = self.modname)
1648 self.st.out(recursive_union_descr,
1650 repoId = node.repoId(),
1651 scope = dotName(fscopedName[:-1]))
1653 self.st.out(union_class,
1655 repoId = node.repoId(),
1656 scopedname = dotName(fscopedName))
1658 if not self.at_module_scope:
1659 self.st.out(union_class_name, cname = dotName(fscopedName))
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())
1667 node.switchType().decl().accept(self)
1669 self.currentScope.pop()
1670 self.at_module_scope = ams
1671 self.st.dec_indent()
1683 for case in node.cases():
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())
1692 case.caseType().decl().accept(self)
1694 self.currentScope.pop()
1695 self.at_module_scope = ams
1696 self.st.dec_indent()
1699 if self.at_module_scope:
1700 ctype = typeAndDeclaratorToDescriptor(case.caseType(),
1704 ctype = typeAndDeclaratorToDescriptor(case.caseType(),
1708 cname = mangle(case.declarator().identifier())
1710 for label in case.labels():
1712 def_m = '"' + cname + '"'
1714 if self.at_module_scope:
1715 def_d = valueToString(label.value(),
1716 label.labelKind(), [])
1717 m_def = "_0_" + self.modname + "._m_" + uname + \
1720 def_d = valueToString(label.value(),
1723 m_def = "_m_" + uname + "[" + defpos + "]"
1725 m_un_l.append('(' + def_d + ', "' + cname + '", ' +\
1728 if self.at_module_scope:
1729 slabel = valueToString(label.value(),
1730 label.labelKind(), [])
1732 slabel = valueToString(label.value(),
1736 m_to_d_l.append('"' + cname + '": ' + slabel)
1737 d_to_m_l.append(slabel + ': "' + cname + '"')
1739 m_un_l.append('(' + slabel + ', "' + cname + '", ' +\
1742 if self.at_module_scope:
1743 d_map_l.append(slabel + ': ' + '_0_' + self.modname + \
1744 "._m_" + uname + "[" + str(i) + "]")
1746 d_map_l.append(slabel + ': ' + "_m_" + \
1747 uname + "[" + str(i) + "]")
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, ", ")
1755 if self.at_module_scope:
1756 self.st.out(union_descriptor_at_module_scope,
1767 modname = self.modname)
1769 self.st.out(union_register_at_module_scope,
1771 modname = self.modname)
1773 self.st.out(union_descriptor,
1784 scope = dotName(fscopedName[:-1]))
1786 self.st.out(union_register, uname = uname)
1791 def visitUnionForward(self, node):
1792 if self.handleImported(node): return
1794 uname = mangle(node.identifier())
1796 if self.at_module_scope:
1797 self.st.out(forward_union_descr_at_module_scope,
1799 repoId = node.repoId(),
1800 modname = self.modname)
1802 self.st.out(forward_union_descr,
1804 repoId = node.repoId(),
1805 modname = self.modname)
1810 def visitEnum(self, node):
1811 if self.handleImported(node): return
1813 ename = mangle(node.identifier())
1814 self.st.out(enum_start, ename = ename)
1818 for item in node.enumerators():
1821 if self.at_module_scope:
1822 self.st.out(enum_item_at_module_scope,
1823 item = item.identifier(),
1824 eitem = mangle(item.identifier()),
1826 modname = self.modname)
1828 self.st.out(enum_item,
1829 item = item.identifier(),
1830 eitem = mangle(item.identifier()),
1833 if self.at_module_scope:
1834 elist.append(dotName(fixupScopedName(item.scopedName())))
1836 elist.append(mangle(item.identifier()))
1840 eitems = string.join(elist, ", ")
1842 if self.at_module_scope:
1843 self.st.out(enum_object_and_descriptor_at_module_scope,
1845 repoId = node.repoId(),
1847 modname = self.modname)
1849 self.st.out(enum_object_and_descriptor,
1851 repoId = node.repoId(),
1854 def visitNative(self, node):
1855 if self.handleImported(node): return
1857 sys.stderr.write(main.cmdname + \
1858 ": Warning: ignoring declaration of native " + \
1859 node.identifier() + "\n")
1861 def visitValueForward(self, node):
1862 if self.handleImported(node): return
1864 vname = mangle(node.identifier())
1866 self.st.out(value_forward_at_module_scope,
1867 vname=vname, repoId=node.repoId(), modname=self.modname)
1870 def visitValueBox(self, node):
1871 if self.handleImported(node): return
1873 boxname = mangle(node.identifier())
1874 boxdesc = typeToDescriptor(node.boxedType())
1876 self.st.out(valuebox, boxname=boxname, repoId=node.repoId(),
1877 boxdesc=boxdesc, modname=self.modname)
1880 def visitValueAbs(self, node):
1881 if self.handleImported(node): return
1883 vname = mangle(node.identifier())
1885 fscopedName = fixupScopedName(node.scopedName(), "")
1886 scopedname = dotName(fscopedName)
1890 for i in node.inherits():
1892 inheritl.append(dotName(fixupScopedName(i.scopedName())))
1894 inherits = string.join(inheritl, ", ")
1896 inherits = "_0_CORBA.ValueBase"
1898 self.st.out(valueabs_class,
1899 vname=vname, scopedname=scopedname, repoId=node.repoId(),
1900 inherits=inherits, modname=self.modname)
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())
1908 for d in node.declarations():
1911 self.currentScope.pop()
1912 self.at_module_scope = 1
1913 self.st.dec_indent()
1916 basedesc = "_0_CORBA.tcInternal.tv_null"
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)
1924 def visitValue(self, node):
1925 if self.handleImported(node): return
1927 vname = mangle(node.identifier())
1929 fscopedName = fixupScopedName(node.scopedName(), "")
1930 scopedname = dotName(fscopedName)
1934 for i in node.inherits():
1936 inheritl.append(dotName(fixupScopedName(i.scopedName())))
1939 inheritl = ["_0_CORBA.ValueBase"]
1942 for i in node.supports():
1944 sn = fixupScopedName(i.scopedName())
1945 sn[0] = sn[0] + "__POA"
1948 skeleton_opl.append(dn)
1950 inherits = string.join(inheritl, ", ")
1952 # Go up the chain of inherited interfaces, picking out the
1959 cin = cnode.inherits()
1962 i = cin[0].fullDecl()
1963 if not isinstance(i, idlast.Value):
1972 members.extend(i.statemembers())
1976 for i in range(len(members)):
1978 for d in member.declarators():
1979 set_argl.append("self.%s = args[%d]" %
1980 (mangle(d.identifier()),i))
1983 set_args = string.join(set_argl, "\n")
1987 if len(set_argl) == 1:
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)
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())
2003 for d in node.declarations():
2006 self.currentScope.pop()
2007 self.at_module_scope = 1
2008 self.st.dec_indent()
2011 # Skeleton operation declarations if necessary
2013 self.st.out(skeleton_methodmap, methodmap="{}")
2014 for i in skeleton_opl:
2015 self.st.out(skeleton_inheritmap, inheritclass=i)
2017 self.st.out(skeleton_set_skel, ifid=vname)
2019 # Register factory if no callables or factories
2020 register_factory = 1
2022 if not all_factories:
2025 if cnode.callables() or cnode.factories() or cnode.supports():
2026 register_factory = 0
2028 cin = cnode.inherits()
2033 if not isinstance(n, idlast.Value):
2034 register_factory = 0
2036 cnode = cin[0].fullDecl()
2038 if register_factory:
2039 self.st.out(value_register_factory, vname=vname)
2041 # If value supports some interfaces, output an objref class for it
2045 for i in node.supports():
2047 sn = fixupScopedName(i.scopedName())
2048 inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
2049 methodl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]) +
2052 inherits = string.join(inheritl, ", ")
2054 self.st.out(objref_class, ifid=vname, inherits=inherits)
2056 for inclass in inheritl:
2057 self.st.out(objref_inherit_init, inclass=inclass)
2059 methods = string.join(methodl, " + ")
2060 self.st.out(objref_methods, methods = methods)
2063 self.st.out(value_objref_register,
2064 ifid=vname, modname=self.modname)
2068 modifier = "_0_CORBA.VM_CUSTOM"
2069 elif node.truncatable():
2070 modifier = "_0_CORBA.VM_TRUNCATABLE"
2072 modifier = "_0_CORBA.VM_NONE"
2078 cin = cnode.inherits()
2083 if not isinstance(i, idlast.Value):
2085 if cnode.truncatable():
2086 sn = fixupScopedName(i.scopedName())
2087 tbasel.append(dotName(sn) + "._NP_RepositoryId")
2093 tbaseids = "(%s._NP_RepositoryId, %s)" % (vname,
2094 string.join(tbasel, ", "))
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))
2106 if basedesc is None:
2107 basedesc = "_0_CORBA.tcInternal.tv_null"
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(),
2115 if m.memberAccess() == 1:
2116 mlist.append("_0_CORBA.PRIVATE_MEMBER")
2118 mlist.append("_0_CORBA.PUBLIC_MEMBER")
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)
2128 if isinstance(node, idlast.Const) and \
2129 node.constKind() == idltype.tk_string and \
2130 node.identifier()[-7:] == "__doc__":
2131 return node.identifier()[:-7]
2136 if hasattr(node, "identifier"):
2137 return node.identifier()
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")
2147 class DocstringVisitor (idlvisitor.AstVisitor):
2148 def __init__(self, st):
2159 for nsn, dsn in self.docs:
2160 nsn = fixupScopedName(nsn)
2161 dsn = fixupScopedName(dsn)
2163 self.st.out("@node@.__doc__ = @doc@",
2164 node=dotName(nsn), doc=dotName(dsn))
2169 def visitAST(self, node):
2170 for n in node.declarations():
2171 if not output_inline and not n.mainFile(): continue
2176 for o in node.declarations():
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()))
2189 def visitModule(self, node):
2190 for n in node.definitions():
2193 if d == node.identifier():
2194 self.docs.append((node.scopedName(), n.scopedName()))
2197 for o in node.definitions():
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()))
2210 def visitInterface(self, node):
2211 for n in node.declarations():
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()))
2221 for o in node.declarations():
2223 self.docs.append((o.scopedName(), n.scopedName()))
2230 for o in node.callables():
2232 self.target_node = n
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()))
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():
2257 sn[-2] = "_set_" + n.identifier()
2258 self.docs.append((sn, self.target_node.scopedName()))
2262 class ExampleVisitor (idlvisitor.AstVisitor, idlvisitor.TypeVisitor):
2263 def __init__(self, st):
2267 def visitAST(self, node):
2268 for n in node.declarations():
2269 if not output_inline and not n.mainFile(): continue
2271 if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
2274 def visitModule(self, node):
2275 for n in node.definitions():
2276 if not output_inline and not n.mainFile(): continue
2278 if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
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)
2289 if self.first is None:
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
2299 # Inherited interface:
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.
2308 # Inherited interfaces:
2312 inheritance_note = ""
2314 for inh in node.inherits():
2315 iname = idlutil.ccolonName(inh.fullDecl().scopedName())
2316 inheritance_note = inheritance_note + " # %s\n" % iname
2318 self.st.out(example_classdef, ifname=ifname,
2319 ccname=ccname, skname=skname,
2320 inheritance_note = inheritance_note)
2322 for c in node.callables():
2324 if isinstance(c, idlast.Attribute):
2326 c.attrType().accept(self)
2327 attrtype = self.__result_type
2329 for attr in c.identifiers():
2331 signature = "attribute %s %s" % (attrtype, attr)
2334 signature = "readonly " + signature
2336 if not c.readonly():
2337 self.st.out(example_opdef,
2338 signature = signature,
2339 opname = "_set_" + attr,
2341 returnspec = "None")
2343 self.st.out(example_opdef,
2344 signature = signature,
2345 opname = "_get_" + attr,
2347 returnspec = "attribute value")
2354 c.returnType().accept(self)
2355 rettype = self.__result_type
2357 if c.returnType().kind() != idltype.tk_void:
2358 outnames.append("result")
2360 for p in c.parameters():
2362 innames.append(p.identifier())
2364 outnames.append(p.identifier())
2366 direction = {0:"in", 1:"out", 2:"inout"}[p.direction()]
2368 p.paramType().accept(self)
2369 siglist.append("%s %s %s" % (direction,
2373 signature = "%s %s(%s)" % (rettype, c.identifier(),
2374 string.join(siglist, ", "))
2377 args = ", " + string.join(innames, ", ")
2382 returnspec = string.join(outnames, ", ")
2386 self.st.out(example_opdef,
2387 signature = signature,
2388 opname = c.identifier(),
2390 returnspec = returnspec)
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"
2414 def visitBaseType(self, type):
2415 self.__result_type = self.ttsMap[type.kind()]
2417 def visitStringType(self, type):
2418 if type.bound() == 0:
2419 self.__result_type = "string"
2421 self.__result_type = "string<" + str(type.bound()) + ">"
2423 def visitWStringType(self, type):
2424 if type.bound() == 0:
2425 self.__result_type = "wstring"
2427 self.__result_type = "wstring<" + str(type.bound()) + ">"
2430 def visitDeclaredType(self, type):
2431 self.__result_type = idlutil.ccolonName(type.decl().scopedName())
2437 def operationToDescriptors(op):
2438 """Return the descriptors for an operation.
2440 Returns a tuple containing strings of (in descriptor, out
2441 descriptor, exception map, context list, contains values)
2448 if op.returnType() is not None and \
2449 op.returnType().kind() != idltype.tk_void:
2451 outdl.append(typeToDescriptor(op.returnType()))
2452 cv = idltype.containsValueType(op.returnType())
2454 # Make the lists of in and out parameters
2455 for p in op.parameters():
2458 indl.append(typeToDescriptor(p.paramType()))
2460 outdl.append(typeToDescriptor(p.paramType()))
2462 cv = cv or idltype.containsValueType(p.paramType())
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("")
2468 inds = "(" + string.join(indl, ", ") + ")"
2472 outds = "(" + string.join(outdl, ", ") + ")"
2477 for e in op.raises():
2478 sn = fixupScopedName(e.scopedName())
2480 edesc = dotName(sn[:-1] + [ "_d_" + sn[-1]])
2481 excl.append(ename + "._NP_RepositoryId: " + edesc)
2484 excs = "{" + string.join(excl, ", ") + "}"
2489 ctxts = "[" + string.join(map(repr, op.contexts()), ", ") + "]"
2493 return inds, outds, excs, ctxts, cv
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"
2516 idltype.tk_longdouble: "long double",
2519 def typeToDescriptor(tspec, from_scope=[], is_typedef=0):
2520 if hasattr(tspec, "python_desc"):
2521 return tspec.python_desc
2523 if ttdMap.has_key(tspec.kind()):
2524 tspec.python_desc = ttdMap[tspec.kind()]
2525 return tspec.python_desc
2527 if unsupportedMap.has_key(tspec.kind()):
2528 error_exit("omniORBpy does not support the %s type." %
2529 unsupportedMap[tspec.kind()])
2531 if tspec.kind() == idltype.tk_string:
2532 ret = "(omniORB.tcInternal.tv_string," + str(tspec.bound()) + ")"
2534 elif tspec.kind() == idltype.tk_wstring:
2535 ret = "(omniORB.tcInternal.tv_wstring," + str(tspec.bound()) + ")"
2537 elif tspec.kind() == idltype.tk_sequence:
2538 ret = "(omniORB.tcInternal.tv_sequence, " + \
2539 typeToDescriptor(tspec.seqType(), from_scope) + \
2540 ", " + str(tspec.bound()) + ")"
2542 elif tspec.kind() == idltype.tk_fixed:
2543 ret = "(omniORB.tcInternal.tv_fixed, " + \
2544 str(tspec.digits()) + ", " + str(tspec.scale()) + ")"
2546 elif tspec.kind() == idltype.tk_alias:
2547 sn = fixupScopedName(tspec.scopedName())
2549 return 'omniORB.typeCodeMapping["%s"]._d' % tspec.decl().repoId()
2551 return 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
2554 ret = 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
2556 tspec.python_desc = ret
2560 def typeAndDeclaratorToDescriptor(tspec, decl, from_scope, is_typedef=0):
2561 desc = typeToDescriptor(tspec, from_scope, is_typedef)
2563 if len(decl.sizes()) > 0:
2564 sizes = decl.sizes()[:]
2567 desc = "(omniORB.tcInternal.tv_array, " + \
2568 desc + ", " + str(size) + ")"
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, ".")
2578 def dotName(scopedName, our_scope=[]):
2579 if scopedName[:len(our_scope)] == our_scope:
2580 l = map(mangle, scopedName[len(our_scope):])
2582 l = map(mangle, scopedName)
2583 return string.join(l, ".")
2586 if keyword.iskeyword(name): return "_" + name
2588 # None is a pseudo-keyword that cannot be assigned to.
2589 if name == "None": return "_None"
2593 def fixupScopedName(scopedName, prefix="_0_"):
2594 """Add a prefix and _GlobalIDL to the front of a ScopedName if necessary"""
2597 decl = idlast.findDecl([scopedName[0]])
2598 except idlast.DeclNotFound:
2601 if isinstance(decl, idlast.Module):
2602 scopedName = [prefix + mangle(scopedName[0])] + scopedName[1:]
2604 scopedName = [prefix + global_module] + scopedName
2607 def valueToString(val, kind, scope=[]):
2608 if kind == idltype.tk_enum:
2609 return dotName(fixupScopedName(val.scopedName()), scope)
2611 elif kind in [idltype.tk_string, idltype.tk_char]:
2612 return '"' + idlutil.escapifyString(val) + '"'
2614 elif kind == idltype.tk_wstring:
2615 return 'u"' + idlutil.escapifyWString(val) + '"'
2617 elif kind == idltype.tk_wchar:
2618 return 'u"' + idlutil.escapifyWString([val]) + '"'
2620 elif kind == idltype.tk_long and val == -2147483647 - 1:
2621 return "-2147483647 - 1"
2623 elif kind in [idltype.tk_float, idltype.tk_double, idltype.tk_longdouble]:
2624 return idlutil.reprFloat(val)
2626 elif kind == idltype.tk_fixed:
2627 return "CORBA.fixed('" + val + "')"
2632 __translate_table = string.maketrans(" -.,", "____")
2634 def outputFileName(idlname):
2635 global __translate_table
2636 return string.translate(os.path.basename(idlname), __translate_table)
2638 def checkStubPackage(package):
2639 """Check the given package name for use as a stub directory
2641 Make sure all fragments of the package name are directories, or
2642 create them. Make __init__.py files in all directories."""
2644 if len(package) == 0:
2647 if package[-1] == ".":
2648 package = package[:-1]
2651 for name in string.split(package, "."):
2652 path = os.path.join(path, name)
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)
2662 error_exit('Cannot create directory "%s".\n' % path)
2664 initfile = os.path.join(path, "__init__.py")
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.' %
2672 open(initfile, "w").write("# omniORB stub directory\n")
2674 error_exit('Cannot create "%s".' % initfile)
2677 def updateModules(modules, pymodule):
2678 """Create or update the Python modules corresponding to the IDL
2681 checkStubPackage(module_package)
2683 poamodules = map(skeletonModuleName, modules)
2685 real_updateModules(modules, pymodule)
2686 real_updateModules(poamodules, pymodule)
2689 def real_updateModules(modules, pymodule):
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")
2697 if not os.path.exists(modpath):
2699 os.makedirs(modpath)
2701 error_exit('Cannot create path "%s".' % modpath)
2703 # Make the __init__.py file if it does not already exist
2704 if not os.path.exists(modfile):
2706 f = open(modfile, "w")
2708 error_exit('Cannot create "%s".' % modfile)
2710 st = output.Stream(f, 4)
2712 st.out(pymodule_template, module=module, package=module_package)
2717 if not os.path.isfile(modfile):
2718 error_exit('Output error: "%s" exists but is not a file.' %
2721 # Insert the import line for the current IDL file
2723 inf = open(modfile, "r")
2725 error_exit('Cannot open "%s" for reading.' % modfile)
2728 outf = open(tmpfile, "w")
2730 error_exit('Cannot open "%s" for writing.' % tmpfile)
2733 while line[:7] != "# ** 1.":
2734 line = inf.readline()
2736 error_exit('Output error: "%s" ended before I found a '
2738 'Have you left behind some files from a '
2739 'different Python ORB?' % modfile)
2744 outputline = "import " + pymodule + "\n"
2747 line = inf.readline()
2749 error_exit('Output error: "%s" ended while I was '
2750 'looking at imports.' % modfile)
2754 if line == outputline:
2758 outf.write(outputline)
2762 # Output the rest of the file
2764 line = inf.readline()
2773 error_exit('Cannot remove "%s".' % modfile)
2775 os.rename(tmpfile, modfile)
2777 error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))
2779 # Go round again, importing sub-modules from their parent modules
2780 for module in modules:
2781 modlist = string.split(module, ".")
2783 if len(modlist) == 1:
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")
2792 # Insert the import line for the sub-module
2794 inf = open(modfile, "r")
2796 error_exit('Cannot open "%s" for reading.' % modfile)
2799 outf = open(tmpfile, "w")
2801 error_exit('Cannot open "%s" for writing.' % tmpfile)
2804 while line[:7] != "# ** 2.":
2805 line = inf.readline()
2807 error_exit('Output error: "%s" ended before I found a '
2809 'Have you left behind some files from a '
2810 'different Python ORB?' % modfile)
2815 outputline = "import " + submod + "\n"
2818 line = inf.readline()
2820 error_exit('Output error: "%s" ended while I was '
2821 'looking at imports.' % modfile)
2825 if line == outputline:
2829 outf.write(outputline)
2833 # Output the rest of the file
2835 line = inf.readline()
2844 error_exit('Cannot remove "%s".' % modfile)
2846 os.rename(tmpfile, modfile)
2848 error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))