@@ -313,9 +313,7 @@ def __init__(self,
313313 self .scoped = scoped
314314
315315 def to_string (self ) -> str :
316- scoped_str = ""
317- if self .scoped :
318- scoped_str = "class"
316+ scoped_str = "class" if self .scoped else ""
319317 prefix = "enum {} {} {{" .format (scoped_str , self .name )
320318 if self .base_type :
321319 prefix = "enum {} {}: {} {{" .format (scoped_str , self .name ,
@@ -362,13 +360,12 @@ def to_string(self) -> str:
362360 else :
363361 return "{}{} {} = {};" .format (doc , self .type_str , self .name ,
364362 self .default )
363+ elif self .default is None :
364+ return "{}{} {}{};" .format (doc , self .type_str , self .name ,
365+ self .array )
365366 else :
366- if self .default is None :
367- return "{}{} {}{};" .format (doc , self .type_str , self .name ,
368- self .array )
369- else :
370- return "{}{} {}{} = {};" .format (doc , self .type_str , self .name ,
371- self .array , self .default )
367+ return "{}{} {}{} = {};" .format (doc , self .type_str , self .name ,
368+ self .array , self .default )
372369
373370
374371class TemplateTypeArgument (object ):
@@ -535,18 +532,10 @@ def unpack(self, args: list) -> str:
535532 return ", " .join (map (str , args ))
536533
537534 def _clean_pre_attrs_impl (self , attrs : List [str ]):
538- res_attrs = [] # type: List[str]
539- for attr in attrs :
540- if attr not in _HEADER_ONLY_PRE_ATTRS :
541- res_attrs .append (attr )
542- return res_attrs
535+ return [attr for attr in attrs if attr not in _HEADER_ONLY_PRE_ATTRS ]
543536
544537 def _clean_post_attrs_impl (self , attrs : List [str ]):
545- res_attrs = [] # type: List[str]
546- for attr in attrs :
547- if attr not in _HEADER_ONLY_POST_ATTRS :
548- res_attrs .append (attr )
549- return res_attrs
538+ return [attr for attr in attrs if attr not in _HEADER_ONLY_POST_ATTRS ]
550539
551540 def get_sig (self ,
552541 name : str ,
@@ -565,9 +554,8 @@ def get_sig(self,
565554 return_type = self .return_type
566555 if isinstance (meta , (ConstructorMeta , DestructorMeta )):
567556 return_type = ""
568- else :
569- if not header_only :
570- assert self .return_type != "auto" and self .return_type != "decltype(auto)"
557+ elif not header_only :
558+ assert self .return_type not in ["auto" , "decltype(auto)" ]
571559 fmt = "{ret_type} {name}({args})"
572560 if withpost :
573561 fmt += "{post_attrs}"
@@ -650,8 +638,7 @@ def get_impl(self, name: str, meta: FunctionMeta, class_name: str = ""):
650638 post_attrs = post_attrs_str )
651639 if pre_attrs_str :
652640 prefix_fmt = pre_attrs_str + " " + prefix_fmt
653- blocks = [] # List[Union[Block, str]]
654- blocks .extend (self ._blocks )
641+ blocks = list (self ._blocks )
655642 block = Block (template_fmt + prefix_fmt , blocks , "}" )
656643 if meta .macro_guard is not None :
657644 block = Block ("#if {}" .format (meta .macro_guard ), [block ], "#endif" )
@@ -972,15 +959,18 @@ def _assign_overload_flag_to_func_decls(self):
972959 member_decl_count [cpp_func_name ] += 1
973960 for decl in self ._function_decls :
974961 cpp_func_name = decl .get_function_name ()
975- if isinstance (decl .meta , ExternalFunctionMeta ):
976- if extend_decl_count [cpp_func_name ] > 1 :
977- decl .is_overload = True
978- elif isinstance (decl .meta , StaticMemberFunctionMeta ):
979- if static_member_decl_count [cpp_func_name ] > 1 :
980- decl .is_overload = True
981- elif isinstance (decl .meta , MemberFunctionMeta ):
982- if member_decl_count [cpp_func_name ] > 1 :
983- decl .is_overload = True
962+ if (
963+ isinstance (decl .meta , ExternalFunctionMeta )
964+ and extend_decl_count [cpp_func_name ] > 1
965+ or not isinstance (decl .meta , ExternalFunctionMeta )
966+ and isinstance (decl .meta , StaticMemberFunctionMeta )
967+ and static_member_decl_count [cpp_func_name ] > 1
968+ or not isinstance (decl .meta , ExternalFunctionMeta )
969+ and not isinstance (decl .meta , StaticMemberFunctionMeta )
970+ and isinstance (decl .meta , MemberFunctionMeta )
971+ and member_decl_count [cpp_func_name ] > 1
972+ ):
973+ decl .is_overload = True
984974
985975 def add_dependency (self , * no_param_class_cls : Type ["Class" ]):
986976 # TODO enable name alias for Class
@@ -1134,7 +1124,7 @@ def get_includes_with_dep(self) -> List[str]:
11341124 for d in self .get_common_deps ())
11351125 return res
11361126
1137- def get_parent_class (self ): # -> Optional[Type["Class"]]
1127+ def get_parent_class (self ): # -> Optional[Type["Class"]]
11381128 """TODO find a better way to check invalid param class inherit
11391129 """
11401130 if type (self ) is Class :
@@ -1145,24 +1135,23 @@ def get_parent_class(self): # -> Optional[Type["Class"]]
11451135 base = candidates .pop ()
11461136 if issubclass (base , Class ):
11471137 cls_meta = get_class_meta (base )
1148- if cls_meta is None :
1149- pccm_base_types . append (base )
1138+ if cls_meta is not None and cls_meta . skip_inherit :
1139+ candidates . extend (base . __bases__ )
11501140 else :
1151- if cls_meta .skip_inherit :
1152- candidates .extend (base .__bases__ )
1153- else :
1154- pccm_base_types .append (base )
1141+ pccm_base_types .append (base )
11551142 assert len (pccm_base_types ) == 1 , "you can only inherit one class."
11561143 pccm_base = pccm_base_types [0 ]
1157- if pccm_base is not Class and base is not ParameterizedClass :
1158- # assert not issubclass(mro[1], ParameterizedClass), "you can't inherit a param class."
1159- if not issubclass (pccm_base , ParameterizedClass ):
1160- # you inherit a class. you must set _this_cls_type by self.set_this_class_type(__class__)
1161- msg = (
1162- "you must use self.set_this_class_type(__class__) to init this class type"
1163- " when you inherit pccm.Class" )
1164- assert self ._this_cls_type is not None , msg
1165- return pccm_base
1144+ if (
1145+ pccm_base is not Class
1146+ and base is not ParameterizedClass
1147+ and not issubclass (pccm_base , ParameterizedClass )
1148+ ):
1149+ # you inherit a class. you must set _this_cls_type by self.set_this_class_type(__class__)
1150+ msg = (
1151+ "you must use self.set_this_class_type(__class__) to init this class type"
1152+ " when you inherit pccm.Class" )
1153+ assert self ._this_cls_type is not None , msg
1154+ return pccm_base
11661155 return None
11671156
11681157 def get_class_deps (self ) -> List [Type ["Class" ]]:
@@ -1232,16 +1221,12 @@ def get_code_class_def(
12321221 d .to_string () for d in self ._members
12331222 if d .cls_type is self ._this_cls_type
12341223 ]
1235- parent_class_alias = None # type: Optional[str]
12361224 parent = self .get_parent_class ()
1237- if parent is not None :
1238- # TODO better way to get alias name
1239- parent_class_alias = parent .__name__
1240- cdef = CodeSectionClassDef (cu_name , dep_alias , self ._code_before_class ,
1225+ parent_class_alias = parent .__name__ if parent is not None else None
1226+ return CodeSectionClassDef (cu_name , dep_alias , self ._code_before_class ,
12411227 self ._code_after_class , ext_decls , ec_strs ,
12421228 typedef_strs , sc_strs , member_func_decls ,
12431229 member_def_strs , parent_class_alias )
1244- return cdef
12451230
12461231 def get_common_deps (self ) -> List ["Class" ]:
12471232 assert self .graph_inited , "you must build dependency graph before generate code"
@@ -1304,13 +1289,12 @@ def generate_namespace(self, namespace: str):
13041289 if namespace == "" :
13051290 return [], []
13061291 namespace_parts = namespace .split ("." )
1307- namespace_before = [] # type: List[str]
1308- namespace_after = [] # type: List[str]
1292+ namespace_before = ["namespace {} {{" .format (p ) for p in namespace_parts ]
1293+ namespace_after = [
1294+ "}} // namespace {}" .format (p ) for p in namespace_parts [::- 1 ]
1295+ ]
1296+
13091297
1310- for p in namespace_parts :
1311- namespace_before .append ("namespace {} {{" .format (p ))
1312- for p in namespace_parts [::- 1 ]:
1313- namespace_after .append ("}} // namespace {}" .format (p ))
13141298 return namespace_before , namespace_after
13151299
13161300
@@ -1394,8 +1378,7 @@ def to_block(self) -> Block:
13941378 prefix = code_before_cls + [
13951379 "struct {class_name} {{" .format (class_name = self .class_name )
13961380 ]
1397- block = Block ("\n " .join (prefix ), class_contents , "};" )
1398- return block
1381+ return Block ("\n " .join (prefix ), class_contents , "};" )
13991382
14001383
14011384class CodeSectionImpl (CodeSection ):
@@ -1438,9 +1421,9 @@ def extract_module_id_of_class(
14381421 relative_path = path .relative_to (Path (root ))
14391422 import_parts = list (relative_path .parts )
14401423 import_parts [- 1 ] = relative_path .stem
1424+ elif loader .locate_top_package (path ) is None :
1425+ return None
14411426 else :
1442- if loader .locate_top_package (path ) is None :
1443- return None
14441427 import_parts = loader .try_capture_import_parts (path , None )
14451428 return "." .join (import_parts )
14461429
@@ -1533,35 +1516,35 @@ def _apply_middleware_to_cus(self, uid_to_cu: Dict[str, Class]):
15331516 new_uid_to_cu = OrderedDict () # type: Dict[str, Class]
15341517 for middleware in self .middlewares :
15351518 mw_type = type (middleware )
1536- if isinstance (middleware , ManualClassGenerator ):
1537- for k , cu in uid_to_cu .items ():
1538- decls_with_meta = [
1539- ] # type: List[Tuple[FunctionDecl, MiddlewareMeta]]
1540- members_with_meta = [
1541- ] # type: List[Tuple[Member, MiddlewareMeta]]
1542- # TODO only one meta is allowed
1543- for decl in cu ._function_decls :
1544- for mw_meta in decl .meta .mw_metas :
1545- if mw_meta .type is mw_type :
1546- decls_with_meta .append ((decl , mw_meta ))
1547- for member in cu ._members :
1548- for mw_meta in member .mw_metas :
1549- if mw_meta .type is mw_type :
1550- members_with_meta .append ((member , mw_meta ))
1551- if not decls_with_meta and not members_with_meta :
1552- continue
1553- new_pcls = middleware .create_manual_class (cu )
1554- if new_pcls .namespace is None :
1555- new_pcls .namespace = cu .namespace + "." + middleware .subnamespace
1556- for decl , mw_meta in decls_with_meta :
1557- new_pcls .handle_function_decl (cu , decl , mw_meta )
1558- for member , mw_meta in members_with_meta :
1559- new_pcls .handle_member (cu , member , mw_meta )
1560- uid = new_pcls .namespace + "-" + type (new_pcls ).__name__
1561- new_uid_to_cu [uid ] = new_pcls
1562- else :
1519+ if not isinstance (middleware , ManualClassGenerator ):
15631520 raise NotImplementedError
15641521
1522+ for k , cu in uid_to_cu .items ():
1523+ decls_with_meta = [
1524+ ] # type: List[Tuple[FunctionDecl, MiddlewareMeta]]
1525+ members_with_meta = [
1526+ ] # type: List[Tuple[Member, MiddlewareMeta]]
1527+ # TODO only one meta is allowed
1528+ for decl in cu ._function_decls :
1529+ for mw_meta in decl .meta .mw_metas :
1530+ if mw_meta .type is mw_type :
1531+ decls_with_meta .append ((decl , mw_meta ))
1532+ for member in cu ._members :
1533+ for mw_meta in member .mw_metas :
1534+ if mw_meta .type is mw_type :
1535+ members_with_meta .append ((member , mw_meta ))
1536+ if not decls_with_meta and not members_with_meta :
1537+ continue
1538+ new_pcls = middleware .create_manual_class (cu )
1539+ if new_pcls .namespace is None :
1540+ new_pcls .namespace = cu .namespace + "." + middleware .subnamespace
1541+ for decl , mw_meta in decls_with_meta :
1542+ new_pcls .handle_function_decl (cu , decl , mw_meta )
1543+ for member , mw_meta in members_with_meta :
1544+ new_pcls .handle_member (cu , member , mw_meta )
1545+ uid = new_pcls .namespace + "-" + type (new_pcls ).__name__
1546+ new_uid_to_cu [uid ] = new_pcls
1547+
15651548 def build_graph (self ,
15661549 cus : List [Union [Class , ParameterizedClass ]],
15671550 root : Optional [Union [str , Path ]] = None ,
0 commit comments