metaname.py 9.55 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
# 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.


import re


class Name(object):
	camelCaseParsingRegex = re.compile('[A-Z][a-z0-9]*')
	lowerCamelCaseSplitingRegex = re.compile('([a-z][a-z0-9]*)([A-Z][a-z0-9]*)')
	
	def __init__(self):
		self.words = []
		self.prev = None
	
	def __eq__(self, other):
		return (other is not None and self.words == other.words) and (self.prev == other.prev)
	
	def __lt__(self, other):
		return self.to_camel_case() < other.to_camel_case()
	
	def copy(self):
		nameType = type(self)
		name = nameType()
		name.words = list(self.words)
		name.prev = None if self.prev is None else self.prev.copy()
		return name
	
	def delete_prefix(self, prefix):
		it = self
		_next = None
		while it is not None and it.words != prefix.words:
			_next = it
			it = it.prev
		
		if it is None or it != prefix:
			raise Error('no common prefix')
		elif _next is not None:
			_next.prev = None
	
	def _set_namespace(self, namespace):
		self.prev = namespace
		if self.prev is not None:
			prefix = namespace.to_word_list()
			i = 0
			while i<len(self.words) and i<len(prefix) and self.words[i] == prefix[i]:
				i += 1
			if i == len(self.words):
				raise Error('name equal to namespace \'{0}\'', self.words)
			else:
				self.words = self.words[i:]
	
	def _lower_all_words(self):
		i = 0
		while i<len(self.words):
			self.words[i] = self.words[i].lower()
			i += 1
	
	def from_snake_case(self, name, namespace=None):
		self.words = name.split('_')
		Name._set_namespace(self, namespace)
	
	def from_camel_case(self, name, islowercased=False, namespace=None):
		if not islowercased:
			self.words = Name.camelCaseParsingRegex.findall(name)
		else:
			match = Name.lowerCamelCaseSplitingRegex.match(name)
			self.words = [match.group(1)]
			self.words += Name.camelCaseParsingRegex.findall(match.group(2))
		
		Name._lower_all_words(self)
		Name._set_namespace(self, namespace)
	
	def to_snake_case(self, fullName=False, upper=False):
		if self.prev is None or not fullName:
			res = '_'.join(self.words)
			if upper:
				res = res.upper()
			return res
		else:
			return Name.to_snake_case(self.prev, fullName=True, upper=upper) + '_' + Name.to_snake_case(self, upper=upper)
	
	def to_camel_case(self, lower=False, fullName=False):
		if self.prev is None or not fullName:
			res = ''
			for elem in self.words:
				if elem is self.words[0] and lower:
					res += elem
				else:
					res += elem.title()
			return res
		else:
			return Name.to_camel_case(self.prev, fullName=True, lower=lower) + Name.to_camel_case(self)
	
	def concatenate(self, upper=False, fullName=False):
		if self.prev is None or not fullName:
			res = ''
			for elem in self.words:
				if upper:
					res += elem.upper()
				else:
					res += elem
			return res
		else:
			return Name.concatenate(self.prev, upper=upper, fullName=True) + Name.concatenate(self, upper=upper)
	
	def to_word_list(self):
		if self.prev is None:
			return list(self.words)
		else:
			return Name.to_word_list(self.prev) + self.words
	
	def is_prefix_of(self, other):
		node = other
		while node is not None and node != self:
			node = node.prev
		return (node is not None)
	
	@staticmethod
	def find_common_parent(name1, name2):
		if name1.prev is None or name2.prev is None:
			return None
		elif name1.prev is name2.prev:
			return name1.prev
		else:
			commonParent = Name.find_common_parent(name1.prev, name2)
			if commonParent is not None:
				return commonParent
			else:
				return Name.find_common_parent(name1, name2.prev)


class ClassName(Name):
	def to_c(self):
		return self.to_camel_case(fullName=True)
	
	def translate(self, translator, **params):
		return translator.translate_class_name(self, **params)


class InterfaceName(ClassName):
	def to_c(self):
		return ClassName.to_c(self)[:-8] + 'Cbs'
	
	def translate(self, translator, **params):
		return translator.translate_interface_name(self, **params)


class EnumName(ClassName):
	def translate(self, translator, **params):
		return translator.translate_enum_name(self, **params)


class EnumeratorName(ClassName):
	def translate(self, translator, **params):
		return translator.translate_enumerator_name(self, **params)


class MethodName(Name):
	regex = re.compile('^\d+$')
	
	def __init__(self):
		self.overloadRef = 0
	
	def from_snake_case(self, name, namespace=None):
		Name.from_snake_case(self, name, namespace=namespace)
		if len(self.words) > 0:
			suffix = self.words[-1]
			if MethodName.regex.match(suffix) is not None:
				self.overloadRef = int(suffix)
				del self.words[-1]
	
	def to_c(self):
		suffix = ('_' + str(self.overloadRef)) if self.overloadRef > 0 else ''
		return self.to_snake_case(fullName=True) + suffix
	
	def translate(self, translator, **params):
		return translator.translate_method_name(self, **params)


class ArgName(Name):
	def to_c(self):
		return self.to_snake_case()
	
	def translate(self, translator, **params):
		return translator.translate_argument_name(self, **params)


class PropertyName(ArgName):
	def translate(self, translator, **params):
		return translator.translate_property_name(self, **params)


class NamespaceName(Name):
	def __init__(self, *params):
		Name.__init__(self)
		if len(params) > 0:
			self.words = params[0]
	
	def translate(self, translator, **params):
		return translator.translate_namespace_name(self, **params)


class Translator:
	instances = {}
	
	@staticmethod
	def get(langCode):
		try:
			if langCode == '':
				raise ValueError('Empty language code')
			if langCode not in Translator.instances:
				className = langCode + 'Translator'
				_class = globals()[className]
				Translator.instances[langCode] = _class()
			
			return Translator.instances[langCode]
		except KeyError:
			raise ValueError("Invalid language code: '{0}'".format(langCode))


class CTranslator(Translator):
	def translate_class_name(self, name, **params):
		return name.to_c()
	
	def translate_interface_name(self, name, **params):
		return name.to_c()
	
	def translate_enum_name(self, name, **params):
		return name.to_c()
	
	def translate_enumerator_name(self, name, **params):
		return name.to_c()
	
	def translate_method_name(self, name, **params):
		return name.to_c()
	
	def translate_namespace_name(self, name, **params):
		return None
	
	def translate_argument_name(self, name, **params):
		return name.to_c()
	
	def translate_property_name(self, name, **params):
		return name.to_c()


class JavaTranslator(Translator):
	def __init__(self):
		self.nsSep = '.'
		self.keyWordEscapes = {}
		self.lowerMethodNames = True
		self.lowerNamespaceNames = True
	
	def translate_class_name(self, name, recursive=False, topAncestor=None):
		if name.prev is None or not recursive or name.prev is topAncestor:
			return name.to_camel_case()
		else:
			params = {'recursive': recursive, 'topAncestor': topAncestor}
			return name.prev.translate(self, **params) + self.nsSep + name.to_camel_case()
	
	def translate_interface_name(self, name, **params):
		return self.translate_class_name(name, **params)
	
	def translate_enum_name(self, name, **params):
		return self.translate_class_name(name, **params)
	
	def translate_enumerator_name(self, name, **params):
		return self.translate_class_name(name, **params)
	
	def translate_method_name(self, name, recursive=False, topAncestor=None):
		translatedName = name.to_camel_case(lower=self.lowerMethodNames)
		translatedName = self._escape_keyword(translatedName)
		
		if name.prev is None or not recursive or name.prev is topAncestor:
			return translatedName
		else:
			params = {'recursive': recursive, 'topAncestor': topAncestor}
			return name.prev.translate(self, **params) + self.nsSep + translatedName
	
	def translate_namespace_name(self, name, recursive=False, topAncestor=None):
		translatedName = name.concatenate() if self.lowerNamespaceNames else name.to_camel_case()
		if name.prev is None or not recursive or name.prev is topAncestor:
			return translatedName
		else:
			params = {'recursive': recursive, 'topAncestor': topAncestor}
			return name.prev.translate(self, **params) + self.nsSep + translatedName
	
	def translate_argument_name(self, name):
		argname = name.to_camel_case(lower=True)
		return self._escape_keyword(argname)
	
	def translate_property_name(self, name):
		return self.translate_argument_name(name)
	
	def _escape_keyword(self, keyword):
		try:
			return self.keyWordEscapes[keyword]
		except KeyError:
			return keyword


class CppTranslator(JavaTranslator):
	def __init__(self):
		JavaTranslator.__init__(self)
		self.nsSep = '::'
		self.keyWordEscapes = {'new' : '_new'}
	
	def translate_enumerator_name(self, name, **params):
		return self.translate_enum_name(name.prev, **params) + name.to_camel_case()


class CSharpTranslator(JavaTranslator):
	def __init__(self):
		JavaTranslator.__init__(self)
		self.keyWordEscapes = {
			'params' : 'parameters',
			'event'  : 'ev',
			'ref'    : 'reference',
			'value'  : 'val',
			'new'    : '_new'
		}
		self.lowerMethodNames = False
		self.lowerNamespaceNames = False
	
	def translate_property_name(self, name):
		return name.to_camel_case()