Represents a qualified name.
| 63 | |
| 64 | # TODO(mdan): Use subclasses to remove the has_attr has_subscript booleans. |
| 65 | class QN(object): |
| 66 | """Represents a qualified name.""" |
| 67 | |
| 68 | def __init__(self, base, attr=None, subscript=None): |
| 69 | if attr is not None and subscript is not None: |
| 70 | raise ValueError('A QN can only be either an attr or a subscript, not ' |
| 71 | 'both: attr={}, subscript={}.'.format(attr, subscript)) |
| 72 | self._has_attr = False |
| 73 | self._has_subscript = False |
| 74 | |
| 75 | if attr is not None: |
| 76 | if not isinstance(base, QN): |
| 77 | raise ValueError( |
| 78 | 'for attribute QNs, base must be a QN; got instead "%s"' % base) |
| 79 | if not isinstance(attr, str): |
| 80 | raise ValueError('attr may only be a string; got instead "%s"' % attr) |
| 81 | self._parent = base |
| 82 | # TODO(mdan): Get rid of the tuple - it can only have 1 or 2 elements now. |
| 83 | self.qn = (base, attr) |
| 84 | self._has_attr = True |
| 85 | |
| 86 | elif subscript is not None: |
| 87 | if not isinstance(base, QN): |
| 88 | raise ValueError('For subscript QNs, base must be a QN.') |
| 89 | self._parent = base |
| 90 | self.qn = (base, subscript) |
| 91 | self._has_subscript = True |
| 92 | |
| 93 | else: |
| 94 | if not isinstance(base, (str, StringLiteral, NumberLiteral)): |
| 95 | # TODO(mdan): Require Symbol instead of string. |
| 96 | raise ValueError( |
| 97 | 'for simple QNs, base must be a string or a Literal object;' |
| 98 | ' got instead "%s"' % type(base)) |
| 99 | assert '.' not in base and '[' not in base and ']' not in base |
| 100 | self._parent = None |
| 101 | self.qn = (base,) |
| 102 | |
| 103 | def is_symbol(self): |
| 104 | return isinstance(self.qn[0], str) |
| 105 | |
| 106 | def is_simple(self): |
| 107 | return len(self.qn) <= 1 |
| 108 | |
| 109 | def is_composite(self): |
| 110 | return len(self.qn) > 1 |
| 111 | |
| 112 | def has_subscript(self): |
| 113 | return self._has_subscript |
| 114 | |
| 115 | def has_attr(self): |
| 116 | return self._has_attr |
| 117 | |
| 118 | @property |
| 119 | def parent(self): |
| 120 | if self._parent is None: |
| 121 | raise ValueError('Cannot get parent of simple name "%s".' % self.qn[0]) |
| 122 | return self._parent |
no outgoing calls