Back to index

salome-paravis  6.5.0
pythonIDL.py
Go to the documentation of this file.
00001 # -*- python -*-
00002 #                           Package   : omniidl
00003 # python.py                 Created on: 1999/10/29
00004 #                        Author    : Duncan Grisby (dpg1)
00005 #
00006 #    Copyright (C) 1999 AT&T Laboratories Cambridge
00007 #
00008 #  This file is part of omniidl.
00009 #
00010 #  omniidl is free software; you can redistribute it and/or modify it
00011 #  under the terms of the GNU General Public License as published by
00012 #  the Free Software Foundation; either version 2 of the License, or
00013 #  (at your option) any later version.
00014 #
00015 #  This program is distributed in the hope that it will be useful,
00016 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
00017 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00018 #  General Public License for more details.
00019 #
00020 #  You should have received a copy of the GNU General Public License
00021 #  along with this program; if not, write to the Free Software
00022 #  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
00023 #  02111-1307, USA.
00024 #
00025 # Description:
00026 #   
00027 #   Back-end for Python
00028 
00029 # $Id: pythonIDL.py,v 1.2 2009-12-29 07:48:05 vsr Exp $
00030 # $Log: pythonIDL.py,v $
00031 # Revision 1.2  2009-12-29 07:48:05  vsr
00032 # Merge from BR_PARAVIS_DEV 29Dec09
00033 #
00034 # Revision 1.1.2.4  2009-11-18 15:56:23  vtn
00035 # Trace support
00036 #
00037 # Revision 1.1.2.3  2009-11-17 12:15:43  vsv
00038 # *** empty log message ***
00039 #
00040 # Revision 1.1.2.2  2009-11-05 14:57:23  vtn
00041 # Added return array support.
00042 #
00043 # Revision 1.1.2.1  2009-11-03 13:14:05  vtn
00044 # Added pathonIDL back-end for omniidl.
00045 #
00046 # Revision 1.33.2.13  2006/10/11 17:44:14  dgrisby
00047 # None is not a keyword, but it cannot be assigned to.
00048 #
00049 # Revision 1.33.2.12  2006/09/29 16:48:03  dgrisby
00050 # Stub changes broke use of package prefix. Thanks Teemu Torma.
00051 #
00052 # Revision 1.33.2.11  2006/09/07 15:28:57  dgrisby
00053 # Remove obsolete check for presence of omniORB.StructBase.
00054 #
00055 # Revision 1.33.2.10  2006/06/21 14:46:26  dgrisby
00056 # Invalid generated code for structs nested inside valuetypes.
00057 #
00058 # Revision 1.33.2.9  2006/01/19 17:28:44  dgrisby
00059 # Merge from omnipy2_develop.
00060 #
00061 # Revision 1.33.2.8  2006/01/18 19:25:13  dgrisby
00062 # Bug inheriting a valuetype from a typedef.
00063 #
00064 # Revision 1.33.2.7  2005/07/29 11:21:36  dgrisby
00065 # Fix long-standing problem with module re-opening by #included files.
00066 #
00067 # Revision 1.33.2.6  2005/01/07 00:22:34  dgrisby
00068 # Big merge from omnipy2_develop.
00069 #
00070 # Revision 1.33.2.5  2004/03/24 22:28:50  dgrisby
00071 # TypeCodes / truncation for inherited state members were broken.
00072 #
00073 # Revision 1.33.2.4  2004/02/16 10:14:18  dgrisby
00074 # Use stream based copy for local calls.
00075 #
00076 # Revision 1.33.2.3  2003/07/10 22:13:25  dgrisby
00077 # Abstract interface support.
00078 #
00079 # Revision 1.33.2.2  2003/05/20 17:10:24  dgrisby
00080 # Preliminary valuetype support.
00081 #
00082 # Revision 1.33.2.1  2003/03/23 21:51:56  dgrisby
00083 # New omnipy3_develop branch.
00084 #
00085 # Revision 1.29.2.14  2002/11/25 21:31:09  dgrisby
00086 # Friendly error messages with file errors, remove code to kill POA
00087 # modules from pre-1.0.
00088 #
00089 # Revision 1.29.2.13  2002/07/04 13:14:52  dgrisby
00090 # Bug with string escapes in Windows filenames.
00091 #
00092 # Revision 1.29.2.12  2002/05/27 01:02:37  dgrisby
00093 # Fix bug with scope lookup in generated code. Fix TypeCode clean-up bug.
00094 #
00095 # Revision 1.29.2.11  2002/01/18 17:41:17  dpg1
00096 # Support for "docstrings" in IDL.
00097 #
00098 # Revision 1.29.2.10  2002/01/18 15:49:45  dpg1
00099 # Context support. New system exception construction. Fix None call problem.
00100 #
00101 # Revision 1.29.2.9  2001/12/04 12:17:08  dpg1
00102 # Incorrect generated code for fixed constants.
00103 #
00104 # Revision 1.29.2.8  2001/08/29 11:57:16  dpg1
00105 # Const fixes.
00106 #
00107 # Revision 1.29.2.7  2001/06/15 10:59:26  dpg1
00108 # Apply fixes from omnipy1_develop.
00109 #
00110 # Revision 1.29.2.6  2001/06/13 11:29:04  dpg1
00111 # Proper omniidl support for wchar/wstring constants.
00112 #
00113 # Revision 1.29.2.5  2001/05/10 15:16:03  dpg1
00114 # Big update to support new omniORB 4 internals.
00115 #
00116 # Revision 1.29.2.4  2001/04/09 15:22:16  dpg1
00117 # Fixed point support.
00118 #
00119 # Revision 1.29.2.3  2000/11/22 14:43:58  dpg1
00120 # Support code set conversion and wchar/wstring.
00121 #
00122 # Revision 1.29.2.2  2000/11/01 15:29:01  dpg1
00123 # Support for forward-declared structs and unions
00124 # RepoIds in indirections are now resolved at the time of use
00125 #
00126 # Revision 1.29.2.1  2000/10/13 13:55:30  dpg1
00127 # Initial support for omniORB 4.
00128 #
00129 # Revision 1.29  2000/10/02 17:34:58  dpg1
00130 # Merge for 1.2 release
00131 #
00132 # Revision 1.27.2.3  2000/08/22 11:52:28  dpg1
00133 # Generate inherited classes for typedef to struct/union.
00134 #
00135 # Revision 1.27.2.2  2000/08/07 09:19:24  dpg1
00136 # Long long support
00137 #
00138 # Revision 1.27.2.1  2000/07/18 15:31:29  dpg1
00139 # Bug with inheritance from typedef
00140 #
00141 # Revision 1.27  2000/07/12 14:32:13  dpg1
00142 # New no_package option to omniidl backend
00143 #
00144 # Revision 1.26  2000/06/28 12:47:48  dpg1
00145 # Proper error messages for unsupported IDL constructs.
00146 #
00147 # Revision 1.25  2000/06/27 15:01:48  dpg1
00148 # Change from POA_M to M__POA mapping.
00149 # Global module only built if necessary.
00150 #
00151 # Revision 1.24  2000/03/29 10:15:47  dpg1
00152 # Exceptions now more closely follow the interface of
00153 # exceptions.Exception.
00154 #
00155 # Revision 1.23  2000/03/17 12:28:09  dpg1
00156 # Comma missing in nested union descriptor.
00157 #
00158 # Revision 1.22  2000/03/03 17:41:28  dpg1
00159 # Major reorganisation to support omniORB 3.0 as well as 2.8.
00160 #
00161 # Revision 1.21  2000/02/23 10:20:52  dpg1
00162 # Bug in descriptors for single-item enums.
00163 #
00164 # Revision 1.20  2000/01/04 15:29:41  dpg1
00165 # Fixes to modules generated within a package.
00166 #
00167 # Revision 1.19  1999/12/21 16:06:15  dpg1
00168 # DOH!  global= not module= !
00169 #
00170 # Revision 1.18  1999/12/21 16:05:11  dpg1
00171 # New module= option.
00172 #
00173 # Revision 1.17  1999/12/17 11:39:52  dpg1
00174 # New arguments to put modules and stubs in a specified package.
00175 #
00176 # Revision 1.16  1999/12/15 11:32:42  dpg1
00177 # -Wbinline option added.
00178 #
00179 # Revision 1.15  1999/12/09 14:12:55  dpg1
00180 # invokeOp() calls now on a single line. typedef now generates a class
00181 # to be passed to CORBA.id().
00182 #
00183 # Revision 1.14  1999/12/07 15:35:14  dpg1
00184 # Bug in currentScope handling.
00185 #
00186 # Revision 1.13  1999/11/30 10:41:20  dpg1
00187 # Back-ends can now have their own usage string.
00188 #
00189 # Revision 1.12  1999/11/25 11:49:31  dpg1
00190 # Minor version number bumped since server-side _is_a() required an
00191 # incompatible change.
00192 #
00193 # Revision 1.11  1999/11/25 11:21:36  dpg1
00194 # Proper support for server-side _is_a().
00195 #
00196 # Revision 1.10  1999/11/19 11:03:49  dpg1
00197 # Extremely important spelling correction in a comment. :-)
00198 #
00199 # Revision 1.9  1999/11/12 15:53:48  dpg1
00200 # New functions omniORB.importIDL() and omniORB.importIDLString().
00201 #
00202 # Revision 1.8  1999/11/11 15:55:29  dpg1
00203 # Python back-end interface now supports valuetype declarations.
00204 # Back-ends still don't support them, though.
00205 #
00206 # Revision 1.7  1999/11/10 16:08:22  dpg1
00207 # Some types weren't registered properly.
00208 #
00209 # Revision 1.6  1999/11/04 11:46:12  dpg1
00210 # Now uses our own version of the GNU C preprocessor.
00211 #
00212 # Revision 1.5  1999/11/02 12:17:26  dpg1
00213 # Top-level module name now has a prefix of _0_ to avoid clashes with
00214 # names of nested declarations.
00215 #
00216 # Revision 1.4  1999/11/02 10:54:01  dpg1
00217 # Two small bugs in union generation.
00218 #
00219 # Revision 1.3  1999/11/02 10:01:46  dpg1
00220 # Minor fixes.
00221 #
00222 # Revision 1.2  1999/11/01 20:19:55  dpg1
00223 # Support for union switch types declared inside the switch statement.
00224 #
00225 # Revision 1.1  1999/11/01 16:40:11  dpg1
00226 # First revision with new front-end.
00227 #
00228 
00229 """omniORB Python bindings"""
00230 
00231 from omniidl import idlast, idltype, idlutil, idlvisitor, output, main
00232 import sys, string, types, os.path, keyword
00233 
00234 cpp_args = ["-D__OMNIIDL_PYTHON__"]
00235 usage_string = """\
00236   -Wbstdout       Send generated stubs to stdout rather than a file
00237   -Wbinline       Output stubs for #included files in line with the main file
00238   -Wbfactories    Register value factories for all valuetypes
00239   -Wbpackage=p    Put both Python modules and stub files in package p
00240   -Wbmodules=p    Put Python modules in package p
00241   -Wbstubs=p      Put stub files in package p
00242   -Wbextern=f:p   Assume Python stub file for file f is in package p.
00243   -Wbglobal=g     Module to use for global IDL scope (default _GlobalIDL)"""
00244 
00245 #""" Uncomment this line to get syntax highlighting on the output strings
00246 
00247 # Output strings
00248 
00249 pymodule_template = """\
00250 # DO NOT EDIT THIS FILE!
00251 #
00252 # Python module @module@ generated by omniidl
00253 
00254 import omniORB
00255 omniORB.updateModule("@package@@module@")
00256 
00257 # ** 1. Stub files contributing to this module
00258 
00259 # ** 2. Sub-modules
00260 
00261 # ** 3. End"""
00262 
00263 file_start = """\
00264 # Python stubs generated by omniidl from @filename@
00265 
00266 import omniORB, _omnipy
00267 from types import *
00268 from omniORB import CORBA, PortableServer
00269 _0_CORBA = CORBA
00270 
00271 _omnipy.checkVersion(3,0, __file__)
00272 """
00273 
00274 file_end = """\
00275 _exported_modules = ( @export_string@)
00276 
00277 # The end."""
00278 
00279 module_start = """
00280 #
00281 # Start of module "@sname@"
00282 #
00283 __name__ = "@package@@sname@"
00284 _0_@sname@ = omniORB.openModule("@package@@sname@", r"@filename@")
00285 _0_@s_sname@ = omniORB.openModule("@package@@s_sname@", r"@filename@")
00286 """
00287 
00288 module_end = """
00289 #
00290 # End of module "@sname@"
00291 #
00292 __name__ = "@package@@modname@"
00293 """
00294 
00295 import_idl_file = """\
00296 # #include "@idlfile@"
00297 import @ifilename@"""
00298 
00299 open_imported_module_name = """\
00300 _0_@imodname@ = omniORB.openModule("@package@@imodname@")
00301 _0_@s_imodname@ = omniORB.openModule("@package@@s_imodname@")"""
00302 
00303 forward_interface = """\
00304 
00305 # @abstract@interface @ifid@;
00306 _0_@modname@._d_@ifid@ = (omniORB.tcInternal.@tvkind@, "@repoId@", "@ifid@")
00307 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@ifid@"""
00308 
00309 
00310 interface_class = """\
00311 
00312 # @abstract@interface @ifid@
00313 _0_@modname@._d_@ifid@ = (omniORB.tcInternal.@tvkind@, "@repoId@", "@ifid@")
00314 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@ifid@
00315 _0_@modname@.@ifid@ = omniORB.newEmptyClass()
00316 class @ifid@ @inherits@:
00317     _NP_RepositoryId = _0_@modname@._d_@ifid@[1]
00318 
00319     def __init__(self, *args, **kw):
00320         raise RuntimeError("Cannot construct objects of this type.")
00321 
00322     _nil = CORBA.Object._nil
00323 """
00324 
00325 interface_descriptor = """
00326 _0_@modname@.@ifid@ = @ifid@
00327 _0_@modname@._tc_@ifid@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@ifid@)
00328 omniORB.registerType(@ifid@._NP_RepositoryId, _0_@modname@._d_@ifid@, _0_@modname@._tc_@ifid@)"""
00329 
00330 callables_header = """
00331 # @ifid@ operations and attributes"""
00332 
00333 attribute_get_descriptor = """\
00334 @ifid@._d__get_@attr@ = ((),(@descr@,),None)"""
00335 
00336 attribute_set_descriptor = """\
00337 @ifid@._d__set_@attr@ = ((@descr@,),(),None)"""
00338 
00339 operation_descriptor = """\
00340 @ifid@._d_@opname@ = (@inds@, @outds@, @excs@@options@)"""
00341 
00342 objref_class = """\
00343 
00344 # @ifid@ object reference
00345 class _objref_@ifid@ (@inherits@):
00346     _NP_RepositoryId = @ifid@._NP_RepositoryId
00347 
00348     def __init__(self):"""
00349 
00350 objref_inherit_init = """\
00351         @inclass@.__init__(self)"""
00352 
00353 objref_object_init = """\
00354         CORBA.Object.__init__(self)"""
00355 
00356 objref_attribute_get = """
00357     def _get_@attr@(self, *args):
00358         return _omnipy.invoke(self, "_get_@attr@", _0_@modname@.@ifid@._d__get_@attr@, args)"""
00359 objref_attribute_set = """
00360     def _set_@attr@(self, *args):
00361         return _omnipy.invoke(self, "_set_@attr@", _0_@modname@.@ifid@._d__set_@attr@, args)"""
00362 objref_operation = """
00363     def @opname@(self, *args):
00364         return _omnipy.invoke(self, "@r_opname@", _0_@modname@.@ifid@._d_@opname@, args)"""
00365 objref_methods = """
00366     __methods__ = @methods@"""
00367 
00368 objref_register = """
00369 omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
00370 _0_@modname@._objref_@ifid@ = _objref_@ifid@
00371 del @ifid@, _objref_@ifid@"""
00372 
00373 skeleton_class = """
00374 # @ifid@ skeleton
00375 __name__ = "@package@@s_modname@"
00376 class @ifid@ (@inherits@):
00377     _NP_RepositoryId = _0_@modname@.@ifid@._NP_RepositoryId
00378 """
00379 
00380 skeleton_methodmap = """
00381     _omni_op_d = @methodmap@"""
00382 
00383 skeleton_inheritmap = """\
00384     _omni_op_d.update(@inheritclass@._omni_op_d)"""
00385 
00386 skeleton_end = """
00387 @ifid@._omni_skeleton = @ifid@
00388 _0_@s_modname@.@ifid@ = @ifid@
00389 omniORB.registerSkeleton(@ifid@._NP_RepositoryId, @ifid@)
00390 del @ifid@
00391 __name__ = "@package@@modname@"\
00392 """
00393 
00394 skeleton_set_skel = """
00395 @ifid@._omni_skeleton = @ifid@
00396 """
00397 
00398 constant_at_module_scope = """\
00399 _0_@modname@.@cname@ = @value@"""
00400 
00401 constant = """\
00402 @cname@ = @value@"""
00403 
00404 typedef_header = """\
00405 
00406 # typedef ... @tdname@
00407 class @tdname@:
00408     _NP_RepositoryId = "@repoId@"
00409     def __init__(self, *args, **kw):
00410         raise RuntimeError("Cannot construct objects of this type.")"""
00411 
00412 typedef_struct_union_header = """\
00413 
00414 # typedef ... @tdname@
00415 class @tdname@ (@parent@):
00416     _NP_RepositoryId = "@repoId@"
00417 """
00418 
00419 typedef_fixed_header = """\
00420 # typedef ... @tdname@
00421 @tdname@ = omniORB.fixedConstructor("@repoId@", @digits@, @scale@)"""
00422 
00423 typedef_at_module_scope = """\
00424 _0_@modname@.@tdname@ = @tdname@
00425 _0_@modname@._d_@tdname@  = @desc@
00426 _0_@modname@._ad_@tdname@ = (omniORB.tcInternal.tv_alias, @tdname@._NP_RepositoryId, "@tdname@", @tddesc@)
00427 _0_@modname@._tc_@tdname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._ad_@tdname@)
00428 omniORB.registerType(@tdname@._NP_RepositoryId, _0_@modname@._ad_@tdname@, _0_@modname@._tc_@tdname@)
00429 del @tdname@"""
00430 
00431 typedef = """\
00432 _d_@tdname@  = @desc@
00433 _ad_@tdname@ = (omniORB.tcInternal.tv_alias, @tdname@._NP_RepositoryId, "@tdname@", @tddesc@)
00434 _tc_@tdname@ = omniORB.tcInternal.createTypeCode(_ad_@tdname@)
00435 omniORB.registerType(@tdname@._NP_RepositoryId, _ad_@tdname@, _tc_@tdname@)"""
00436 
00437 forward_struct_descr_at_module_scope = """
00438 # Forward struct @sname@
00439 _0_@modname@._d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00440 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@sname@"""
00441 
00442 forward_struct_descr = """
00443 # Forward struct @sname@
00444 _d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00445 omniORB.typeMapping["@repoId@"] = _d_@sname@"""
00446 
00447 recursive_struct_descr_at_module_scope = """
00448 # Recursive struct @sname@
00449 _0_@modname@._d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00450 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@sname@"""
00451 
00452 recursive_struct_descr = """
00453 # Recursive struct @sname@
00454 _d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00455 _0_@scope@._d_@sname@ = _d_@sname@
00456 omniORB.typeMapping["@repoId@"] = _d_@sname@"""
00457 
00458 struct_class = """
00459 # struct @sname@
00460 _0_@scopedname@ = omniORB.newEmptyClass()
00461 class @sname@ (omniORB.StructBase):
00462     _NP_RepositoryId = "@repoId@"
00463 """
00464 
00465 struct_class_name = """\
00466     _NP_ClassName = "@cname@"
00467 """
00468 
00469 struct_class_init = """\
00470     def __init__(self@mnames@):"""
00471 
00472 struct_init_member = """\
00473         self.@mname@ = @mname@"""
00474 
00475 struct_descriptor_at_module_scope = """\
00476 
00477 _0_@modname@.@sname@ = @sname@
00478 _0_@modname@._d_@sname@  = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
00479 
00480 struct_register_at_module_scope = """\
00481 _0_@modname@._tc_@sname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@sname@)
00482 omniORB.registerType(@sname@._NP_RepositoryId, _0_@modname@._d_@sname@, _0_@modname@._tc_@sname@)
00483 del @sname@"""
00484 
00485 struct_descriptor = """\
00486 
00487 _d_@sname@  = _0_@scope@._d_@sname@ = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
00488 
00489 struct_register = """\
00490 _tc_@sname@ = omniORB.tcInternal.createTypeCode(_d_@sname@)
00491 omniORB.registerType(@sname@._NP_RepositoryId, _d_@sname@, _tc_@sname@)"""
00492 
00493 struct_module_descriptors = """
00494 _0_@modname@._d_@sname@  = _d_@sname@
00495 _0_@modname@._tc_@sname@ = _tc_@sname@
00496 del @sname@, _d_@sname@, _tc_@sname@"""
00497 
00498 exception_class = """\
00499 
00500 # exception @sname@
00501 _0_@scopedname@ = omniORB.newEmptyClass()
00502 class @sname@ (CORBA.UserException):
00503     _NP_RepositoryId = "@repoId@"
00504 """
00505 
00506 exception_class_init = """\
00507     def __init__(self@mnames@):
00508         CORBA.UserException.__init__(self@mnames@)"""
00509 
00510 exception_init_member = """\
00511         self.@mname@ = @mname@"""
00512 
00513 exception_descriptor_at_module_scope = """\
00514 
00515 _0_@modname@.@sname@ = @sname@
00516 _0_@modname@._d_@sname@  = (omniORB.tcInternal.tv_except, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)
00517 _0_@modname@._tc_@sname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@sname@)
00518 omniORB.registerType(@sname@._NP_RepositoryId, _0_@modname@._d_@sname@, _0_@modname@._tc_@sname@)
00519 del @sname@"""
00520 
00521 exception_descriptor = """\
00522 
00523 _d_@sname@  = (omniORB.tcInternal.tv_except, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)
00524 _tc_@sname@ = omniORB.tcInternal.createTypeCode(_d_@sname@)
00525 omniORB.registerType(@sname@._NP_RepositoryId, _d_@sname@, _tc_@sname@)"""
00526 
00527 forward_union_descr_at_module_scope = """
00528 # Forward union @uname@
00529 _0_@modname@._d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00530 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@uname@"""
00531 
00532 forward_union_descr = """
00533 # Forward union @uname@
00534 _d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00535 omniORB.typeMapping["@repoId@"] = _d_@uname@"""
00536 
00537 recursive_union_descr_at_module_scope = """
00538 # Recursive union @uname@
00539 _0_@modname@._d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00540 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@uname@"""
00541 
00542 recursive_union_descr = """
00543 # Recursive union @uname@
00544 _d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00545 _0_@scope@._d_@uname@ = _d_@uname@
00546 omniORB.typeMapping["@repoId@"] = _d_@uname@"""
00547 
00548 union_class = """
00549 # union @uname@
00550 _0_@scopedname@ = omniORB.newEmptyClass()
00551 class @uname@ (omniORB.Union):
00552     _NP_RepositoryId = "@repoId@"\
00553 """
00554 
00555 union_class_name = """\
00556     _NP_ClassName = "@cname@"
00557 """
00558 
00559 union_descriptor_at_module_scope = """
00560 _0_@modname@.@uname@ = @uname@
00561 
00562 @uname@._m_to_d = {@m_to_d@}
00563 @uname@._d_to_m = {@d_to_m@}
00564 @uname@._def_m  = @def_m@
00565 @uname@._def_d  = @def_d@
00566 
00567 _0_@modname@._m_@uname@  = (@m_un@,)
00568 _0_@modname@._d_@uname@  = (omniORB.tcInternal.tv_union, @uname@, @uname@._NP_RepositoryId, "@uname@", @stype@, @defpos@, _0_@modname@._m_@uname@, @m_def@, {@d_map@})"""
00569 
00570 union_register_at_module_scope = """\
00571 _0_@modname@._tc_@uname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@uname@)
00572 omniORB.registerType(@uname@._NP_RepositoryId, _0_@modname@._d_@uname@, _0_@modname@._tc_@uname@)
00573 del @uname@"""
00574 
00575 union_descriptor = """
00576 @uname@._m_to_d = {@m_to_d@}
00577 @uname@._d_to_m = {@d_to_m@}
00578 @uname@._def_m  = @def_m@
00579 @uname@._def_d  = @def_d@
00580 
00581 _m_@uname@  = (@m_un@,)
00582 _d_@uname@  = _0_@scope@._d_@uname@ = (omniORB.tcInternal.tv_union, @uname@, @uname@._NP_RepositoryId, "@uname@", @stype@, @defpos@, _m_@uname@, @m_def@, {@d_map@})"""
00583 
00584 union_register = """\
00585 _tc_@uname@ = omniORB.tcInternal.createTypeCode(_d_@uname@)
00586 omniORB.registerType(@uname@._NP_RepositoryId, _d_@uname@, _tc_@uname@)"""
00587 
00588 
00589 enum_start = """
00590 # enum @ename@\
00591 """
00592 
00593 enum_item_at_module_scope = """\
00594 _0_@modname@.@eitem@ = omniORB.EnumItem("@item@", @eval@)"""
00595 
00596 enum_object_and_descriptor_at_module_scope = """\
00597 _0_@modname@.@ename@ = omniORB.Enum("@repoId@", (@eitems@,))
00598 
00599 _0_@modname@._d_@ename@  = (omniORB.tcInternal.tv_enum, _0_@modname@.@ename@._NP_RepositoryId, "@ename@", _0_@modname@.@ename@._items)
00600 _0_@modname@._tc_@ename@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@ename@)
00601 omniORB.registerType(_0_@modname@.@ename@._NP_RepositoryId, _0_@modname@._d_@ename@, _0_@modname@._tc_@ename@)"""
00602 
00603 enum_item = """\
00604 @eitem@ = omniORB.EnumItem("@item@", @eval@)"""
00605 
00606 enum_object_and_descriptor = """\
00607 @ename@ = omniORB.Enum("@repoId@", (@eitems@,))
00608 
00609 _d_@ename@  = (omniORB.tcInternal.tv_enum, @ename@._NP_RepositoryId, "@ename@", @ename@._items)
00610 _tc_@ename@ = omniORB.tcInternal.createTypeCode(_d_@ename@)
00611 omniORB.registerType(@ename@._NP_RepositoryId, _d_@ename@, _tc_@ename@)"""
00612 
00613 
00614 value_forward_at_module_scope = """\
00615 # forward valuetype @vname@
00616 _0_@modname@._d_@vname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00617 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@vname@
00618 """
00619 
00620 value_class = """
00621 # valuetype @vname@
00622 _0_@modname@._d_@vname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
00623 omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@vname@
00624 _0_@modname@.@vname@ = omniORB.newEmptyClass()
00625 
00626 class @vname@ (@inherits@):
00627     _NP_RepositoryId = "@repoId@"
00628 
00629     def __init__(self, *args, **kwargs):
00630         if args:
00631             if len(args) != @arglen@:
00632                 raise TypeError("@vname@() takes @arglen@ argument@s@ "
00633                                 "(%d given)" % len(args))
00634             @set_args@
00635         if kwargs:
00636             self.__dict__.update(kwargs)
00637 """
00638 
00639 valueabs_class = """\
00640 class @vname@ (@inherits@):
00641     _NP_RepositoryId = "@repoId@"
00642 
00643     def __init__(self, *args, **kwargs):
00644         raise RuntimeError("Cannot construct objects of this type.")
00645 """
00646 
00647 value_register_factory = """\
00648 omniORB.registerValueFactory(@vname@._NP_RepositoryId, @vname@)
00649 """
00650 
00651 value_descriptor_at_module_scope = """\
00652 _0_@modname@.@vname@ = @vname@
00653 _0_@modname@._d_@vname@  = (omniORB.tcInternal.tv_value, @vname@, @vname@._NP_RepositoryId, "@vname@", @modifier@, @tbaseids@, @basedesc@, @mdescs@)
00654 _0_@modname@._tc_@vname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@vname@)
00655 omniORB.registerType(@vname@._NP_RepositoryId, _0_@modname@._d_@vname@, _0_@modname@._tc_@vname@)
00656 del @vname@
00657 """
00658 
00659 value_objref_register = """
00660 omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
00661 _0_@modname@._objref_@ifid@ = _objref_@ifid@
00662 del _objref_@ifid@"""
00663 
00664 
00665 valuebox = """\
00666 
00667 # valuebox @boxname@
00668 class @boxname@:
00669     _NP_RepositoryId = "@repoId@"
00670     def __init__(self, *args, **kw):
00671         raise RuntimeError("Cannot construct objects of this type.")
00672 
00673 _0_@modname@.@boxname@ = @boxname@
00674 _0_@modname@._d_@boxname@  = (omniORB.tcInternal.tv_value_box, @boxname@, @boxname@._NP_RepositoryId, "@boxname@", @boxdesc@)
00675 _0_@modname@._tc_@boxname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@boxname@)
00676 omniORB.registerType(@boxname@._NP_RepositoryId, _0_@modname@._d_@boxname@, _0_@modname@._tc_@boxname@)
00677 omniORB.registerValueFactory(@boxname@._NP_RepositoryId, @boxname@)
00678 del @boxname@
00679 """
00680 
00681 
00682 example_start = """\
00683 #!/usr/bin/env python
00684 
00685 # Python example implementations generated from @filename@
00686 
00687 import CORBA, PortableServer
00688 
00689 # Import the Python stub modules so type definitions are available.
00690 """
00691 
00692 example_import_skels = """
00693 # Import the Python Skeleton modules so skeleton base classes are available.
00694 """
00695 
00696 example_import = """\
00697 import @module@"""
00698 
00699 example_classdef = """
00700 
00701 # Implementation of interface @ccname@
00702 
00703 class @ifname@_i (@skname@):
00704 @inheritance_note@
00705     def __init__(self):
00706         # Initialise member variables here
00707         pass
00708 """
00709 
00710 example_opdef = """\
00711     # @signature@
00712     def @opname@(self@args@):
00713         raise CORBA.NO_IMPLEMENT(0, CORBA.COMPLETED_NO)
00714         # *** Implement me
00715         # Must return: @returnspec@
00716 """
00717 
00718 example_end = """
00719 if __name__ == "__main__":
00720     import sys
00721     
00722     # Initialise the ORB
00723     orb = CORBA.ORB_init(sys.argv)
00724     
00725     # As an example, we activate an object in the Root POA
00726     poa = orb.resolve_initial_references("RootPOA")
00727 
00728     # Create an instance of a servant class
00729     servant = @ifname@_i()
00730 
00731     # Activate it in the Root POA
00732     poa.activate_object(servant)
00733 
00734     # Get the object reference to the object
00735     objref = servant._this()
00736     
00737     # Print a stringified IOR for it
00738     print orb.object_to_string(objref)
00739 
00740     # Activate the Root POA's manager
00741     poa._get_the_POAManager().activate()
00742 
00743     # Run the ORB, blocking this thread
00744     orb.run()
00745 """
00746 
00747 
00748 # Global state
00749 imported_files   = {}
00750 exported_modules = {}
00751 
00752 # Command line options
00753 output_inline    = 0
00754 global_module    = "_GlobalIDL"
00755 module_package   = ""
00756 stub_package     = ""
00757 stub_directory   = ""
00758 all_factories    = 0
00759 example_impl     = 0
00760 extern_stub_pkgs = {}
00761 
00762 def methgrp_index(metharr,opname):
00763     for i in range(0, len(metharr)):
00764         if len(opname) > 2 and metharr[i] == opname[:-2]:
00765             return i
00766 
00767     return -1
00768 
00769 def ret_arg(p):
00770     return "args["+str(p)+"]"
00771 
00772 def is_int(p):
00773     return "(type("+ret_arg(p)+") in [IntType, LongType])"
00774 
00775 def is_boolean(p):
00776     return "(type("+ret_arg(p)+") in [IntType, LongType, BooleanType])"
00777 
00778 def is_double(p):
00779     return "(type("+ret_arg(p)+") in [IntType, LongType, FloatType])"
00780 
00781 def is_string(p):
00782     return "(type("+ret_arg(p)+") in [StringType])"
00783 
00784 def is_vtkPtr(p):
00785     return "(type("+ret_arg(p)+") in [InstanceType])"
00786 
00787 def is_list(p):
00788     return "(type("+ret_arg(p)+").count('[]') > 0)"
00789 
00790 def is_any(p):
00791     return "(type("+ret_arg(p)+") in [CORBA.Any])"
00792 
00793 def is_char(p):
00794     return "((type("+ret_arg(p)+") in [StringType]) and (len(" + ret_arg(p) + ") == 1))"
00795 
00796 def error_exit(message):
00797     sys.stderr.write(main.cmdname + ": " + message + "\n")
00798     sys.exit(1)
00799 
00800 def run(tree, args):
00801     global main_idl_file, imported_files, exported_modules, output_inline
00802     global global_module, module_package, stub_package, stub_directory
00803     global all_factories, example_impl, extern_stub_pkgs
00804 
00805     imported_files.clear()
00806     exported_modules.clear()
00807 
00808     # Look at the args:
00809     use_stdout     = 0
00810     create_package = 1
00811     for arg in args:
00812 
00813         if arg == "stdout":
00814             use_stdout     = 1
00815             create_package = 0
00816 
00817         elif arg == "no_package":
00818             create_package = 0
00819 
00820         elif arg == "inline":
00821             output_inline = 1
00822 
00823         elif arg == "factories":
00824             all_factories = 1
00825 
00826         elif arg[:8] == "modules=":
00827             module_package = arg[8:]
00828             if module_package != "":
00829                 module_package = module_package + "."
00830 
00831         elif arg[:6] == "stubs=":
00832             stub_package   = arg[6:]
00833             stub_directory = apply(os.path.join,
00834                                    string.split(stub_package, "."))
00835             if stub_package != "":
00836                 stub_package = stub_package + "."
00837 
00838         elif arg[:8] == "package=":
00839             module_package = stub_package = arg[8:]
00840             stub_directory = apply(os.path.join,
00841                                    string.split(stub_package, "."))
00842             if module_package != "":
00843                 module_package = stub_package = module_package + "."
00844 
00845         elif arg[:7] == "global=":
00846             global_module = arg[7:]
00847             if global_module == "":
00848                 error_exit("You may not have an unnamed global module.")
00849 
00850         elif arg == "example":
00851             example_impl = 1
00852 
00853         elif arg[:7] == "extern=":
00854             f_p = string.split(arg[7:], ":", 1)
00855             if len(f_p) == 1:
00856                 extern_stub_pkgs[f_p[0]] = None
00857             else:
00858                 extern_stub_pkgs[f_p[0]] = f_p[1]
00859 
00860         else:
00861             sys.stderr.write(main.cmdname + ": Warning: Python " \
00862                              "back-end does not understand argument: " + \
00863                              arg + "\n")
00864 
00865     main_idl_file = tree.file()
00866 
00867     outpybasename = outputFileName(main_idl_file)
00868     outpymodule   = stub_package + outpybasename
00869     outpyname     = os.path.join(stub_directory, outpybasename + ".py")
00870 
00871     imported_files[outpybasename] = 1
00872 
00873     if create_package:
00874         checkStubPackage(stub_package)
00875 
00876     if use_stdout:
00877         st = output.Stream(sys.stdout, 4)
00878     else:
00879         try:
00880             st = output.Stream(open(outpyname, "w"), 4)
00881         except IOError:
00882             error_exit('Cannot open "%s" for writing.' % outpyname)
00883 
00884     st.out(file_start, filename=main_idl_file)
00885 
00886     pv = PythonVisitor(st, outpymodule)
00887     tree.accept(pv)
00888 
00889     dv = DocstringVisitor(st)
00890     tree.accept(dv)
00891     dv.output()
00892 
00893     exports = exported_modules.keys()
00894     exports.sort()
00895     export_list = map(lambda s: '"' + module_package + s + '"', exports)
00896     if len(export_list) == 1: export_list.append("")
00897     export_string = string.join(export_list, ", ")
00898 
00899     st.out(file_end, export_string=export_string)
00900 
00901     if create_package:
00902         updateModules(exports, outpymodule)
00903 
00904     if example_impl:
00905         implname = os.path.join(stub_directory, outpybasename + "_example.py")
00906         exst = output.Stream(open(implname, "w"), 4)
00907         exst.out(example_start, filename=main_idl_file)
00908         for mod in exports:
00909             exst.out(example_import, module=mod)
00910         exst.out(example_import_skels)
00911         for mod in exports:
00912             exst.out(example_import, module=skeletonModuleName(mod))
00913 
00914         ev = ExampleVisitor(exst)
00915         tree.accept(ev)
00916 
00917         exst.out(example_end, ifname=ev.first)
00918 
00919 
00920 class PythonVisitor:
00921     def __init__(self, st, outpymodule):
00922         self.st          = st
00923         self.outpymodule = outpymodule
00924 
00925     def handleImported(self, node):
00926         global imported_files
00927 
00928         if node.mainFile() or output_inline:
00929             return 0
00930         else:
00931             ifilename = outputFileName(node.file())
00932             if not imported_files.has_key(ifilename):
00933                 imported_files[ifilename] = 1
00934                 ibasename,ext = os.path.splitext(os.path.basename(node.file()))
00935                 if extern_stub_pkgs.has_key(ibasename):
00936                     ipackage = extern_stub_pkgs[ibasename]
00937                     if ipackage:
00938                         fn = ipackage + '.' + ifilename
00939                     else:
00940                         fn = ifilename
00941                 else:
00942                     fn = stub_package + ifilename
00943 
00944                 self.st.out(import_idl_file,
00945                             idlfile=node.file(),
00946                             ifilename=fn)
00947             return 1
00948         
00949     #
00950     # The global module
00951     #
00952     def visitAST(self, node):
00953         self.at_module_scope = 1
00954         self.at_global_scope = 1
00955         self.currentScope    = ["_0_" + global_module]
00956 
00957         decls_in_global_module = 0
00958 
00959         for n in node.declarations():
00960             if not isinstance(n, idlast.Module):
00961                 decls_in_global_module = 1
00962                 break
00963 
00964         if decls_in_global_module:
00965             self.modname = global_module
00966             self.st.out(module_start,
00967                         sname=global_module,
00968                         s_sname=skeletonModuleName(global_module),
00969                         filename=node.file(), package=module_package)
00970         else:
00971             self.modname = self.outpymodule
00972 
00973         for n in node.declarations():
00974             n.accept(self)
00975 
00976         if decls_in_global_module:
00977             exported_modules[global_module] = 1
00978             self.st.out(module_end, modname=self.outpymodule,
00979                         sname=global_module,
00980                         package="")
00981 
00982     #
00983     # Module
00984     #
00985     def visitModule(self, node):
00986         if self.handleImported(node):
00987             imodname = dotName(node.scopedName())
00988             ibasename,ext = os.path.splitext(os.path.basename(node.file()))
00989 
00990             if extern_stub_pkgs.has_key(ibasename):
00991                 package = extern_stub_pkgs[ibasename]
00992                 if package is None:
00993                     package = ""
00994                 else:
00995                     package = package + "."
00996             else:
00997                 package = module_package
00998 
00999             self.st.out(open_imported_module_name,
01000                         imodname=imodname,
01001                         s_imodname=skeletonModuleName(imodname),
01002                         package=package)
01003 
01004         assert self.at_module_scope
01005 
01006         sname = dotName(node.scopedName())
01007 
01008         if node.mainFile() or output_inline:
01009             self.st.out(module_start,
01010                         sname = sname,
01011                         s_sname = skeletonModuleName(sname),
01012                         filename = node.file(), package=module_package)
01013 
01014         parentmodname = self.modname
01015         self.modname  = dotName(node.scopedName())
01016 
01017         ags = self.at_global_scope
01018         if ags:
01019             self.currentScope = ["_0_" + node.identifier()]
01020         else:
01021             self.currentScope.append(node.identifier())
01022 
01023         self.at_global_scope = 0
01024 
01025         for n in node.definitions():
01026             n.accept(self)
01027 
01028         if ags:
01029             self.currentScope = ["_0_" + global_module]
01030         else:
01031             self.currentScope.pop()
01032         self.at_global_scope = ags
01033         self.modname         = parentmodname
01034 
01035         if node.mainFile() or output_inline:
01036             exported_modules[sname] = 1
01037             self.st.out(module_end, modname=parentmodname, sname=sname,
01038                         package=module_package)
01039 
01040     #
01041     # Forward interface
01042     #
01043     def visitForward(self, node):
01044         if self.handleImported(node): return
01045 
01046         assert self.at_module_scope
01047         ifid   = mangle(node.identifier())
01048         repoId = node.repoId()
01049         if node.abstract():
01050             tvkind = "tv_abstract_interface"
01051             abstract = "abstract "
01052         else:
01053             tvkind = "tv_objref"
01054             abstract = ""
01055 
01056         self.st.out(forward_interface, ifid=ifid, tvkind=tvkind,
01057                     repoId=repoId, abstract=abstract, modname=self.modname)
01058 
01059     #
01060     # Interface
01061     #
01062     def visitInterface(self, node):
01063         if self.handleImported(node): return
01064 
01065         assert self.at_module_scope
01066         ifid = mangle(node.identifier())
01067 
01068         if len(node.inherits()) > 0:
01069             inheritl = []
01070             for i in node.inherits():
01071                 i = i.fullDecl()
01072                 inheritl.append(dotName(fixupScopedName(i.scopedName())))
01073             
01074             inherits = "(" + string.join(inheritl, ", ") + ")"
01075         else:
01076             inherits = ""
01077 
01078         if node.abstract():
01079             tvkind = "tv_abstract_interface"
01080             abstract = "abstract "
01081         else:
01082             tvkind = "tv_objref"
01083             abstract = ""
01084 
01085         # Class header
01086         self.st.out(interface_class, ifid=ifid, tvkind=tvkind,
01087                     inherits=inherits, repoId=node.repoId(),
01088                     abstract=abstract, modname=self.modname)
01089 
01090         # Declarations within the interface
01091         if len(node.declarations()) > 0:
01092             self.st.inc_indent()
01093             self.at_module_scope = 0
01094             self.currentScope.append(node.identifier())
01095 
01096             for d in node.declarations():
01097                 d.accept(self)
01098 
01099             self.currentScope.pop()
01100             self.at_module_scope = 1
01101             self.st.dec_indent()
01102             self.st.out("")
01103 
01104         # Descriptor and TypeCode for the interface
01105         self.st.out(interface_descriptor,
01106                     modname = self.modname, ifid = ifid)
01107 
01108         # Attributes and operations
01109         # *** Was there a good reason for putting these in the class def?
01110         if len(node.callables()) > 0:
01111             self.st.out(callables_header, ifid=ifid)
01112 
01113         for c in node.callables():
01114             if isinstance(c, idlast.Attribute):
01115 
01116                 descr = typeToDescriptor(c.attrType())
01117 
01118                 for attr in c.identifiers():
01119 
01120                     self.st.out(attribute_get_descriptor,
01121                                 attr=attr, descr=descr, ifid=ifid)
01122 
01123                     if not c.readonly():
01124 
01125                         self.st.out(attribute_set_descriptor,
01126                                     attr=attr, descr=descr, ifid=ifid)
01127             else: # Operation
01128 
01129                 inds, outds, excs, ctxts, cv = operationToDescriptors(c)
01130 
01131                 options = ""
01132 
01133                 if cv:
01134                     ctxts = ctxts or "None"
01135 
01136                 if ctxts:
01137                     options = ", " + ctxts
01138 
01139                 if cv:
01140                     options = options + ", 1"
01141 
01142                 # Output the declaration
01143                 self.st.out(operation_descriptor,
01144                             opname  = mangle(c.identifier()),
01145                             inds    = inds,
01146                             outds   = outds,
01147                             excs    = excs,
01148                             options = options,
01149                             ifid    = ifid)
01150 
01151         # Objref class
01152         if node.inherits():
01153             inheritl = []
01154             for i in node.inherits():
01155                 i = i.fullDecl()
01156                 sn = fixupScopedName(i.scopedName())
01157                 inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
01158                 
01159             inherits = string.join(inheritl, ", ")
01160         else:
01161             inherits = "CORBA.Object"
01162 
01163         self.st.out(objref_class, ifid=ifid, inherits=inherits)
01164 
01165         if node.inherits():
01166             for inclass in inheritl:
01167                 self.st.out(objref_inherit_init, inclass=inclass)
01168         else:
01169             self.st.out(objref_object_init)
01170 
01171         # Operations and attributes
01172         methodl = []
01173         methadd = []
01174         methdsc = []
01175 
01176         for c in node.callables():
01177 
01178             if isinstance(c, idlast.Attribute):
01179 
01180                 for attr in c.identifiers():
01181 
01182                     self.st.out(objref_attribute_get,
01183                                 attr    = attr,
01184                                 ifid    = ifid,
01185                                 modname = self.modname)
01186                     
01187                     methodl.append('"_get_' + attr + '"')
01188 
01189                     if not c.readonly():
01190 
01191                         self.st.out(objref_attribute_set,
01192                                     attr    = attr,
01193                                     ifid    = ifid,
01194                                     modname = self.modname)
01195                         
01196                         methodl.append('"_set_' + attr + '"')
01197 
01198             else: # Operation
01199                 opname = mangle(c.identifier())
01200                 
01201                 if len(opname) > 2 and opname[-2] == '_':
01202                     methlen = methgrp_index(methadd,opname)
01203                     if methlen < 0:
01204                         methodl.append('"' + opname[:-2] + '"')
01205 
01206                         methlen = len(methadd)
01207 
01208                         methadd = methadd + [opname[:-2]]
01209 
01210                         methdsc = methdsc + [""]
01211                         methdsc[methlen] = "\n    def "+opname[:-2]+"(self, *args):"
01212 
01213                     methdsc[methlen] = methdsc[methlen] + "\n        "
01214                         
01215                     methdsc[methlen] = methdsc[methlen] + "if len(args) == " + str(len(c.parameters()))
01216 
01217                     for p in range(0,len(c.parameters())):
01218                         methdsc[methlen] = methdsc[methlen] + " and "
01219                         if c.parameters()[p].paramType().kind() in [idltype.tk_short,idltype.tk_long]:
01220                             methdsc[methlen] = methdsc[methlen] + is_int(p)
01221                         if c.parameters()[p].paramType().kind() in [idltype.tk_float,idltype.tk_double]:
01222                             methdsc[methlen] = methdsc[methlen] + is_double(p)
01223                         if c.parameters()[p].paramType().kind() in [idltype.tk_string]:
01224                             methdsc[methlen] = methdsc[methlen] + is_string(p)
01225                         if c.parameters()[p].paramType().kind() in [idltype.tk_sequence,idltype.tk_alias]:
01226                             methdsc[methlen] = methdsc[methlen] + is_list(p)
01227                         if c.parameters()[p].paramType().kind() in [idltype.tk_objref]:
01228                             methdsc[methlen] = methdsc[methlen] + is_vtkPtr(p)
01229                         if c.parameters()[p].paramType().kind() in [idltype.tk_boolean]:
01230                             methdsc[methlen] = methdsc[methlen] + is_boolean(p)
01231                         if c.parameters()[p].paramType().kind() in [idltype.tk_any]:
01232                             methdsc[methlen] = methdsc[methlen] + is_any(p)
01233                         if c.parameters()[p].paramType().kind() in [idltype.tk_char]:
01234                             methdsc[methlen] = methdsc[methlen] + is_char(p)
01235                         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]:
01236                             methdsc[methlen] = methdsc[methlen] + " " + str(c.parameters()[p].paramType().kind()) + " == '' "
01237 
01238                     methdsc[methlen] = methdsc[methlen] + ":"
01239                     methdsc[methlen] = methdsc[methlen] + "\n            return self."+opname+"(*args)"
01240 
01241                 self.st.out(objref_operation,
01242                             opname   = opname,
01243                             r_opname = c.identifier(),
01244                             ifid     = ifid,
01245                             modname  = self.modname)
01246                 methodl.append('"' + opname + '"')
01247 
01248         for p in range(0,len(methadd)):
01249             methgrp = methadd[p]
01250             methtmp = methdsc[p]
01251             methtmp = methtmp + "\n        print 'Warning: The corresponding method of " + methgrp + " group is not found for ' + str(args)"
01252             self.st.out(methtmp)
01253 
01254         #self.st.out("\n    def __eq__(self,other):")
01255         #self.st.out("        return self.IsSame(other)==0")
01256 
01257         # __methods__ assignment
01258         methods = "[" + string.join(methodl, ", ") + "]"
01259 
01260         if node.inherits():
01261             inheritl = []
01262             for i in node.inherits():
01263                 i = i.fullDecl()
01264                 sn = fixupScopedName(i.scopedName())
01265                 methods = methods + " + " + \
01266                           dotName(sn[:-1] + ["_objref_" + sn[-1]]) + \
01267                           ".__methods__"
01268         else:
01269             methods = methods + " + CORBA.Object.__methods__"
01270 
01271         self.st.out(objref_methods, methods = methods)
01272 
01273         # registerObjRef()
01274         self.st.out(objref_register, ifid = ifid, modname = self.modname)
01275 
01276         # Skeleton class
01277         if node.inherits():
01278             inheritl = []
01279             for i in node.inherits():
01280                 i = i.fullDecl()
01281                 fsn = fixupScopedName(i.scopedName())
01282                 dsn = dotName(fsn)
01283                 ssn = skeletonModuleName(dsn)
01284                 inheritl.append(ssn)
01285                 
01286             inherits = string.join(inheritl, ", ")
01287         else:
01288             inherits = "PortableServer.Servant"
01289 
01290         self.st.out(skeleton_class,
01291                     ifid      = ifid,
01292                     inherits  = inherits,
01293                     modname   = self.modname,
01294                     s_modname = skeletonModuleName(self.modname),
01295                     package   = module_package)
01296 
01297         # Operations and attributes
01298         methodl = []
01299 
01300         for c in node.callables():
01301             if isinstance(c, idlast.Attribute):
01302 
01303                 for attr in c.identifiers():
01304 
01305                     methodl.append('"_get_' + attr + '": ' + \
01306                                    '_0_' + self.modname + '.' + \
01307                                    ifid + '.' + '_d__get_' + attr)
01308 
01309                     if not c.readonly():
01310 
01311                         methodl.append('"_set_' + attr + '": ' + \
01312                                        '_0_' + self.modname + '.' + \
01313                                        ifid + '.' + '_d__set_' + attr)
01314 
01315             else: # Operation
01316                 opname = mangle(c.identifier())
01317                 
01318                 methodl.append('"' + opname + '": ' + '_0_' + self.modname + \
01319                                '.' + ifid + '.' + '_d_' + opname)
01320 
01321         methodmap = "{" + string.join(methodl, ", ") + "}"
01322 
01323         self.st.out(skeleton_methodmap, methodmap = methodmap)
01324 
01325         if node.inherits():
01326             for inheritclass in inheritl:
01327                 self.st.out(skeleton_inheritmap, inheritclass = inheritclass)
01328 
01329         self.st.out(skeleton_end,
01330                     ifid      = ifid,
01331                     modname   = self.modname,
01332                     s_modname = skeletonModuleName(self.modname),
01333                     package   = module_package)
01334 
01335     #
01336     # Constant
01337     #
01338     def visitConst(self, node):
01339         if self.handleImported(node): return
01340 
01341         cname = mangle(node.identifier())
01342 
01343         if self.at_module_scope:
01344             value = valueToString(node.value(), node.constKind(), [])
01345         else:
01346             value = valueToString(node.value(), node.constKind(),
01347                                   self.currentScope)
01348         if self.at_module_scope:
01349             self.st.out(constant_at_module_scope,
01350                         cname   = cname,
01351                         value   = value,
01352                         modname = self.modname)
01353         else:
01354             self.st.out(constant,
01355                         cname   = cname,
01356                         value   = value)
01357 
01358     #
01359     # Typedef
01360     #
01361     def visitTypedef(self, node):
01362         if self.handleImported(node): return
01363 
01364         if node.constrType():
01365             node.aliasType().decl().accept(self)
01366 
01367         for decl in node.declarators():
01368             tdname = mangle(decl.identifier())
01369             if self.at_module_scope:
01370                 desc   = typeAndDeclaratorToDescriptor(node.aliasType(),
01371                                                        decl, [])
01372                 tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
01373                                                        decl, [], 1)
01374 
01375                 unaliased_type = node.aliasType().unalias()
01376 
01377                 if len(decl.sizes()) == 0 and \
01378                    unaliased_type.kind() in [idltype.tk_struct,
01379                                              idltype.tk_union]:
01380 
01381                     parent = dotName(fixupScopedName(unaliased_type.decl().\
01382                                                      scopedName()))
01383 
01384                     self.st.out(typedef_struct_union_header,
01385                                 tdname = tdname,
01386                                 repoId = decl.repoId(),
01387                                 parent = parent)
01388 
01389                 elif len(decl.sizes()) == 0 and\
01390                      unaliased_type.kind() == idltype.tk_fixed:
01391 
01392                     self.st.out(typedef_fixed_header,
01393                                 tdname = tdname,
01394                                 repoId = decl.repoId(),
01395                                 digits = unaliased_type.digits(),
01396                                 scale  = unaliased_type.scale())
01397                     
01398                 else:
01399                     self.st.out(typedef_header,
01400                                 tdname  = tdname,
01401                                 repoId  = decl.repoId())
01402 
01403                 self.st.out(typedef_at_module_scope,
01404                             tdname  = tdname,
01405                             desc    = desc,
01406                             tddesc  = tddesc,
01407                             modname = self.modname)
01408             else:
01409                 desc   = typeAndDeclaratorToDescriptor(node.aliasType(),
01410                                                        decl,
01411                                                        self.currentScope)
01412                 tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
01413                                                        decl,
01414                                                        self.currentScope, 1)
01415 
01416                 unaliased_type = node.aliasType().unalias()
01417 
01418                 if len(decl.sizes()) == 0 and \
01419                    unaliased_type.kind() in [idltype.tk_struct,
01420                                              idltype.tk_union]:
01421 
01422                     psname  = unaliased_type.decl().scopedName()
01423                     myscope = decl.scopedName()[:-1]
01424 
01425                     # If the struct/union definition is in the same
01426                     # scope as the typedef, we must use a relative
01427                     # name to refer to the parent class, since the
01428                     # enclosing Python class has not yet been fully
01429                     # defined.
01430 
01431                     if psname[:len(myscope)] == myscope:
01432                         parent = dotName(psname[len(myscope):])
01433                     else:
01434                         parent = dotName(fixupScopedName(psname))
01435 
01436                     self.st.out(typedef_struct_union_header,
01437                                 tdname = tdname,
01438                                 repoId = decl.repoId(),
01439                                 parent = parent)
01440                 else:
01441                     self.st.out(typedef_header,
01442                                 tdname  = tdname,
01443                                 repoId  = decl.repoId())
01444 
01445                 self.st.out(typedef,
01446                             tdname  = tdname,
01447                             desc    = desc,
01448                             tddesc  = tddesc)
01449     #
01450     # Struct
01451     #
01452     def visitStruct(self, node):
01453         if self.handleImported(node): return
01454 
01455         sname = mangle(node.identifier())
01456 
01457         fscopedName = fixupScopedName(node.scopedName(), "")
01458 
01459         if node.recursive():
01460             if self.at_module_scope:
01461                 self.st.out(recursive_struct_descr_at_module_scope,
01462                             sname   = sname,
01463                             repoId  = node.repoId(),
01464                             modname = self.modname)
01465             else:
01466                 self.st.out(recursive_struct_descr,
01467                             sname   = sname,
01468                             repoId  = node.repoId(),
01469                             scope   = dotName(fscopedName[:-1]))
01470 
01471         self.st.out(struct_class,
01472                     sname      = sname,
01473                     repoId     = node.repoId(),
01474                     scopedname = dotName(fscopedName))
01475 
01476         if not self.at_module_scope:
01477             self.st.out(struct_class_name, cname = dotName(fscopedName))
01478 
01479         mnamel = []
01480         mdescl = []
01481         for mem in node.members():
01482 
01483             # Deal with nested declarations
01484             if mem.constrType():
01485                 self.st.inc_indent()
01486                 ams = self.at_module_scope
01487                 self.at_module_scope = 0
01488                 self.currentScope.append(node.identifier())
01489                 
01490                 mem.memberType().decl().accept(self)
01491 
01492                 self.currentScope.pop()
01493                 self.at_module_scope = ams
01494                 self.st.dec_indent()
01495                 self.st.out("")
01496 
01497             for decl in mem.declarators():
01498                 mnamel.append(mangle(decl.identifier()))
01499                 mdescl.append('"' + mangle(decl.identifier()) + '"')
01500                 
01501                 if self.at_module_scope:
01502                     mdescl.append(\
01503                         typeAndDeclaratorToDescriptor(mem.memberType(),
01504                                                       decl,
01505                                                       []))
01506                 else:
01507                     mdescl.append(\
01508                         typeAndDeclaratorToDescriptor(mem.memberType(),
01509                                                       decl,
01510                                                       self.currentScope))
01511         if len(mnamel) > 0:
01512             mnames = ", " + string.join(mnamel, ", ")
01513 
01514             self.st.out(struct_class_init, mnames = mnames)
01515 
01516             for mname in mnamel:
01517                 self.st.out(struct_init_member, mname = mname)
01518 
01519         if len(mdescl) > 0:
01520             mdescs = ", " + string.join(mdescl, ", ")
01521         else:
01522             mdescs = ""
01523 
01524         if self.at_module_scope:
01525             self.st.out(struct_descriptor_at_module_scope,
01526                         sname   = sname,
01527                         mdescs  = mdescs,
01528                         modname = self.modname)
01529             
01530             self.st.out(struct_register_at_module_scope,
01531                         sname   = sname,
01532                         modname = self.modname)
01533         else:
01534             self.st.out(struct_descriptor,
01535                         sname  = sname,
01536                         mdescs = mdescs,
01537                         scope  = dotName(fscopedName[:-1]))
01538 
01539             self.st.out(struct_register, sname = sname)
01540 
01541     #
01542     # Forward struct
01543     #
01544     def visitStructForward(self, node):
01545         if self.handleImported(node): return
01546 
01547         sname = mangle(node.identifier())
01548 
01549         if self.at_module_scope:
01550             self.st.out(forward_struct_descr_at_module_scope,
01551                         sname   = sname,
01552                         repoId  = node.repoId(),
01553                         modname = self.modname)
01554         else:
01555             self.st.out(forward_struct_descr,
01556                         sname   = sname,
01557                         repoId  = node.repoId(),
01558                         modname = self.modname)
01559 
01560     #
01561     # Exception
01562     #
01563     def visitException(self, node):
01564         if self.handleImported(node): return
01565 
01566         sname = mangle(node.identifier())
01567         fscopedName = fixupScopedName(node.scopedName(), "")
01568         self.st.out(exception_class,
01569                     sname = sname,
01570                     repoId = node.repoId(),
01571                     scopedname = dotName(fscopedName))
01572 
01573         if not self.at_module_scope:
01574             self.st.out(struct_class_name, cname = dotName(fscopedName))
01575 
01576         mnamel = []
01577         mdescl = []
01578         for mem in node.members():
01579 
01580             # Deal with nested declarations
01581             if mem.constrType():
01582                 self.st.inc_indent()
01583                 ams = self.at_module_scope
01584                 self.at_module_scope = 0
01585                 self.currentScope.append(node.identifier())
01586                 
01587                 mem.memberType().decl().accept(self)
01588 
01589                 self.currentScope.pop()
01590                 self.at_module_scope = ams
01591                 self.st.dec_indent()
01592                 self.st.out("")
01593 
01594             for decl in mem.declarators():
01595                 mnamel.append(mangle(decl.identifier()))
01596                 mdescl.append('"' + mangle(decl.identifier()) + '"')
01597 
01598                 if self.at_module_scope:
01599                     mdescl.append(\
01600                         typeAndDeclaratorToDescriptor(mem.memberType(),
01601                                                       decl,
01602                                                       []))
01603                 else:
01604                     mdescl.append(\
01605                         typeAndDeclaratorToDescriptor(mem.memberType(),
01606                                                       decl,
01607                                                       self.currentScope))
01608 
01609         if len(mnamel) > 0:
01610             mnames = ", " + string.join(mnamel, ", ")
01611         else:
01612             mnames = ""
01613 
01614         self.st.out(exception_class_init, mnames = mnames)
01615 
01616         for mname in mnamel:
01617             self.st.out(exception_init_member, mname = mname)
01618 
01619         if len(mdescl) > 0:
01620             mdescs = ", " + string.join(mdescl, ", ")
01621         else:
01622             mdescs = ""
01623 
01624         if self.at_module_scope:
01625             self.st.out(exception_descriptor_at_module_scope,
01626                         sname = sname, mdescs = mdescs, modname = self.modname)
01627         else:
01628             self.st.out(exception_descriptor, sname = sname, mdescs = mdescs)
01629 
01630     #
01631     # Union
01632     #
01633     def visitUnion(self, node):
01634         if self.handleImported(node): return
01635 
01636         uname = mangle(node.identifier())
01637         if self.at_module_scope:
01638             stype = typeToDescriptor(node.switchType(), [])
01639         else:
01640             stype = typeToDescriptor(node.switchType(), self.currentScope)
01641 
01642         fscopedName = fixupScopedName(node.scopedName(), "")
01643         
01644         if node.recursive():
01645             if self.at_module_scope:
01646                 self.st.out(recursive_union_descr_at_module_scope,
01647                             uname   = uname,
01648                             repoId  = node.repoId(),
01649                             modname = self.modname)
01650             else:
01651                 self.st.out(recursive_union_descr,
01652                             uname   = uname,
01653                             repoId  = node.repoId(),
01654                             scope   = dotName(fscopedName[:-1]))
01655 
01656         self.st.out(union_class,
01657                     uname      = uname,
01658                     repoId     = node.repoId(),
01659                     scopedname = dotName(fscopedName))
01660 
01661         if not self.at_module_scope:
01662             self.st.out(union_class_name, cname = dotName(fscopedName))
01663 
01664         if node.constrType():
01665             self.st.inc_indent()
01666             ams = self.at_module_scope
01667             self.at_module_scope = 0
01668             self.currentScope.append(node.identifier())
01669             
01670             node.switchType().decl().accept(self)
01671 
01672             self.currentScope.pop()
01673             self.at_module_scope = ams
01674             self.st.dec_indent()
01675 
01676         def_m    = "None"
01677         def_d    = "None"
01678         m_def    = "None"
01679         defpos   = "-1"
01680         m_to_d_l = []
01681         d_to_m_l = []
01682         m_un_l   = []
01683         d_map_l  = []
01684 
01685         i = 0
01686         for case in node.cases():
01687 
01688             # Deal with nested declarations
01689             if case.constrType():
01690                 self.st.inc_indent()
01691                 ams = self.at_module_scope
01692                 self.at_module_scope = 0
01693                 self.currentScope.append(node.identifier())
01694                 
01695                 case.caseType().decl().accept(self)
01696 
01697                 self.currentScope.pop()
01698                 self.at_module_scope = ams
01699                 self.st.dec_indent()
01700                 self.st.out("")
01701 
01702             if self.at_module_scope:
01703                 ctype = typeAndDeclaratorToDescriptor(case.caseType(),
01704                                                       case.declarator(),
01705                                                       [])
01706             else:
01707                 ctype = typeAndDeclaratorToDescriptor(case.caseType(),
01708                                                       case.declarator(),
01709                                                       self.currentScope)
01710 
01711             cname = mangle(case.declarator().identifier())
01712 
01713             for label in case.labels():
01714                 if label.default():
01715                     def_m  = '"' + cname + '"'
01716                     defpos = str(i)
01717                     if self.at_module_scope:
01718                         def_d  = valueToString(label.value(),
01719                                                label.labelKind(), [])
01720                         m_def  = "_0_" + self.modname + "._m_" + uname + \
01721                                  "[" + defpos + "]"
01722                     else:
01723                         def_d  = valueToString(label.value(),
01724                                                label.labelKind(),
01725                                                self.currentScope)
01726                         m_def  = "_m_" + uname + "[" + defpos + "]"
01727 
01728                     m_un_l.append('(' + def_d + ', "' + cname + '", ' +\
01729                                   ctype + ')')
01730                 else:
01731                     if self.at_module_scope:
01732                         slabel = valueToString(label.value(),
01733                                                label.labelKind(), [])
01734                     else:
01735                         slabel = valueToString(label.value(),
01736                                                label.labelKind(),
01737                                                self.currentScope)
01738 
01739                     m_to_d_l.append('"' + cname + '": ' + slabel)
01740                     d_to_m_l.append(slabel + ': "' + cname + '"')
01741 
01742                     m_un_l.append('(' + slabel + ', "' + cname + '", ' +\
01743                                   ctype + ')')
01744 
01745                     if self.at_module_scope:
01746                         d_map_l.append(slabel + ': ' + '_0_' + self.modname + \
01747                                        "._m_" + uname + "[" + str(i) + "]")
01748                     else:
01749                         d_map_l.append(slabel + ': ' + "_m_" + \
01750                                        uname + "[" + str(i) + "]")
01751                 i = i + 1
01752 
01753         m_to_d = string.join(m_to_d_l, ", ")
01754         d_to_m = string.join(d_to_m_l, ", ")
01755         m_un   = string.join(m_un_l,   ", ")
01756         d_map  = string.join(d_map_l,  ", ")
01757 
01758         if self.at_module_scope:
01759             self.st.out(union_descriptor_at_module_scope,
01760                         uname   = uname,
01761                         m_to_d  = m_to_d,
01762                         d_to_m  = d_to_m,
01763                         def_m   = def_m,
01764                         def_d   = def_d,
01765                         m_un    = m_un,
01766                         stype   = stype,
01767                         defpos  = defpos,
01768                         m_def   = m_def,
01769                         d_map   = d_map,
01770                         modname = self.modname)
01771             
01772             self.st.out(union_register_at_module_scope,
01773                         uname   = uname,
01774                         modname = self.modname)
01775         else:
01776             self.st.out(union_descriptor,
01777                         uname   = uname,
01778                         m_to_d  = m_to_d,
01779                         d_to_m  = d_to_m,
01780                         def_m   = def_m,
01781                         def_d   = def_d,
01782                         m_un    = m_un,
01783                         stype   = stype,
01784                         defpos  = defpos,
01785                         m_def   = m_def,
01786                         d_map   = d_map,
01787                         scope   = dotName(fscopedName[:-1]))
01788             
01789             self.st.out(union_register, uname = uname)
01790 
01791     #
01792     # Forward union
01793     #
01794     def visitUnionForward(self, node):
01795         if self.handleImported(node): return
01796 
01797         uname = mangle(node.identifier())
01798 
01799         if self.at_module_scope:
01800             self.st.out(forward_union_descr_at_module_scope,
01801                         uname   = uname,
01802                         repoId  = node.repoId(),
01803                         modname = self.modname)
01804         else:
01805             self.st.out(forward_union_descr,
01806                         uname   = uname,
01807                         repoId  = node.repoId(),
01808                         modname = self.modname)
01809 
01810     #
01811     # Enum
01812     #
01813     def visitEnum(self, node):
01814         if self.handleImported(node): return
01815 
01816         ename = mangle(node.identifier())
01817         self.st.out(enum_start, ename = ename)
01818 
01819         i=0
01820         elist = []
01821         for item in node.enumerators():
01822             eval = str(i)
01823 
01824             if self.at_module_scope:
01825                 self.st.out(enum_item_at_module_scope,
01826                             item    = item.identifier(),
01827                             eitem   = mangle(item.identifier()),
01828                             eval    = eval,
01829                             modname = self.modname)
01830             else:
01831                 self.st.out(enum_item,
01832                             item    = item.identifier(),
01833                             eitem   = mangle(item.identifier()),
01834                             eval    = eval)
01835 
01836             if self.at_module_scope:
01837                 elist.append(dotName(fixupScopedName(item.scopedName())))
01838             else:
01839                 elist.append(mangle(item.identifier()))
01840 
01841             i = i + 1
01842 
01843         eitems = string.join(elist, ", ")
01844 
01845         if self.at_module_scope:
01846             self.st.out(enum_object_and_descriptor_at_module_scope,
01847                         ename   = ename,
01848                         repoId  = node.repoId(),
01849                         eitems  = eitems,
01850                         modname = self.modname)
01851         else:
01852             self.st.out(enum_object_and_descriptor,
01853                         ename   = ename,
01854                         repoId  = node.repoId(),
01855                         eitems  = eitems)
01856 
01857     def visitNative(self, node):
01858         if self.handleImported(node): return
01859 
01860         sys.stderr.write(main.cmdname + \
01861                          ": Warning: ignoring declaration of native " + \
01862                          node.identifier() + "\n")
01863 
01864     def visitValueForward(self, node):
01865         if self.handleImported(node): return
01866 
01867         vname = mangle(node.identifier())
01868 
01869         self.st.out(value_forward_at_module_scope,
01870                     vname=vname, repoId=node.repoId(), modname=self.modname)
01871 
01872 
01873     def visitValueBox(self, node):
01874         if self.handleImported(node): return
01875 
01876         boxname = mangle(node.identifier())
01877         boxdesc = typeToDescriptor(node.boxedType())
01878 
01879         self.st.out(valuebox, boxname=boxname, repoId=node.repoId(),
01880                     boxdesc=boxdesc, modname=self.modname)
01881 
01882 
01883     def visitValueAbs(self, node):
01884         if self.handleImported(node): return
01885 
01886         vname = mangle(node.identifier())
01887 
01888         fscopedName = fixupScopedName(node.scopedName(), "")
01889         scopedname  = dotName(fscopedName)
01890 
01891         if node.inherits():
01892             inheritl = []
01893             for i in node.inherits():
01894                 i = i.fullDecl()
01895                 inheritl.append(dotName(fixupScopedName(i.scopedName())))
01896             
01897             inherits = string.join(inheritl, ", ")
01898         else:
01899             inherits = "_0_CORBA.ValueBase"
01900 
01901         self.st.out(valueabs_class,
01902                     vname=vname, scopedname=scopedname, repoId=node.repoId(),
01903                     inherits=inherits, modname=self.modname)
01904 
01905         # Declarations within the value
01906         if len(node.declarations()) > 0:
01907             self.st.inc_indent()
01908             self.at_module_scope = 0
01909             self.currentScope.append(node.identifier())
01910 
01911             for d in node.declarations():
01912                 d.accept(self)
01913 
01914             self.currentScope.pop()
01915             self.at_module_scope = 1
01916             self.st.dec_indent()
01917             self.st.out("")
01918 
01919         basedesc = "_0_CORBA.tcInternal.tv_null"
01920 
01921         self.st.out(value_descriptor_at_module_scope,
01922                     vname=vname, modifier="_0_CORBA.VM_ABSTRACT",
01923                     tbaseids="None", basedesc=basedesc, mdescs="",
01924                     modname=self.modname)
01925 
01926 
01927     def visitValue(self, node):
01928         if self.handleImported(node): return
01929 
01930         vname = mangle(node.identifier())
01931 
01932         fscopedName = fixupScopedName(node.scopedName(), "")
01933         scopedname  = dotName(fscopedName)
01934 
01935         if node.inherits():
01936             inheritl = []
01937             for i in node.inherits():
01938                 i = i.fullDecl()
01939                 inheritl.append(dotName(fixupScopedName(i.scopedName())))
01940             
01941         else:
01942             inheritl = ["_0_CORBA.ValueBase"]
01943 
01944         skeleton_opl = []
01945         for i in node.supports():
01946             i = i.fullDecl()
01947             sn = fixupScopedName(i.scopedName())
01948             sn[0] = sn[0] + "__POA"
01949             dn = dotName(sn)
01950             inheritl.append(dn)
01951             skeleton_opl.append(dn)
01952 
01953         inherits = string.join(inheritl, ", ")
01954 
01955         # Go up the chain of inherited interfaces, picking out the
01956         # state members
01957         members = []
01958         ilist   = []
01959         cnode   = node
01960         
01961         while 1:
01962             cin = cnode.inherits()
01963             if not cin:
01964                 break
01965             i = cin[0].fullDecl()
01966             if not isinstance(i, idlast.Value):
01967                 break
01968             ilist.append(i)
01969             cnode = i
01970 
01971         ilist.reverse()
01972         ilist.append(node)
01973         
01974         for i in ilist:
01975             members.extend(i.statemembers())
01976 
01977         set_argl = []
01978 
01979         for i in range(len(members)):
01980             member = members[i]
01981             for d in member.declarators():
01982                 set_argl.append("self.%s = args[%d]" %
01983                                 (mangle(d.identifier()),i))
01984 
01985         if set_argl:
01986             set_args = string.join(set_argl, "\n")
01987         else:
01988             set_args = "pass"
01989 
01990         if len(set_argl) == 1:
01991             s = ""
01992         else:
01993             s = "s"
01994 
01995         self.st.out(value_class,
01996                     vname=vname, scopedname=scopedname, repoId=node.repoId(),
01997                     inherits=inherits, set_args=set_args, arglen=len(set_argl),
01998                     s=s, modname=self.modname)
01999 
02000         # Declarations within the value
02001         if len(node.declarations()) > 0:
02002             self.st.inc_indent()
02003             self.at_module_scope = 0
02004             self.currentScope.append(node.identifier())
02005 
02006             for d in node.declarations():
02007                 d.accept(self)
02008 
02009             self.currentScope.pop()
02010             self.at_module_scope = 1
02011             self.st.dec_indent()
02012             self.st.out("")
02013 
02014         # Skeleton operation declarations if necessary
02015         if node.supports():
02016             self.st.out(skeleton_methodmap, methodmap="{}")
02017             for i in skeleton_opl:
02018                 self.st.out(skeleton_inheritmap, inheritclass=i)
02019 
02020             self.st.out(skeleton_set_skel, ifid=vname)
02021 
02022         # Register factory if no callables or factories
02023         register_factory = 1
02024 
02025         if not all_factories:
02026             cnode = node
02027             while 1:
02028                 if cnode.callables() or cnode.factories() or cnode.supports():
02029                     register_factory = 0
02030                     break
02031                 cin = cnode.inherits()
02032                 if not cin:
02033                     break
02034                 for n in cin:
02035                     n = n.fullDecl()
02036                     if not isinstance(n, idlast.Value):
02037                         register_factory = 0
02038                         break
02039                 cnode = cin[0].fullDecl()
02040 
02041         if register_factory:
02042             self.st.out(value_register_factory, vname=vname)
02043         
02044         # If value supports some interfaces, output an objref class for it
02045         if node.supports():
02046             inheritl = []
02047             methodl  = []
02048             for i in node.supports():
02049                 i = i.fullDecl()
02050                 sn = fixupScopedName(i.scopedName())
02051                 inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
02052                 methodl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]) +
02053                                ".__methods__")
02054                 
02055             inherits = string.join(inheritl, ", ")
02056 
02057             self.st.out(objref_class, ifid=vname, inherits=inherits)
02058 
02059             for inclass in inheritl:
02060                 self.st.out(objref_inherit_init, inclass=inclass)
02061 
02062             methods = string.join(methodl, " + ")
02063             self.st.out(objref_methods, methods = methods)
02064 
02065             # registerObjRef()
02066             self.st.out(value_objref_register,
02067                         ifid=vname, modname=self.modname)
02068 
02069         # Modifier
02070         if node.custom():
02071             modifier = "_0_CORBA.VM_CUSTOM"
02072         elif node.truncatable():
02073             modifier = "_0_CORBA.VM_TRUNCATABLE"
02074         else:
02075             modifier = "_0_CORBA.VM_NONE"
02076 
02077         # Truncatable bases
02078         tbasel = []
02079         cnode  = node
02080         while 1:
02081             cin = cnode.inherits()
02082             if not cin:
02083                 break
02084             i = cin[0]
02085             i = i.fullDecl()
02086             if not isinstance(i, idlast.Value):
02087                 break
02088             if cnode.truncatable():
02089                 sn = fixupScopedName(i.scopedName())
02090                 tbasel.append(dotName(sn) + "._NP_RepositoryId")
02091             else:
02092                 break
02093             cnode = i
02094 
02095         if tbasel:
02096             tbaseids = "(%s._NP_RepositoryId, %s)" % (vname,
02097                                                      string.join(tbasel, ", "))
02098         else:
02099             tbaseids = "None"
02100 
02101         basedesc = None
02102         if node.inherits():
02103             i = node.inherits()[0].fullDecl()
02104             if isinstance(i, idlast.Value):
02105                 sn = i.scopedName()[:]
02106                 sn[-1] = "_d_" + sn[-1]
02107                 basedesc = dotName(fixupScopedName(sn))
02108 
02109         if basedesc is None:
02110             basedesc = "_0_CORBA.tcInternal.tv_null"
02111 
02112         mlist = []
02113         for m in node.statemembers():
02114             for d in m.declarators():
02115                 mlist.append('"%s"' % mangle(d.identifier()))
02116                 mlist.append(typeAndDeclaratorToDescriptor(m.memberType(),
02117                                                            d, []))
02118                 if m.memberAccess() == 1:
02119                     mlist.append("_0_CORBA.PRIVATE_MEMBER")
02120                 else:
02121                     mlist.append("_0_CORBA.PUBLIC_MEMBER")
02122                     
02123         mdescs = string.join(mlist, ", ")
02124         self.st.out(value_descriptor_at_module_scope,
02125                     vname=vname, modifier=modifier, tbaseids=tbaseids,
02126                     basedesc=basedesc, mdescs=mdescs, modname=self.modname)
02127 
02128 
02129 
02130 def docConst(node):
02131     if isinstance(node, idlast.Const)        and \
02132        node.constKind() == idltype.tk_string and \
02133        node.identifier()[-7:] == "__doc__":
02134         return node.identifier()[:-7]
02135     else:
02136         return None
02137 
02138 def nodeId(node):
02139     if hasattr(node, "identifier"):
02140         return node.identifier()
02141     else:
02142         return None
02143 
02144 def docWarning(node):
02145     sys.stderr.write(main.cmdname + \
02146                      ": Warning: Constant '" + node.identifier() + "' looks "
02147                      "like a Python docstring, but there is no declaration "
02148                      "named '" + node.identifier()[:-7] + "'.\n")
02149     
02150 class DocstringVisitor (idlvisitor.AstVisitor):
02151     def __init__(self, st):
02152         self.docs = []
02153         self.st   = st
02154 
02155     def output(self):
02156         if self.docs:
02157             self.st.out("""\
02158 #
02159 # Docstrings
02160 #
02161 """)
02162         for nsn, dsn in self.docs:
02163             nsn = fixupScopedName(nsn)
02164             dsn = fixupScopedName(dsn)
02165 
02166             self.st.out("@node@.__doc__ = @doc@",
02167                         node=dotName(nsn), doc=dotName(dsn))
02168             
02169         if self.docs:
02170             self.st.out("")
02171 
02172     def visitAST(self, node):
02173         for n in node.declarations():
02174             if not output_inline and not n.mainFile(): continue
02175             
02176             d = docConst(n)
02177             if d:
02178                 ok = 0
02179                 for o in node.declarations():
02180                     if nodeId(o) == d:
02181                         self.docs.append((o.scopedName(), n.scopedName()))
02182                         if isinstance(o, idlast.Interface):
02183                             sn = o.scopedName()[:]
02184                             sn[-1] = "_objref_" + sn[-1]
02185                             self.docs.append((sn, n.scopedName()))
02186                         ok = 1
02187                         break
02188                 if not ok:
02189                     docWarning(n)
02190             n.accept(self)
02191 
02192     def visitModule(self, node):
02193         for n in node.definitions():
02194             d = docConst(n)
02195             if d:
02196                 if d == node.identifier():
02197                     self.docs.append((node.scopedName(), n.scopedName()))
02198                 else:
02199                     ok = 0
02200                     for o in node.definitions():
02201                         if nodeId(o) == d:
02202                             self.docs.append((o.scopedName(), n.scopedName()))
02203                             if isinstance(o, idlast.Interface):
02204                                 sn = o.scopedName()[:]
02205                                 sn[-1] = "_objref_" + sn[-1]
02206                                 self.docs.append((sn, n.scopedName()))
02207                             ok = 1
02208                             break
02209                     if not ok:
02210                         docWarning(n)
02211             n.accept(self)
02212 
02213     def visitInterface(self, node):
02214         for n in node.declarations():
02215             d = docConst(n)
02216             if d:
02217                 if d == node.identifier():
02218                     self.docs.append((node.scopedName(), n.scopedName()))
02219                     sn = node.scopedName()[:]
02220                     sn[-1] = "_objref_" + sn[-1]
02221                     self.docs.append((sn, n.scopedName()))
02222                 else:
02223                     ok = 0
02224                     for o in node.declarations():
02225                         if nodeId(o) == d:
02226                             self.docs.append((o.scopedName(), n.scopedName()))
02227                             ok = 1
02228                             break
02229                                 
02230                     if ok:
02231                         continue
02232 
02233                     for o in node.callables():
02234                         self.target_id   = d
02235                         self.target_node = n
02236                         self.ok          = 0
02237                         o.accept(self)
02238                         if self.ok:
02239                             break
02240                     
02241                     if not self.ok:    
02242                         docWarning(n)
02243 
02244     def visitOperation(self, node):
02245         if node.identifier() == self.target_id:
02246             sn = node.scopedName() + ["im_func"]
02247             sn[-3] = "_objref_" + sn[-3]
02248             self.docs.append((sn, self.target_node.scopedName()))
02249             self.ok = 1
02250 
02251     def visitAttribute(self, node):
02252         for n in node.declarators():
02253             if n.identifier() == self.target_id:
02254                 sn = n.scopedName() + ["im_func"]
02255                 sn[-3] = "_objref_" + sn[-3]
02256                 sn[-2] = "_get_"    + sn[-2]
02257                 self.docs.append((sn, self.target_node.scopedName()))
02258                 if not node.readonly():
02259                     sn = sn[:]
02260                     sn[-2] = "_set_" + n.identifier()
02261                     self.docs.append((sn, self.target_node.scopedName()))
02262                 self.ok = 1
02263 
02264 
02265 class ExampleVisitor (idlvisitor.AstVisitor, idlvisitor.TypeVisitor):
02266     def __init__(self, st):
02267         self.st = st
02268         self.first = None
02269 
02270     def visitAST(self, node):
02271         for n in node.declarations():
02272             if not output_inline and not n.mainFile(): continue
02273 
02274             if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
02275                 n.accept(self)
02276 
02277     def visitModule(self, node):
02278         for n in node.definitions():
02279             if not output_inline and not n.mainFile(): continue
02280 
02281             if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
02282                 n.accept(self)
02283 
02284     def visitInterface(self, node):
02285         ifname = mangle(node.identifier())
02286         sname  = node.scopedName()
02287         ccname = idlutil.ccolonName(sname)
02288         fsname = fixupScopedName(sname, prefix="")
02289         dname  = dotName(fsname)
02290         skname = skeletonModuleName(dname)
02291 
02292         if self.first is None:
02293             self.first = ifname
02294 
02295         if len(node.inherits()) == 1:
02296             inheritance_note = """
02297     # Note: this interface inherits from another interface. You must
02298     # either multiply inherit from the servant class implementing the
02299     # base interface, or explicitly implement the inherited operations
02300     # here.
02301     #
02302     # Inherited interface:
02303     #
02304 """
02305         elif node.inherits():
02306             inheritance_note = """
02307     # Note: this interface inherits from other interfaces. You must either
02308     # multiply inherit from the servant classes implementing the base
02309     # interfaces, or explicitly implement the inherited operations here.
02310     #
02311     # Inherited interfaces:
02312     #
02313 """
02314         else:
02315             inheritance_note = ""
02316 
02317         for inh in node.inherits():
02318             iname = idlutil.ccolonName(inh.fullDecl().scopedName())
02319             inheritance_note = inheritance_note + "    #   %s\n" % iname
02320         
02321         self.st.out(example_classdef, ifname=ifname,
02322                     ccname=ccname, skname=skname,
02323                     inheritance_note = inheritance_note)
02324 
02325         for c in node.callables():
02326 
02327             if isinstance(c, idlast.Attribute):
02328 
02329                 c.attrType().accept(self)
02330                 attrtype = self.__result_type
02331 
02332                 for attr in c.identifiers():
02333 
02334                     signature = "attribute %s %s" % (attrtype, attr)
02335 
02336                     if c.readonly():
02337                         signature = "readonly " + signature
02338 
02339                     if not c.readonly():
02340                         self.st.out(example_opdef,
02341                                     signature = signature,
02342                                     opname = "_set_" + attr,
02343                                     args = ", value",
02344                                     returnspec = "None")
02345 
02346                     self.st.out(example_opdef,
02347                                 signature = signature,
02348                                 opname = "_get_" + attr,
02349                                 args = "",
02350                                 returnspec = "attribute value")
02351             else:
02352                 # Operation
02353                 innames  = []
02354                 outnames = []
02355                 siglist  = []
02356 
02357                 c.returnType().accept(self)
02358                 rettype = self.__result_type
02359 
02360                 if c.returnType().kind() != idltype.tk_void:
02361                     outnames.append("result")
02362 
02363                 for p in c.parameters():
02364                     if p.is_in():
02365                         innames.append(p.identifier())
02366                     if p.is_out():
02367                         outnames.append(p.identifier())
02368 
02369                     direction = {0:"in", 1:"out", 2:"inout"}[p.direction()]
02370 
02371                     p.paramType().accept(self)
02372                     siglist.append("%s %s %s" % (direction,
02373                                                  self.__result_type,
02374                                                  p.identifier()))
02375 
02376                 signature = "%s %s(%s)" % (rettype, c.identifier(),
02377                                            string.join(siglist, ", "))
02378 
02379                 if innames:
02380                     args = ", " + string.join(innames, ", ")
02381                 else:
02382                     args = ""
02383 
02384                 if outnames:
02385                     returnspec = string.join(outnames, ", ")
02386                 else:
02387                     returnspec = "None"
02388 
02389                 self.st.out(example_opdef,
02390                             signature = signature,
02391                             opname = c.identifier(),
02392                             args = args,
02393                             returnspec = returnspec)
02394 
02395 
02396 
02397     ttsMap = {
02398         idltype.tk_void:       "void",
02399         idltype.tk_short:      "short",
02400         idltype.tk_long:       "long",
02401         idltype.tk_ushort:     "unsigned short",
02402         idltype.tk_ulong:      "unsigned long",
02403         idltype.tk_float:      "float",
02404         idltype.tk_double:     "double",
02405         idltype.tk_boolean:    "boolean",
02406         idltype.tk_char:       "char",
02407         idltype.tk_octet:      "octet",
02408         idltype.tk_any:        "any",
02409         idltype.tk_TypeCode:   "CORBA::TypeCode",
02410         idltype.tk_Principal:  "CORBA::Principal",
02411         idltype.tk_longlong:   "long long",
02412         idltype.tk_ulonglong:  "unsigned long long",
02413         idltype.tk_longdouble: "long double",
02414         idltype.tk_wchar:      "wchar"
02415         }
02416 
02417     def visitBaseType(self, type):
02418         self.__result_type = self.ttsMap[type.kind()]
02419 
02420     def visitStringType(self, type):
02421         if type.bound() == 0:
02422             self.__result_type = "string"
02423         else:
02424             self.__result_type = "string<" + str(type.bound()) + ">"
02425 
02426     def visitWStringType(self, type):
02427         if type.bound() == 0:
02428             self.__result_type = "wstring"
02429         else:
02430             self.__result_type = "wstring<" + str(type.bound()) + ">"
02431 
02432 
02433     def visitDeclaredType(self, type):
02434         self.__result_type = idlutil.ccolonName(type.decl().scopedName())
02435 
02436 
02437 
02438 
02439 
02440 def operationToDescriptors(op):
02441     """Return the descriptors for an operation.
02442 
02443     Returns a tuple containing strings of (in descriptor, out
02444     descriptor, exception map, context list, contains values)
02445     """
02446 
02447     indl  = []
02448     outdl = []
02449     cv    = 0
02450 
02451     if op.returnType() is not None and \
02452        op.returnType().kind() != idltype.tk_void:
02453 
02454         outdl.append(typeToDescriptor(op.returnType()))
02455         cv = idltype.containsValueType(op.returnType())
02456 
02457     # Make the lists of in and out parameters
02458     for p in op.parameters():
02459 
02460         if p.is_in():
02461             indl.append(typeToDescriptor(p.paramType()))
02462         if p.is_out():
02463             outdl.append(typeToDescriptor(p.paramType()))
02464 
02465         cv = cv or idltype.containsValueType(p.paramType())
02466 
02467     # Fudge single-item lists so that single item tuples work
02468     if len(indl)  == 1: indl.append("")
02469     if len(outdl) == 1: outdl.append("")
02470 
02471     inds = "(" + string.join(indl, ", ") + ")"
02472     if op.oneway():
02473         outds = "None"
02474     else:
02475         outds = "(" + string.join(outdl, ", ") + ")"
02476 
02477     # Exceptions
02478     excl = []
02479 
02480     for e in op.raises():
02481         sn = fixupScopedName(e.scopedName())
02482         ename = dotName(sn)
02483         edesc = dotName(sn[:-1] + [ "_d_" + sn[-1]])
02484         excl.append(ename + "._NP_RepositoryId: " + edesc)
02485 
02486     if len(excl) > 0:
02487         excs = "{" + string.join(excl, ", ") + "}"
02488     else:
02489         excs = "None"
02490 
02491     if op.contexts():
02492         ctxts = "[" + string.join(map(repr, op.contexts()), ", ") + "]"
02493     else:
02494         ctxts = None
02495 
02496     return inds, outds, excs, ctxts, cv
02497 
02498 
02499 
02500 ttdMap = {
02501     idltype.tk_short:      "omniORB.tcInternal.tv_short",
02502     idltype.tk_long:       "omniORB.tcInternal.tv_long",
02503     idltype.tk_ushort:     "omniORB.tcInternal.tv_ushort",
02504     idltype.tk_ulong:      "omniORB.tcInternal.tv_ulong",
02505     idltype.tk_float:      "omniORB.tcInternal.tv_float",
02506     idltype.tk_double:     "omniORB.tcInternal.tv_double",
02507     idltype.tk_boolean:    "omniORB.tcInternal.tv_boolean",
02508     idltype.tk_char:       "omniORB.tcInternal.tv_char",
02509     idltype.tk_octet:      "omniORB.tcInternal.tv_octet",
02510     idltype.tk_any:        "omniORB.tcInternal.tv_any",
02511     idltype.tk_TypeCode:   "omniORB.tcInternal.tv_TypeCode",
02512     idltype.tk_Principal:  "omniORB.tcInternal.tv_Principal",
02513     idltype.tk_longlong:   "omniORB.tcInternal.tv_longlong",
02514     idltype.tk_ulonglong:  "omniORB.tcInternal.tv_ulonglong",
02515     idltype.tk_wchar:      "omniORB.tcInternal.tv_wchar"
02516 }
02517 
02518 unsupportedMap = {
02519     idltype.tk_longdouble: "long double",
02520 }
02521 
02522 def typeToDescriptor(tspec, from_scope=[], is_typedef=0):
02523     if hasattr(tspec, "python_desc"):
02524         return tspec.python_desc
02525 
02526     if ttdMap.has_key(tspec.kind()):
02527         tspec.python_desc = ttdMap[tspec.kind()]
02528         return tspec.python_desc
02529 
02530     if unsupportedMap.has_key(tspec.kind()):
02531         error_exit("omniORBpy does not support the %s type." %
02532                    unsupportedMap[tspec.kind()])
02533 
02534     if tspec.kind() == idltype.tk_string:
02535         ret = "(omniORB.tcInternal.tv_string," + str(tspec.bound()) + ")"
02536 
02537     elif tspec.kind() == idltype.tk_wstring:
02538         ret = "(omniORB.tcInternal.tv_wstring," + str(tspec.bound()) + ")"
02539 
02540     elif tspec.kind() == idltype.tk_sequence:
02541         ret = "(omniORB.tcInternal.tv_sequence, " + \
02542               typeToDescriptor(tspec.seqType(), from_scope) + \
02543               ", " + str(tspec.bound()) + ")"
02544 
02545     elif tspec.kind() == idltype.tk_fixed:
02546         ret = "(omniORB.tcInternal.tv_fixed, " + \
02547               str(tspec.digits()) + ", " + str(tspec.scale()) + ")"
02548 
02549     elif tspec.kind() == idltype.tk_alias:
02550         sn = fixupScopedName(tspec.scopedName())
02551         if is_typedef:
02552             return 'omniORB.typeCodeMapping["%s"]._d' % tspec.decl().repoId()
02553         else:
02554             return 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
02555 
02556     else:
02557         ret = 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
02558 
02559     tspec.python_desc = ret
02560     return ret
02561 
02562 
02563 def typeAndDeclaratorToDescriptor(tspec, decl, from_scope, is_typedef=0):
02564     desc = typeToDescriptor(tspec, from_scope, is_typedef)
02565 
02566     if len(decl.sizes()) > 0:
02567         sizes = decl.sizes()[:]
02568         sizes.reverse()
02569         for size in sizes:
02570             desc = "(omniORB.tcInternal.tv_array, " + \
02571                    desc + ", " + str(size) + ")"
02572     return desc
02573 
02574 def skeletonModuleName(mname):
02575     """Convert a scoped name string into the corresponding skeleton
02576 module name. e.g. M1.M2.I -> M1__POA.M2.I"""
02577     l = string.split(mname, ".")
02578     l[0] = l[0] + "__POA"
02579     return string.join(l, ".")
02580 
02581 def dotName(scopedName, our_scope=[]):
02582     if scopedName[:len(our_scope)] == our_scope:
02583         l = map(mangle, scopedName[len(our_scope):])
02584     else:
02585         l = map(mangle, scopedName)
02586     return string.join(l, ".")
02587 
02588 def mangle(name):
02589     if keyword.iskeyword(name): return "_" + name
02590 
02591     # None is a pseudo-keyword that cannot be assigned to.
02592     if name == "None": return "_None"
02593 
02594     return name
02595 
02596 def fixupScopedName(scopedName, prefix="_0_"):
02597     """Add a prefix and _GlobalIDL to the front of a ScopedName if necessary"""
02598 
02599     try:
02600         decl = idlast.findDecl([scopedName[0]])
02601     except idlast.DeclNotFound:
02602         decl = None
02603 
02604     if isinstance(decl, idlast.Module):
02605         scopedName = [prefix + mangle(scopedName[0])] + scopedName[1:]
02606     else:
02607         scopedName = [prefix + global_module] + scopedName
02608     return scopedName
02609 
02610 def valueToString(val, kind, scope=[]):
02611     if kind == idltype.tk_enum:
02612         return dotName(fixupScopedName(val.scopedName()), scope)
02613 
02614     elif kind in [idltype.tk_string, idltype.tk_char]:
02615         return '"' + idlutil.escapifyString(val) + '"'
02616 
02617     elif kind == idltype.tk_wstring:
02618         return 'u"' + idlutil.escapifyWString(val) + '"'
02619 
02620     elif kind == idltype.tk_wchar:
02621         return 'u"' + idlutil.escapifyWString([val]) + '"'
02622 
02623     elif kind == idltype.tk_long and val == -2147483647 - 1:
02624         return "-2147483647 - 1"
02625 
02626     elif kind in [idltype.tk_float, idltype.tk_double, idltype.tk_longdouble]:
02627         return idlutil.reprFloat(val)
02628 
02629     elif kind == idltype.tk_fixed:
02630         return "CORBA.fixed('" + val + "')"
02631 
02632     else:
02633         return str(val)
02634 
02635 __translate_table = string.maketrans(" -.,", "____")
02636 
02637 def outputFileName(idlname):
02638     global __translate_table
02639     return string.translate(os.path.basename(idlname), __translate_table)
02640 
02641 def checkStubPackage(package):
02642     """Check the given package name for use as a stub directory
02643 
02644     Make sure all fragments of the package name are directories, or
02645     create them. Make __init__.py files in all directories."""
02646 
02647     if len(package) == 0:
02648         return
02649 
02650     if package[-1] == ".":
02651         package = package[:-1]
02652 
02653     path = ""
02654     for name in string.split(package, "."):
02655         path = os.path.join(path, name)
02656         
02657         if os.path.exists(path):
02658             if not os.path.isdir(path):
02659                 error_exit('Output error: "%s" exists and is not '
02660                            'a directory.' % path)
02661         else:
02662             try:
02663                 os.mkdir(path)
02664             except:
02665                 error_exit('Cannot create directory "%s".\n' % path)
02666 
02667         initfile = os.path.join(path, "__init__.py")
02668 
02669         if os.path.exists(initfile):
02670             if not os.path.isfile(initfile):
02671                 error_exit('Output error: "%s" exists and is not a file.' %
02672                            initfile)
02673         else:
02674             try:
02675                 open(initfile, "w").write("# omniORB stub directory\n")
02676             except:
02677                 error_exit('Cannot create "%s".' % initfile)
02678 
02679 
02680 def updateModules(modules, pymodule):
02681     """Create or update the Python modules corresponding to the IDL
02682     module names"""
02683 
02684     checkStubPackage(module_package)
02685 
02686     poamodules = map(skeletonModuleName, modules)
02687 
02688     real_updateModules(modules,    pymodule)
02689     real_updateModules(poamodules, pymodule)
02690 
02691 
02692 def real_updateModules(modules, pymodule):
02693 
02694     for module in modules:
02695         modlist = string.split(module_package, ".") + string.split(module, ".")
02696         modpath = apply(os.path.join, modlist)
02697         modfile = os.path.join(modpath, "__init__.py")
02698         tmpfile = os.path.join(modpath, "new__init__.py")
02699 
02700         if not os.path.exists(modpath):
02701             try:
02702                 os.makedirs(modpath)
02703             except:
02704                 error_exit('Cannot create path "%s".' % modpath)
02705 
02706         # Make the __init__.py file if it does not already exist
02707         if not os.path.exists(modfile):
02708             try:
02709                 f = open(modfile, "w")
02710             except:
02711                 error_exit('Cannot create "%s".' % modfile)
02712             
02713             st = output.Stream(f, 4)
02714 
02715             st.out(pymodule_template, module=module, package=module_package)
02716 
02717             f.close()
02718             del f, st
02719 
02720         if not os.path.isfile(modfile):
02721             error_exit('Output error: "%s" exists but is not a file.' %
02722                        modfile)
02723 
02724         # Insert the import line for the current IDL file
02725         try:
02726             inf = open(modfile, "r")
02727         except:
02728             error_exit('Cannot open "%s" for reading.' % modfile)
02729 
02730         try:
02731             outf = open(tmpfile, "w")
02732         except:
02733             error_exit('Cannot open "%s" for writing.' % tmpfile)
02734 
02735         line = ""
02736         while line[:7] != "# ** 1.":
02737             line = inf.readline()
02738             if line == "":
02739                 error_exit('Output error: "%s" ended before I found a '
02740                            '"# ** 1." tag.\n'
02741                            'Have you left behind some files from a '
02742                            'different Python ORB?' % modfile)
02743                 
02744             outf.write(line)
02745             
02746         already    = 0
02747         outputline = "import " + pymodule + "\n"
02748 
02749         while line != "\n":
02750             line = inf.readline()
02751             if line == "":
02752                 error_exit('Output error: "%s" ended while I was '
02753                            'looking at imports.' % modfile)
02754 
02755             if line != "\n":
02756                 outf.write(line)
02757                 if line == outputline:
02758                     already = 1
02759 
02760         if not already:
02761             outf.write(outputline)
02762 
02763         outf.write("\n")
02764 
02765         # Output the rest of the file
02766         while line != "":
02767             line = inf.readline()
02768             outf.write(line)
02769 
02770         inf.close()
02771         outf.close()
02772 
02773         try:
02774             os.remove(modfile)
02775         except:
02776             error_exit('Cannot remove "%s".' % modfile)
02777         try:
02778             os.rename(tmpfile, modfile)
02779         except:
02780             error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))
02781 
02782     # Go round again, importing sub-modules from their parent modules
02783     for module in modules:
02784         modlist = string.split(module, ".")
02785 
02786         if len(modlist) == 1:
02787             continue
02788 
02789         modlist = string.split(module_package, ".") + modlist
02790         submod  = modlist[-1]
02791         modpath = apply(os.path.join, modlist[:-1])
02792         modfile = os.path.join(modpath, "__init__.py")
02793         tmpfile = os.path.join(modpath, "new__init__.py")
02794 
02795         # Insert the import line for the sub-module
02796         try:
02797             inf = open(modfile, "r")
02798         except:
02799             error_exit('Cannot open "%s" for reading.' % modfile)
02800 
02801         try:
02802             outf = open(tmpfile, "w")
02803         except:
02804             error_exit('Cannot open "%s" for writing.' % tmpfile)
02805 
02806         line = ""
02807         while line[:7] != "# ** 2.":
02808             line = inf.readline()
02809             if line == "":
02810                 error_exit('Output error: "%s" ended before I found a '
02811                            '"# ** 1." tag.\n'
02812                            'Have you left behind some files from a '
02813                            'different Python ORB?' % modfile)
02814                 
02815             outf.write(line)
02816             
02817         already    = 0
02818         outputline = "import " + submod + "\n"
02819 
02820         while line != "\n":
02821             line = inf.readline()
02822             if line == "":
02823                 error_exit('Output error: "%s" ended while I was '
02824                            'looking at imports.' % modfile)
02825 
02826             if line != "\n":
02827                 outf.write(line)
02828                 if line == outputline:
02829                     already = 1
02830 
02831         if not already:
02832             outf.write(outputline)
02833 
02834         outf.write("\n")
02835 
02836         # Output the rest of the file
02837         while line != "":
02838             line = inf.readline()
02839             outf.write(line)
02840 
02841         inf.close()
02842         outf.close()
02843 
02844         try:
02845             os.remove(modfile)
02846         except:
02847             error_exit('Cannot remove "%s".' % modfile)
02848         try:
02849             os.rename(tmpfile, modfile)
02850         except:
02851             error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))