Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# ======== End overridden functions
@property
def words(self):
""" Iterates over words, but without spaces. Like Unspaced List. """
return [word.strip("\"\'") for word in self._data if not word.isspace()]
def __getitem__(self, index):
return self.words[index]
def __contains__(self, word):
return word in self.words
class Block(Parsable):
""" Any sort of bloc, denoted by a block name and curly braces, like so:
The parsed block:
block name {
content 1;
content 2;
}
might be represented with the list [names, contents], where
names = ["block", " ", "name", " "]
contents = [["\n ", "content", " ", "1"], ["\n ", "content", " ", "2"], "\n"]
"""
def __init__(self, parent=None):
super(Block, self).__init__(parent)
self.names = None # type: Sentence
self.contents = None # type: Block
@staticmethod
def dump(self, include_spaces=False):
""" Dumps back to pyparsing-like list tree. The opposite of `parse`.
Note: if this object has not been modified, `dump` with `include_spaces=True`
should always return the original input of `parse`.
:param bool include_spaces: If set to False, magically hides whitespace tokens from
dumped output.
:returns: Pyparsing-like list tree.
:rtype list:
"""
return [elem.dump(include_spaces) for elem in self._data]
class Statements(Parsable):
""" A group or list of "Statements". A Statement is either a Block or a Sentence.
The underlying representation is simply a list of these Statement objects, with
an extra `_trailing_whitespace` string to keep track of the whitespace that does not
precede any more statements.
"""
def __init__(self, parent=None):
super(Statements, self).__init__(parent)
self._trailing_whitespace = None
# ======== Begin overridden functions
@staticmethod
def should_parse(lists):
return isinstance(lists, list)
yield sub_elem
# ======== End overridden functions
def _space_list(list_):
""" Inserts whitespace between adjacent non-whitespace tokens. """
spaced_statement = [] # type: List[str]
for i in reversed(six.moves.xrange(len(list_))):
spaced_statement.insert(0, list_[i])
if i > 0 and not list_[i].isspace() and not list_[i-1].isspace():
spaced_statement.insert(0, " ")
return spaced_statement
class Sentence(Parsable):
""" A list of words. Non-whitespace words are typically separated with whitespace tokens. """
# ======== Begin overridden functions
@staticmethod
def should_parse(lists):
""" Returns True if `lists` can be parseable as a `Sentence`-- that is,
every element is a string type.
:param list lists: The raw unparsed list to check.
:returns: whether this lists is parseable by `Sentence`.
"""
return isinstance(lists, list) and len(lists) > 0 and \
all([isinstance(elem, six.string_types) for elem in lists])