コード例 #1
0
	def __init__(self):
		"""
		Instantiate an empty tree.
		"""
		self.__contents = None
		self.__elements = SortedDict()
コード例 #2
0
class ParseTree(object):
	"""
	A parse tree to model an expression parsing.

	It is returned by the L{read<lect.Lect.read>} method of class C{Lect}.
	"""
	def __init__(self):
		"""
		Instantiate an empty tree.
		"""
		self.__contents = None
		self.__elements = SortedDict()

	def add_recognition(self, recognition):
		"""
		Add a list of expression parsings to the tree, calling the L{add} method.

		@param recognition: A list of expression parsings.
		@type recognition: list of C{(item, path)} tuples
		"""
		for item, path in recognition:
			self.add(item, path)

	def iter_children(self, path):
		"""
		Return an iterator to the subtrees below a given position.

		@param path: A tree path.
		@type path: list of str

		@return: The child trees below a given position.
		@rtype: iterator of ParseTree
		"""
		return self.__elements.items()

	def subtree(self, path):
		"""
		Return the subtree at a given position.

		@param path: A tree path.
		@type path: list of str

		@return: The child tree at given position.
		@rtype: ParseTree
		"""
		st = self
		for segm in path:
			st = st.__elements[segm]
		return st

	def iter_items(self):
		"""
		Return an iterator to the items.

		@rtype: iterator of items
		"""
		for i in self.__contents:
			yield i

	def add(self, item, path):
		"""
		Add an expression parsing to the tree.

		If another item exists at the given position, the new item is appended, otherwise the new position is created with the item only.

		@param item: An expression parsing.
		@type item: C{(item, path)} tuples
		@param path: A tree path.
		@type path: list of str
		"""
		if len(path) == 0:
			return
		st = self
		for segm in path:
			if segm in st.__elements:
				st = st.__elements[segm]
			else:
				nst = ParseTree()
				st.__elements[segm] = nst
				st = nst
		if st.__contents is None:
			st.__contents = [item]
		else:
			st.__contents.append(item)

	def __repr__(self):
		"""
		Compute a representation for the parse tree.

		@rtype: str
		"""
		s = []
		if self.__elements:
			s.append(Utilities.dict_str(self.__elements))
		if self.__contents:
			s.append(str(self.__contents))
		return " = ".join(s)