abstractapi.py 40.8 KB
Newer Older
1

François Grisez's avatar
François Grisez committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (C) 2017 Belledonne Communications SARL
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

18

19 20
import re
import genapixml as CApi
21
import metaname
22
import logging
23

24

25 26
logger = logging.getLogger(__name__)

27

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
class Error(Exception):
	@property
	def reason(self):
		return self.args[0]
	
	def __str__(self):
		return str(self.reason)
	
	@staticmethod
	def _name_get_type_as_string(name):
		if type(name) is metaname.ClassName:
			return 'class'
		elif type(name) is metaname.EnumName:
			return 'enum'
		elif type(name) is metaname.EnumeratorName:
			return 'enumerator'
		elif type(name) is metaname.MethodName:
			return 'function'
		else:
			raise TypeError('{0} not handled'.format(type(name)))
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

class ParsingError(Error):
	@property
	def context(self):
		return self.args[1] if len(self.args) >= 2 else None
	
	def __str__(self):
		if self.context is None:
			return Error.__str__(self)
		else:
			params = {
				'reason': self.reason,
				'name': self.context.to_c(addBrackets=True),
				'type_': Error._name_get_type_as_string(self.context)
			}
			return "error while parsing {name} {type_}: {reason}".format(**params)


class BlacklistedSymbolError(Error):
	@property
	def name(self):
		return self.args[0]
	
	def __str__(self):
		params = {
			'name': self.name.to_c(addBrackets=True),
			'type_': Error._name_get_type_as_string(self.name)
		}
		return "{name} {type_} has been blacklisted".format(**params)


class TranslationError(Error):
81 82
	pass

83

84
class Constant:
85 86 87
	pass


88 89 90
class Nil(Constant):
	def translate(self, langTranslator):
		return langTranslator.nilToken
91 92


93 94 95
class Boolean(Constant):
	def __init__(self, value=False):
		self.value = value
96
	
97 98
	def __bool__(self):
		return self.value
99
	
100 101
	def translate(self, langTranslator):
		return langTranslator.trueConstantToken if self else langTranslator.falseConstantToken
102 103 104 105 106 107


class Object(object):
	def __init__(self, name):
		self.name = name
		self.parent = None
108
		self.deprecated = False
109
	
110 111 112
	def __lt__(self, other):
		return self.name < other.name
	
113 114 115 116 117 118
	def find_first_ancestor_by_type(self, *types, **kargs):
		try:
			priorAncestor = kargs['priorAncestor']
		except KeyError:
			priorAncestor = False

119
		current = self
120
		ancestor = self.parent
121
		while ancestor is not None and type(ancestor) not in types:
122
			current = ancestor
123
			ancestor = ancestor.parent
124
		return ancestor if not priorAncestor else current
125 126 127 128 129 130 131


class Type(Object):
	def __init__(self, name, isconst=False, isref=False):
		Object.__init__(self, name)
		self.isconst = isconst
		self.isref = isref
132
		self.cDecl = None
133 134 135 136 137 138 139


class BaseType(Type):
	def __init__(self, name, isconst=False, isref=False, size=None, isUnsigned=False):
		Type.__init__(self, name, isconst=isconst, isref=isref)
		self.size = size
		self.isUnsigned = isUnsigned
140 141 142
	
	def translate(self, translator, **params):
		return translator.translate_base_type(self, **params)
143 144 145 146 147 148


class EnumType(Type):
	def __init__(self, name, isconst=False, isref=False, enumDesc=None):
		Type.__init__(self, name, isconst=isconst, isref=isref)
		self.desc = enumDesc
149 150 151
	
	def translate(self, translator, **params):
		return translator.translate_enum_type(self, **params)
152 153 154 155 156 157


class ClassType(Type):
	def __init__(self, name, isconst=False, isref=False, classDesc=None):
		Type.__init__(self, name, isconst=isconst, isref=isref)
		self.desc = classDesc
158 159 160
	
	def translate(self, translator, **params):
		return translator.translate_class_type(self, **params)
161 162 163 164 165 166 167 168


class ListType(Type):
	def __init__(self, containedTypeName, isconst=False, isref=False):
		Type.__init__(self, 'list', isconst=isconst, isref=isref)
		self.containedTypeName = containedTypeName
		self._containedTypeDesc = None
	
169 170
	@property
	def containedTypeDesc(self):
171 172
		return self._containedTypeDesc
	
173 174 175 176
	@containedTypeDesc.setter
	def containedTypeDesc(self, desc):
		self._containedTypeDesc = desc
		desc.parent = self
177 178 179
	
	def translate(self, translator, **params):
		return translator.translate_list_type(self, **params)
180 181 182 183 184


class DocumentableObject(Object):
	def __init__(self, name):
		Object.__init__(self, name)
185 186
		self._briefDescription = None
		self._detailedDescription = None
187
	
188 189
	@property
	def briefDescription(self):
190 191
		return self._briefDescription
	
192 193
	@briefDescription.setter
	def briefDescription(self, description):
194 195 196
		self._briefDescription = description
		description.relatedObject = self
	
197 198
	@property
	def detailedDescription(self):
199 200
		return self._detailedDescription
	
201 202
	@detailedDescription.setter
	def detailedDescription(self, description):
203 204 205
		self._detailedDescription = description
		description.relatedObject = self
	
206 207 208 209 210 211 212 213 214 215
	def set_from_c(self, cObject, namespace=None):
		self.briefDescription = cObject.briefDescription
		self.detailedDescription = cObject.detailedDescription
		self.deprecated = cObject.deprecated
		self.parent = namespace
	
	def get_namespace_object(self):
		if isinstance(self, (Namespace,Enum,Class)):
			return self
		elif self.parent is None:
216
			return None
217 218 219 220 221 222 223
		else:
			return self.parent.get_namespace_object()


class Namespace(DocumentableObject):
	def __init__(self, name):
		DocumentableObject.__init__(self, name)
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
		self.enums = []
		self.classes = []
		self.interfaces = []

	def addenum(self, enum):
		Namespace._insert_element(self.enums, enum)
		enum.parent = self

	def delenum(self, enum):
		i = self.enums.index(enum)
		del self.enums[i]
		enum.parent = None

	def addclass(self, class_):
		Namespace._insert_element(self.classes, class_)
		class_.parent = self

	def delclass(self, class_):
		i = self.classes.index(class_)
		del self.classes[i]
		class_.parent = None
245
	
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
	def addinterface(self, interface):
		Namespace._insert_element(self.interfaces, interface)
		interface.parent = self

	def delinterface(self, interface):
		i = self.interfaces.index(interface)
		del self.interfaces[i]
		interface.parent = None

	@staticmethod
	def _insert_element(l, e):
		try:
			inspoint = next(x for x in l if e.name < x.name)
			index = l.index(inspoint)
			l.insert(index, e)
		except StopIteration:
			l.append(e)
263 264


265 266 267
GlobalNs = Namespace('')


268 269 270 271 272
class Flag:
	def __init__(self, position):
		self.position = position


273
class Enumerator(DocumentableObject):
274 275 276 277 278
	def __init__(self, name):
		DocumentableObject.__init__(self, name)
		self.value = None
	
	def value_from_string(self, stringValue):
279
		m = re.match('^\s*1\s*<<\s*([0-9]+)$', stringValue)
280 281 282 283
		if m is not None:
			self.value = Flag(int(m.group(1)))
		else:
			self.value = int(stringValue, base=0)
284 285 286
	
	def translate_value(self, translator):
		return translator.translate_enumerator_value(self.value)
287 288 289 290 291


class Enum(DocumentableObject):
	def __init__(self, name):
		DocumentableObject.__init__(self, name)
292
		self.enumerators = []
293
	
294 295 296
	def add_enumerator(self, enumerator):
		self.enumerators.append(enumerator)
		enumerator.parent = self
297 298 299 300 301 302 303 304 305
	
	def set_from_c(self, cEnum, namespace=None):
		Object.set_from_c(self, cEnum, namespace=namespace)
		
		if 'associatedTypedef' in dir(cEnum):
			name = cEnum.associatedTypedef.name
		else:
			name = cEnum.name
		
306
		self.name = metaname.EnumName()
307 308 309 310
		self.name.prev = None if namespace is None else namespace.name
		self.name.set_from_c(name)
		
		for cEnumValue in cEnum.values:
311
			aEnumValue = Enumerator()
312
			aEnumValue.set_from_c(cEnumValue, namespace=self)
313
			self.add_enumerator(aEnumValue)
314 315 316 317 318 319 320 321 322 323


class Argument(DocumentableObject):
	def __init__(self, name, argType, optional=False, default=None):
		DocumentableObject.__init__(self, name)
		self._type = argType
		argType.parent = self
		self.optional = optional
		self.default = default
	
324 325
	@property
	def type(self):
326 327
		return self._type
	
328 329 330 331
	@type.setter
	def type(self, _type):
		self._type = _type
		_type.parent = self
332 333 334
	
	def translate(self, translator, **params):
		return translator.translate_argument(self, **params)
335 336 337 338 339 340 341 342 343 344


class Method(DocumentableObject):
	class Type:
		Instance = 0,
		Class = 1
	
	def __init__(self, name, type=Type.Instance):
		DocumentableObject.__init__(self, name)
		self.type = type
345
		self.isconst = False
346 347
		self.args = []
		self._returnType = None
348 349 350 351 352
	
	def add_arguments(self, arg):
		self.args.append(arg)
		arg.parent = self
	
353 354
	@property
	def returnType(self):
355 356
		return self._returnType
	
357 358 359 360
	@returnType.setter
	def returnType(self, returnType):
		self._returnType = returnType
		returnType.parent = self
361 362 363
	
	def translate_as_prototype(self, translator, **params):
		return translator.translate_method_as_prototype(self, **params)
364 365 366 367 368 369 370


class Property(DocumentableObject):
	def __init__(self, name):
		DocumentableObject.__init__(self, name)
		self._setter = None
		self._getter = None
371
		self._type = None
372
	
373 374 375 376 377 378
	@property
	def setter(self):
		return self._setter

	@setter.setter
	def setter(self, setter):
379 380 381
		self._setter = setter
		setter.parent = self
	
382 383 384
	@property
	def getter(self):
		return self._getter
385
	
386 387
	@getter.setter
	def getter(self, getter):
388
		self._getter = getter
389 390
		if self._type is None:
			self._type = getter.returnType
391 392 393
		getter.parent = self


394
class Class(Namespace):
395
	def __init__(self, name):
396
		Namespace.__init__(self, name)
397 398 399 400 401
		self.properties = []
		self.instanceMethods = []
		self.classMethods = []
		self._listenerInterface = None
		self.multilistener = False
402
		self.refcountable = False
403

404
	def add_property(self, property):
405
		Namespace._insert_element(self.properties, property)
406 407 408
		property.parent = self
	
	def add_instance_method(self, method):
409
		Namespace._insert_element(self.instanceMethods, method)
410 411 412
		method.parent = self
	
	def add_class_method(self, method):
413
		Namespace._insert_element(self.classMethods, method)
414 415
		method.parent = self
	
416 417
	@property
	def listenerInterface(self):
418 419
		return self._listenerInterface
	
420 421 422 423
	@listenerInterface.setter
	def listenerInterface(self, interface):
		self._listenerInterface = interface
		interface._listenedClass = self
424 425 426 427 428
	
	def sort(self):
		self.properties.sort()
		self.instanceMethods.sort()
		self.classMethods.sort()
429 430 431 432 433 434 435 436 437 438 439 440


class Interface(DocumentableObject):
	def __init__(self, name):
		DocumentableObject.__init__(self, name)
		self.methods = []
		self._listenedClass = None
	
	def add_method(self, method):
		self.methods.append(method)
		method.parent = self
	
441 442
	@property
	def listenedClass(self):
443 444
		return self._listenedClass
	
445 446 447 448
	@listenedClass.setter
	def listenedClass(self, method):
		self.methods.append(method)
		method.parent = self
449 450 451
	
	def sort(self):
		self.methods.sort()
452 453 454


class CParser(object):
455
	def __init__(self, cProject, classBlAppend=[]):
456
		self.cBaseType = ['void', 'bool_t', 'char', 'short', 'int', 'long', 'size_t', 'time_t', 'float', 'double', 'LinphoneStatus']
457 458
		self.cListType = 'bctbx_list_t'
		self.regexFixedSizeInteger = '^(u?)int(\d?\d)_t$'
459
		self.methodBl = ['ref', 'unref', 'new', 'destroy', 'getCurrentCallbacks', 'setUserData', 'getUserData']
460
		self.functionBl = [
461 462 463 464 465
					   'linphone_factory_create_core', # manually wrapped
					   'linphone_factory_create_core_2', # manually wrapped
					   'linphone_factory_create_core_with_config', # manually wrapped
					   'linphone_factory_create_core_with_config_2', # manually wrapped
					   'linphone_vcard_get_belcard'] # manually wrapped
466

467
		self.classBl = ['LpConfig']  # temporarly blacklisted
468 469
		for bl in classBlAppend:
			self.classBl.append(bl)
470 471 472 473
		
		# list of classes that must be concidered as refcountable even if
		# they are no ref()/unref() methods
		self.forcedRefcountableClasses = ['LinphoneFactory']
474
		
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
		self.enum_relocations = {
			'LinphoneAccountCreatorActivationCodeStatus' : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorDomainStatus'         : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorEmailStatus'          : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorLanguageStatus'       : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorPasswordStatus'       : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorPhoneNumberStatus'    : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorStatus'               : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorTransportStatus'      : 'LinphoneAccountCreator',
			'LinphoneAccountCreatorUsernameStatus'       : 'LinphoneAccountCreator',
			'LinphoneCallDir'                            : 'LinphoneCall',
			'LinphoneCallState'                          : 'LinphoneCall',
			'LinphoneCallStatus'                         : 'LinphoneCall',
			'LinphoneChatRoomState'                      : 'LinphoneChatRoom',
			'LinphoneChatMessageDirection'               : 'LinphoneChatMessage',
			'LinphoneChatMessageState'                   : 'LinphoneChatMessage',
			'LinphoneCoreLogCollectionUploadState'       : 'LinphoneCore',
			'LinphoneEventLogType'                       : 'LinphoneEventLog',
			'LinphoneFriendListStatus'                   : 'LinphoneFriendList',
			'LinphoneFriendListSyncStatus'               : 'LinphoneFriendList',
			'LinphonePlayerState'                        : 'LinphonePlayer',
			'LinphonePresenceActivityType'               : 'LinphonePresenceActivity',
			'LinphoneTunnelMode'                         : 'LinphoneTunnel'
		}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
		self.cProject = cProject
		
		self.enumsIndex = {}
		for enum in self.cProject.enums:
			if enum.associatedTypedef is None:
				self.enumsIndex[enum.name] = None
			else:
				self.enumsIndex[enum.associatedTypedef.name] = None
		
		self.classesIndex = {}
		self.interfacesIndex = {}
		for _class in self.cProject.classes:
			if _class.name not in self.classBl:
				if _class.name.endswith('Cbs'):
					self.interfacesIndex[_class.name] = None
				else:
					self.classesIndex[_class.name] = None
		
518 519 520 521 522 523 524 525 526 527 528 529
		self.methodsIndex = {}
		for _class in self.cProject.classes:
			for funcname in _class.classMethods:
				self.methodsIndex[funcname] = None
			for funcname in _class.instanceMethods:
				self.methodsIndex[funcname] = None
			for _property in _class.properties.values():
				if _property.setter is not None:
					self.methodsIndex[_property.setter.name] = None
				if _property.getter is not None:
					self.methodsIndex[_property.getter.name] = None
		
530
		name = metaname.NamespaceName()
531 532 533
		name.from_snake_case('linphone')
		
		self.namespace = Namespace(name)
534
		self._pending_enums = []
535 536
	
	def _is_blacklisted(self, name):
537
		if type(name) is metaname.MethodName:
538
			return name.to_camel_case(lower=True) in self.methodBl or name.to_c() in self.functionBl
539
		elif type(name) is metaname.ClassName:
540 541 542 543 544 545
			return name.to_c() in self.classBl
		else:
			return False
		
	def parse_all(self):
		for enum in self.cProject.enums:
546 547
			try:
				self.parse_enum(enum)
548 549
			except BlacklistedSymbolError as e:
				logger.debug(e)
550
		
551
		for class_ in self.cProject.classes:
552
			try:
553 554 555
				self.parse_class(class_)
			except BlacklistedSymbolError as e:
				logger.debug(e)
556
		
557
		self._treat_pending_enums()
558
		self._clean_all_indexes()
559
		self._fix_all_types()
560
		self._fix_all_docs()
561
	
562 563 564 565 566 567 568 569 570 571 572 573 574 575
	def _treat_pending_enums(self):
		for enum in self._pending_enums:
			try:
				enum_cname = enum.name.to_c()
				parent_cname = self.enum_relocations[enum_cname]
				newparent = self.classesIndex[parent_cname]
				enum.parent.delenum(enum)
				newparent.addenum(enum)
				enum.name.from_c(enum_cname, namespace=newparent.name)
			except KeyError:
				reason = "cannot move the enum inside {0} enum because it doesn't exsist".format(parent_cname)
				raise ParsingError(reason, context=enum.name)
		self._pending_enums = []

576 577 578 579 580 581 582 583 584 585 586 587
	def _clean_all_indexes(self):
		for index in [self.classesIndex, self.interfacesIndex, self.methodsIndex]:
			self._clean_index(index)
	
	def _clean_index(self, index):
		keysToRemove = []
		for key in index.keys():
			if index[key] is None:
				keysToRemove.append(key)
		
		for key in keysToRemove:
			del index[key]
588 589 590 591 592 593 594 595 596 597
	
	def _class_is_refcountable(self, _class):
		if _class.name in self.forcedRefcountableClasses:
			return True
		
		for method in _class.instanceMethods:
			if method.startswith(_class.cFunctionPrefix) and method[len(_class.cFunctionPrefix):] == 'ref':
				return True
		return False
	
598 599 600 601 602 603 604
	def _fix_all_types_in_class_or_interface(self, _class):
		if _class is not None:
			if type(_class) is Class:
				self._fix_all_types_in_class(_class)
			else:
				self._fix_all_types_in_interface(_class)
	
605
	def _fix_all_types(self):
606 607 608 609
		for _class in self.interfacesIndex.values():
			self._fix_all_types_in_class_or_interface(_class)
		for _class in self.classesIndex.values():
			self._fix_all_types_in_class_or_interface(_class)
610 611 612 613
	
	def _fix_all_types_in_class(self, _class):
		for property in _class.properties:
			if property.setter is not None:
614
				self._fix_all_types_in_method(property.setter)
615
			if property.getter is not None:
616
				self._fix_all_types_in_method(property.getter)
617 618
		
		for method in (_class.instanceMethods + _class.classMethods):
619
			self._fix_all_types_in_method(method)
620 621 622
	
	def _fix_all_types_in_interface(self, interface):
		for method in interface.methods:
623
			self._fix_all_types_in_method(method)
624 625 626
	
	def _fix_all_types_in_method(self, method):
		try:
627
			self._fix_type(method.returnType)
628
			for arg in method.args:
629
				self._fix_type(arg.type)
630 631
		except ParsingError as e:
			raise ParsingError(e, method.name)
632
		
633 634 635 636 637 638
	def _fix_type(self, _type):
		if isinstance(_type, EnumType) and _type.desc is None:
			_type.desc = self.enumsIndex[_type.name]
		elif isinstance(_type, ClassType) and _type.desc is None:
			if _type.name in self.classesIndex:
				_type.desc = self.classesIndex[_type.name]
639
			else:
640 641 642 643 644 645 646 647
				_type.desc = self.interfacesIndex[_type.name]
		elif isinstance(_type, ListType) and _type.containedTypeDesc is None:
			if _type.containedTypeName in self.classesIndex:
				_type.containedTypeDesc = ClassType(_type.containedTypeName, classDesc=self.classesIndex[_type.containedTypeName])
			elif _type.containedTypeName in self.interfacesIndex:
				_type.containedTypeDesc = ClassType(_type.containedTypeName, classDesc=self.interfacesIndex[_type.containedTypeName])
			elif _type.containedTypeName in self.enumsIndex:
				_type.containedTypeDesc = EnumType(_type.containedTypeName, enumDesc=self.enumsIndex[_type.containedTypeName])
648
			else:
649
				if _type.containedTypeName is not None:
650
					_type.containedTypeDesc = self.parse_c_base_type(_type.containedTypeName)
651
				else:
652
					raise ParsingError('bctbx_list_t type without specified contained type')
653
	
654 655
	def _fix_all_docs(self):
		for _class in self.classesIndex.values():
656 657 658 659 660
			self._fix_doc(_class)
		for enum in self.enumsIndex.values():
			self._fix_doc(enum)
			for enumerator in enum.enumerators:
				self._fix_doc(enumerator)
661
		for method in self.methodsIndex.values():
662 663 664 665 666 667 668
			self._fix_doc(method)
	
	def _fix_doc(self, obj):
		if obj.briefDescription is not None:
			obj.briefDescription.resolve_all_references(self)
		if obj.detailedDescription is not None:
			obj.detailedDescription.resolve_all_references(self)
669
	
670
	def parse_enum(self, cenum):
671
		name = metaname.EnumName()
672
		name.from_camel_case(cenum.publicName, namespace=self.namespace.name)
673
		enum = Enum(name)
674
		enum.briefDescription = cenum.briefDoc
675
		enum.detailedDescription = cenum.detailedDoc
676
		self.namespace.addenum(enum)
677 678
		
		for cEnumValue in cenum.values:
679
			valueName = metaname.EnumeratorName()
680
			valueName.from_camel_case(cEnumValue.name, namespace=name)
681
			aEnumValue = Enumerator(valueName)
682
			aEnumValue.briefDescription = cEnumValue.briefDoc
683
			aEnumValue.detailedDescription = cEnumValue.detailedDoc
684 685 686 687
			if cEnumValue.value is not None:
				try:
					aEnumValue.value_from_string(cEnumValue.value)
				except ValueError:
688 689 690 691
					reason = '{0} enum value has an invalid definition ({1})'.format(cEnumValue.name, cEnumValue.value)
					context = metaname.EnumeratorName()
					context.from_camel_case(cEnumValue.name)
					raise ParsingError(reason, context)
692
			enum.add_enumerator(aEnumValue)
693
		
694
		self.enumsIndex[cenum.publicName] = enum
695 696
		if cenum.publicName in self.enum_relocations:
			self._pending_enums.append(enum)
697 698 699 700
		return enum
	
	def parse_class(self, cclass):
		if cclass.name in self.classBl:
701 702 703
			name = metaname.ClassName()
			name.from_snake_case(cclass.name)
			raise BlacklistedSymbolError(name)
704 705
		
		if cclass.name.endswith('Cbs'):
706
			_class = self._parse_listener(cclass)
707
			self.interfacesIndex[cclass.name] = _class
708
			self.namespace.addinterface(_class)
709
		else:
710
			_class = self._parse_class(cclass)
711
			self.classesIndex[cclass.name] = _class
712
			self.namespace.addclass(_class)
713 714 715
		return _class
	
	def _parse_class(self, cclass):
716
		name = metaname.ClassName()
717 718
		name.from_camel_case(cclass.name, namespace=self.namespace.name)
		_class = Class(name)
719
		_class.briefDescription = cclass.briefDoc
720
		_class.detailedDescription = cclass.detailedDoc
721
		_class.refcountable = self._class_is_refcountable(cclass)
722 723 724 725
		
		for cproperty in cclass.properties.values():
			try:
				if cproperty.name != 'callbacks':
726
					absProperty = self._parse_property(cproperty, namespace=name)
727 728 729
					_class.add_property(absProperty)
				else:
					_class.listenerInterface = self.interfacesIndex[cproperty.getter.returnArgument.ctype]
730 731
			except BlacklistedSymbolError as e:
				logger.debug(e)
732 733 734
		
		for cMethod in cclass.instanceMethods.values():
			try:
735
				method = self.parse_method(cMethod, namespace=name)
736 737 738 739 740 741 742 743
				if method.name.to_snake_case() == 'add_callbacks' or method.name.to_snake_case() == 'remove_callbacks':
					if _class.listenerInterface is None or not _class.multilistener:
						_class.multilistener = True
						_class.listenerInterface = self.interfacesIndex[_class.name.to_camel_case(fullName=True) + 'Cbs']
				elif isinstance(method.returnType, ClassType) and method.returnType.name.endswith('Cbs'):
					pass
				else:
					_class.add_instance_method(method)
744 745 746
			except BlacklistedSymbolError as e:
				logger.debug(e)
		
747 748
		for cMethod in cclass.classMethods.values():
			try:
749
				method = self.parse_method(cMethod, type=Method.Type.Class, namespace=name)
750
				_class.add_class_method(method)
751 752
			except BlacklistedSymbolError as e:
				logger.debug(e)
753 754 755 756
		
		return _class
	
	def _parse_property(self, cproperty, namespace=None):
757
		name = metaname.PropertyName()
758 759 760 761 762 763 764
		name.from_snake_case(cproperty.name)
		if (cproperty.setter is not None and len(cproperty.setter.arguments) == 1) or (cproperty.getter is not None and len(cproperty.getter.arguments) == 0):
			methodType = Method.Type.Class
		else:
			methodType = Method.Type.Instance
		aproperty = Property(name)
		if cproperty.setter is not None:
765
			method = self.parse_method(cproperty.setter, namespace=namespace, type=methodType)
766 767
			aproperty.setter = method
		if cproperty.getter is not None:
768
			method = self.parse_method(cproperty.getter, namespace=namespace, type=methodType)
769 770 771 772 773
			aproperty.getter = method
		return aproperty
	
	
	def _parse_listener(self, cclass):
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
		try:
			name = metaname.InterfaceName()
			name.from_camel_case(cclass.name, namespace=self.namespace.name)
			name.words[-1] = 'listener'
			
			listener = Interface(name)
			listener.briefDescription = cclass.briefDoc
			listener.detailedDescription = cclass.detailedDoc
			
			for property in cclass.properties.values():
				if property.name != 'user_data':
					try:
						method = self._parse_listener_property(property, listener, cclass.events)
						listener.add_method(method)
					except BlacklistedSymbolError as e:
						logger.debug(e)
			
			return listener
		except ParsingError as e:
			context = metaname.ClassName()
			context.from_camel_case(cclass.name)
			raise ParsingError(e, context)
796 797
	
	def _parse_listener_property(self, property, listener, events):
798
		methodName = metaname.MethodName()
799 800 801 802 803 804 805 806 807
		methodName.from_snake_case(property.name)
		methodName.words.insert(0, 'on')
		methodName.prev = listener.name
		
		if property.getter is not None:
			eventName = property.getter.returnArgument.ctype
		elif property.setter is not None and len(property.setter.arguments) == 2:
			eventName = property.setter.arguments[1].ctype
		else:
808
			raise ParsingError('event name for {0} property of {1} listener not found'.format(property.name, listener.name.to_c()))
809 810 811 812
		
		try:
			event = events[eventName]
		except KeyError:
813
			raise ParsingError('invalid event name \'{0}\''.format(eventName))
814 815
		
		method = Method(methodName)
816
		method.returnType = self.parse_type(event.returnArgument)
817
		for arg in event.arguments:
818
			argName = metaname.ArgName()
819
			argName.from_snake_case(arg.name)
820
			argument = Argument(argName, self.parse_type(arg))
821 822 823 824 825
			method.add_arguments(argument)
		
		return method
	
	def parse_method(self, cfunction, namespace, type=Method.Type.Instance):
826
		name = metaname.MethodName()
827 828
		name.from_snake_case(cfunction.name, namespace=namespace)
		
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
		try:
			if self._is_blacklisted(name):
				raise BlacklistedSymbolError(name)
			
			method = Method(name, type=type)
			method.briefDescription = cfunction.briefDoc
			method.detailedDescription = cfunction.detailedDoc
			method.deprecated = cfunction.deprecated
			method.returnType = self.parse_type(cfunction.returnArgument)
			
			for arg in cfunction.arguments:
				if type == Method.Type.Instance and arg is cfunction.arguments[0]:
					method.isconst = ('const' in arg.completeType.split(' '))
				else:
					aType = self.parse_type(arg)
					argName = metaname.ArgName()
					argName.from_snake_case(arg.name)
					absArg = Argument(argName, aType)
					method.add_arguments(absArg)
			
			self.methodsIndex[cfunction.name] = method
			return method
		except ParsingError as e:
			raise ParsingError(e, name)
853 854 855
	
	def parse_type(self, cType):
		if cType.ctype in self.cBaseType or re.match(self.regexFixedSizeInteger, cType.ctype):
856
			absType = self.parse_c_base_type(cType.completeType)
857 858 859 860
		elif cType.ctype in self.enumsIndex:
			absType = EnumType(cType.ctype, enumDesc=self.enumsIndex[cType.ctype])
		elif cType.ctype in self.classesIndex or cType.ctype in self.interfacesIndex:
			absType = ClassType(cType.ctype)
861
			absType.isconst = cType.completeType.startswith('const ')
862
			absType.isref = cType.completeType.endswith('*')
863 864
		elif cType.ctype == self.cListType:
			absType = ListType(cType.containedType)
François Grisez's avatar
François Grisez committed
865 866
		elif cType.ctype.endswith('Mask'):
			absType = BaseType('integer', isUnsigned=True)
867
		else:
868
			raise ParsingError('Unknown C type \'{0}\''.format(cType.ctype))
869
		
870
		absType.cDecl = cType.completeType
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
		return absType
	
	def parse_c_base_type(self, cDecl):
		declElems = cDecl.split(' ')
		param = {}
		name = None
		for elem in declElems:
			if elem == 'const':
				if name is None:
					param['isconst'] = True
			elif elem == 'unsigned':
				param['isUnsigned'] = True
			elif elem == 'char':
				name = 'character'
			elif elem == 'void':
				name = 'void'
			elif elem == 'bool_t':
				name = 'boolean'
			elif elem in ['short', 'long']:
				param['size'] = elem
			elif elem == 'int':
				name = 'integer'
			elif elem == 'float':
				name = 'floatant'
				param['size'] = 'float'
			elif elem == 'size_t':
				name = 'size'
			elif elem == 'time_t':
				name = 'time'
			elif elem == 'double':
				name = 'floatant'
				if 'size' in param and param['size'] == 'long':
					param['size'] = 'long double'
				else:
					param['size'] = 'double'
906 907
			elif elem == 'LinphoneStatus':
				name = 'status'
908 909 910 911 912 913 914 915 916
			elif elem == '*':
				if name is not None:
					if name == 'character':
						name = 'string'
					elif name == 'string':
						name = 'string_array'
					elif 'isref' not in param or param['isref'] is False:
						param['isref'] = True
					else:
917
						raise ParsingError('Unhandled double-pointer')
918 919 920 921 922 923 924 925 926
			else:
				matchCtx = re.match(self.regexFixedSizeInteger, elem)
				if matchCtx:
					name = 'integer'
					if matchCtx.group(1) == 'u':
						param['isUnsigned'] = True
					
					param['size'] = int(matchCtx.group(2))
					if param['size'] not in [8, 16, 32, 64]:
927
						raise ParsingError('{0} C basic type has an invalid size ({1})'.format(cDecl, param['size']))
928 929 930 931 932
		
		
		if name is not None:
			return BaseType(name, **param)
		else:
933
			raise ParsingError('could not find type in \'{0}\''.format(cDecl))
934 935


936

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
class Translator:
	instances = {}
	
	@staticmethod
	def get(langCode):
		try:
			if langCode not in Translator.instances:
				className = langCode + 'LangTranslator'
				_class = globals()[className]
				Translator.instances[langCode] = _class()
			
			return Translator.instances[langCode]
		except KeyError:
			raise ValueError("Invalid language code: '{0}'".format(langCode))

952 953 954 955 956 957 958
	def _get_object_name(self, obj):
		return obj.desc.name if isinstance(obj, (EnumType, ClassType)) else obj.name

	def _compute_namespace_name(self, namespace, obj):
		if namespace is not None:
			return namespace.name if namespace is not GlobalNs else None
		else:
959
			namespace = obj.find_first_ancestor_by_type(Enum, Class, Namespace, Interface)
960 961
			return metaname.Name.find_common_parent(self._get_object_name(obj), namespace.name)

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007

class CLikeLangTranslator(Translator):
	def translate_enumerator_value(self, value):
		if value is None:
			return None
		elif isinstance(value, int):
			return str(value)
		elif isinstance(value, Flag):
			return '1<<{0}'.format(value.position)
		else:
			raise TypeError('invalid enumerator value type: {0}'.format(value))
	
	def translate_argument(self, argument, **kargs):
		return '{0} {1}'.format(argument.type.translate(self, **kargs), argument.name.translate(self.nameTranslator))


class CLangTranslator(CLikeLangTranslator):
	def __init__(self):
		self.nameTranslator = metaname.Translator.get('C')
		self.nilToken = 'NULL'
		self.falseConstantToken = 'FALSE'
		self.trueConstantToken = 'TRUE'
	
	def translate_base_type(self, _type):
		return _type.cDecl
	
	def translate_enum_type(self, _type):
		return _type.cDecl
	
	def translate_class_type(self, _type):
		return _type.cDecl
	
	def translate_list_type(self, _type):
		return _type.cDecl
	
	def translate_enumerator_value(self, value):
		if value is None:
			return None
		elif isinstance(value, int):
			return str(value)
		elif isinstance(value, Flag):
			return '1<<{0}'.format(value.position)
		else:
			raise TypeError('invalid enumerator value type: {0}'.format(value))
	
	def translate_method_as_prototype(self, method, **params):
1008
		_class = method.find_first_ancestor_by_type(Class)
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
		params = '{const}{className} *obj'.format(
			className=_class.name.to_c(),
			const='const ' if method.isconst else ''
		)
		for arg in method.args:
			params += (', ' + arg.translate(self))
		
		return '{returnType} {name}({params})'.format(
			returnType=method.returnType.translate(self),
			name=method.name.translate(self.nameTranslator),
			params=params
		)


class CppLangTranslator(CLikeLangTranslator):
	def __init__(self):
		self.nameTranslator = metaname.Translator.get('Cpp')
		self.nilToken = 'nullptr'
		self.falseConstantToken = 'false'
		self.trueConstantToken = 'true'
		self.ambigousTypes = []
	
	def translate_base_type(self, _type, showStdNs=True, namespace=None):
		if _type.name == 'void':
			if _type.isref:
				return 'void *'
			else:
				return 'void'
		elif _type.name == 'boolean':
			res = 'bool'
		elif _type.name == 'character':
			res = 'char'
		elif _type.name == 'size':
			res = 'size_t'
		elif _type.name == 'time':
			res = 'time_t'
		elif _type.name == 'integer':
			if _type.size is None:
				res = 'int'
			elif isinstance(_type.size, str):
				res = _type.size
			else:
				res = 'int{0}_t'.format(_type.size)
				
		elif _type.name == 'floatant':
			if _type.size is not None and _type.size == 'double':
				res = 'double'
			else:
				res = 'float'
		elif _type.name == 'status':
			res = 'linphone::Status'
		elif _type.name == 'string':
			res = CppLangTranslator.prepend_std('string', showStdNs)
			if type(_type.parent) is Argument:
				res += ' &'
		elif _type.name == 'string_array':
			res = '{0}<{1}>'.format(
				CppLangTranslator.prepend_std('list', showStdNs),
				CppLangTranslator.prepend_std('string', showStdNs)
			)
			if type(_type.parent) is Argument:
				res += ' &'
		else:
1072
			raise TranslationError('\'{0}\' is not a base abstract type'.format(_type.name))
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
		
		if _type.isUnsigned:
			if _type.name == 'integer' and isinstance(_type.size, int):
				res = 'u' + res
			else:
				res = 'unsigned ' + res
		
		if _type.isconst:
			if _type.name not in ['string', 'string_array'] or type(_type.parent) is Argument:
				res = 'const ' + res
		
		if _type.isref:
			res += ' *'
		return res
	
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
	def translate_enum_type(self, type_, showStdNs=True, namespace=None):
		if type_.desc is None:
			raise TranslationError('{0} has not been fixed'.format(type_.name))
		nsName = self._compute_namespace_name(namespace, type_)
		return type_.desc.name.translate(self.nameTranslator, recursive=True, topAncestor=nsName)

	def translate_class_type(self, type_, showStdNs=True, namespace=None):
		if type_.desc is None:
			raise TranslationError('{0} has not been fixed'.format(type_.name))
		nsName = self._compute_namespace_name(namespace, type_)
		res = type_.desc.name.translate(self.nameTranslator, recursive=True, topAncestor=nsName)
1099
		
1100 1101
		if type_.desc.refcountable:
			if type_.isconst:
1102
				res = 'const ' + res
1103
			if type(type_.parent) is Argument:
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
				return 'const {0}<{1}> &'.format(
					CppLangTranslator.prepend_std('shared_ptr', showStdNs),
					res
				)
			else:
				return '{0}<{1}>'.format(
					CppLangTranslator.prepend_std('shared_ptr', showStdNs),
					res
				)
		else:
1114
			if type(type_.parent) is Argument:
1115 1116 1117 1118 1119 1120
				return 'const {0} &'.format(res)
			else:
				return '{0}'.format(res)
	
	def translate_list_type(self, _type, showStdNs=True, namespace=None):
		if _type.containedTypeDesc is None:
1121
			raise TranslationError('{0} has not been fixed'.format(_type.containedTypeName))