You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

581 lines
22 KiB

  1. # Configurable Element class lookup
  2. ################################################################################
  3. # Custom Element classes
  4. cdef public class ElementBase(_Element) [ type LxmlElementBaseType,
  5. object LxmlElementBase ]:
  6. """ElementBase(*children, attrib=None, nsmap=None, **_extra)
  7. The public Element class. All custom Element classes must inherit
  8. from this one. To create an Element, use the `Element()` factory.
  9. BIG FAT WARNING: Subclasses *must not* override __init__ or
  10. __new__ as it is absolutely undefined when these objects will be
  11. created or destroyed. All persistent state of Elements must be
  12. stored in the underlying XML. If you really need to initialize
  13. the object after creation, you can implement an ``_init(self)``
  14. method that will be called directly after object creation.
  15. Subclasses of this class can be instantiated to create a new
  16. Element. By default, the tag name will be the class name and the
  17. namespace will be empty. You can modify this with the following
  18. class attributes:
  19. * TAG - the tag name, possibly containing a namespace in Clark
  20. notation
  21. * NAMESPACE - the default namespace URI, unless provided as part
  22. of the TAG attribute.
  23. * HTML - flag if the class is an HTML tag, as opposed to an XML
  24. tag. This only applies to un-namespaced tags and defaults to
  25. false (i.e. XML).
  26. * PARSER - the parser that provides the configuration for the
  27. newly created document. Providing an HTML parser here will
  28. default to creating an HTML element.
  29. In user code, the latter three are commonly inherited in class
  30. hierarchies that implement a common namespace.
  31. """
  32. def __init__(self, *children, attrib=None, nsmap=None, **_extra):
  33. """ElementBase(*children, attrib=None, nsmap=None, **_extra)
  34. """
  35. cdef bint is_html = 0
  36. cdef _BaseParser parser
  37. cdef _Element last_child
  38. # don't use normal attribute access as it might be overridden
  39. _getattr = object.__getattribute__
  40. try:
  41. namespace = _utf8(_getattr(self, 'NAMESPACE'))
  42. except AttributeError:
  43. namespace = None
  44. try:
  45. ns, tag = _getNsTag(_getattr(self, 'TAG'))
  46. if ns is not None:
  47. namespace = ns
  48. except AttributeError:
  49. tag = _utf8(_getattr(_getattr(self, '__class__'), '__name__'))
  50. if b'.' in tag:
  51. tag = tag.split(b'.')[-1]
  52. try:
  53. parser = _getattr(self, 'PARSER')
  54. except AttributeError:
  55. parser = None
  56. for child in children:
  57. if isinstance(child, _Element):
  58. parser = (<_Element>child)._doc._parser
  59. break
  60. if isinstance(parser, HTMLParser):
  61. is_html = 1
  62. if namespace is None:
  63. try:
  64. is_html = _getattr(self, 'HTML')
  65. except AttributeError:
  66. pass
  67. _initNewElement(self, is_html, tag, namespace, parser,
  68. attrib, nsmap, _extra)
  69. last_child = None
  70. for child in children:
  71. if _isString(child):
  72. if last_child is None:
  73. _setNodeText(self._c_node,
  74. (_collectText(self._c_node.children) or '') + child)
  75. else:
  76. _setTailText(last_child._c_node,
  77. (_collectText(last_child._c_node.next) or '') + child)
  78. elif isinstance(child, _Element):
  79. last_child = child
  80. _appendChild(self, last_child)
  81. elif isinstance(child, type) and issubclass(child, ElementBase):
  82. last_child = child()
  83. _appendChild(self, last_child)
  84. else:
  85. raise TypeError, f"Invalid child type: {type(child)!r}"
  86. cdef class CommentBase(_Comment):
  87. """All custom Comment classes must inherit from this one.
  88. To create an XML Comment instance, use the ``Comment()`` factory.
  89. Subclasses *must not* override __init__ or __new__ as it is
  90. absolutely undefined when these objects will be created or
  91. destroyed. All persistent state of Comments must be stored in the
  92. underlying XML. If you really need to initialize the object after
  93. creation, you can implement an ``_init(self)`` method that will be
  94. called after object creation.
  95. """
  96. def __init__(self, text):
  97. # copied from Comment() factory
  98. cdef _Document doc
  99. cdef xmlDoc* c_doc
  100. if text is None:
  101. text = b''
  102. else:
  103. text = _utf8(text)
  104. c_doc = _newXMLDoc()
  105. doc = _documentFactory(c_doc, None)
  106. self._c_node = _createComment(c_doc, _xcstr(text))
  107. if self._c_node is NULL:
  108. raise MemoryError()
  109. tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
  110. _registerProxy(self, doc, self._c_node)
  111. self._init()
  112. cdef class PIBase(_ProcessingInstruction):
  113. """All custom Processing Instruction classes must inherit from this one.
  114. To create an XML ProcessingInstruction instance, use the ``PI()``
  115. factory.
  116. Subclasses *must not* override __init__ or __new__ as it is
  117. absolutely undefined when these objects will be created or
  118. destroyed. All persistent state of PIs must be stored in the
  119. underlying XML. If you really need to initialize the object after
  120. creation, you can implement an ``_init(self)`` method that will be
  121. called after object creation.
  122. """
  123. def __init__(self, target, text=None):
  124. # copied from PI() factory
  125. cdef _Document doc
  126. cdef xmlDoc* c_doc
  127. target = _utf8(target)
  128. if text is None:
  129. text = b''
  130. else:
  131. text = _utf8(text)
  132. c_doc = _newXMLDoc()
  133. doc = _documentFactory(c_doc, None)
  134. self._c_node = _createPI(c_doc, _xcstr(target), _xcstr(text))
  135. if self._c_node is NULL:
  136. raise MemoryError()
  137. tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
  138. _registerProxy(self, doc, self._c_node)
  139. self._init()
  140. cdef class EntityBase(_Entity):
  141. """All custom Entity classes must inherit from this one.
  142. To create an XML Entity instance, use the ``Entity()`` factory.
  143. Subclasses *must not* override __init__ or __new__ as it is
  144. absolutely undefined when these objects will be created or
  145. destroyed. All persistent state of Entities must be stored in the
  146. underlying XML. If you really need to initialize the object after
  147. creation, you can implement an ``_init(self)`` method that will be
  148. called after object creation.
  149. """
  150. def __init__(self, name):
  151. cdef _Document doc
  152. cdef xmlDoc* c_doc
  153. name_utf = _utf8(name)
  154. c_name = _xcstr(name_utf)
  155. if c_name[0] == c'#':
  156. if not _characterReferenceIsValid(c_name + 1):
  157. raise ValueError, f"Invalid character reference: '{name}'"
  158. elif not _xmlNameIsValid(c_name):
  159. raise ValueError, f"Invalid entity reference: '{name}'"
  160. c_doc = _newXMLDoc()
  161. doc = _documentFactory(c_doc, None)
  162. self._c_node = _createEntity(c_doc, c_name)
  163. if self._c_node is NULL:
  164. raise MemoryError()
  165. tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
  166. _registerProxy(self, doc, self._c_node)
  167. self._init()
  168. cdef int _validateNodeClass(xmlNode* c_node, cls) except -1:
  169. if c_node.type == tree.XML_ELEMENT_NODE:
  170. expected = ElementBase
  171. elif c_node.type == tree.XML_COMMENT_NODE:
  172. expected = CommentBase
  173. elif c_node.type == tree.XML_ENTITY_REF_NODE:
  174. expected = EntityBase
  175. elif c_node.type == tree.XML_PI_NODE:
  176. expected = PIBase
  177. else:
  178. assert False, f"Unknown node type: {c_node.type}"
  179. if not (isinstance(cls, type) and issubclass(cls, expected)):
  180. raise TypeError(
  181. f"result of class lookup must be subclass of {type(expected)}, got {type(cls)}")
  182. return 0
  183. ################################################################################
  184. # Element class lookup
  185. ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*)
  186. # class to store element class lookup functions
  187. cdef public class ElementClassLookup [ type LxmlElementClassLookupType,
  188. object LxmlElementClassLookup ]:
  189. """ElementClassLookup(self)
  190. Superclass of Element class lookups.
  191. """
  192. cdef _element_class_lookup_function _lookup_function
  193. cdef public class FallbackElementClassLookup(ElementClassLookup) \
  194. [ type LxmlFallbackElementClassLookupType,
  195. object LxmlFallbackElementClassLookup ]:
  196. """FallbackElementClassLookup(self, fallback=None)
  197. Superclass of Element class lookups with additional fallback.
  198. """
  199. cdef readonly ElementClassLookup fallback
  200. cdef _element_class_lookup_function _fallback_function
  201. def __cinit__(self):
  202. # fall back to default lookup
  203. self._fallback_function = _lookupDefaultElementClass
  204. def __init__(self, ElementClassLookup fallback=None):
  205. if fallback is not None:
  206. self._setFallback(fallback)
  207. else:
  208. self._fallback_function = _lookupDefaultElementClass
  209. cdef void _setFallback(self, ElementClassLookup lookup):
  210. """Sets the fallback scheme for this lookup method.
  211. """
  212. self.fallback = lookup
  213. self._fallback_function = lookup._lookup_function
  214. if self._fallback_function is NULL:
  215. self._fallback_function = _lookupDefaultElementClass
  216. def set_fallback(self, ElementClassLookup lookup not None):
  217. """set_fallback(self, lookup)
  218. Sets the fallback scheme for this lookup method.
  219. """
  220. self._setFallback(lookup)
  221. cdef inline object _callLookupFallback(FallbackElementClassLookup lookup,
  222. _Document doc, xmlNode* c_node):
  223. return lookup._fallback_function(lookup.fallback, doc, c_node)
  224. ################################################################################
  225. # default lookup scheme
  226. cdef class ElementDefaultClassLookup(ElementClassLookup):
  227. """ElementDefaultClassLookup(self, element=None, comment=None, pi=None, entity=None)
  228. Element class lookup scheme that always returns the default Element
  229. class.
  230. The keyword arguments ``element``, ``comment``, ``pi`` and ``entity``
  231. accept the respective Element classes.
  232. """
  233. cdef readonly object element_class
  234. cdef readonly object comment_class
  235. cdef readonly object pi_class
  236. cdef readonly object entity_class
  237. def __cinit__(self):
  238. self._lookup_function = _lookupDefaultElementClass
  239. def __init__(self, element=None, comment=None, pi=None, entity=None):
  240. if element is None:
  241. self.element_class = _Element
  242. elif issubclass(element, ElementBase):
  243. self.element_class = element
  244. else:
  245. raise TypeError, "element class must be subclass of ElementBase"
  246. if comment is None:
  247. self.comment_class = _Comment
  248. elif issubclass(comment, CommentBase):
  249. self.comment_class = comment
  250. else:
  251. raise TypeError, "comment class must be subclass of CommentBase"
  252. if entity is None:
  253. self.entity_class = _Entity
  254. elif issubclass(entity, EntityBase):
  255. self.entity_class = entity
  256. else:
  257. raise TypeError, "Entity class must be subclass of EntityBase"
  258. if pi is None:
  259. self.pi_class = None # special case, see below
  260. elif issubclass(pi, PIBase):
  261. self.pi_class = pi
  262. else:
  263. raise TypeError, "PI class must be subclass of PIBase"
  264. cdef object _lookupDefaultElementClass(state, _Document _doc, xmlNode* c_node):
  265. "Trivial class lookup function that always returns the default class."
  266. if c_node.type == tree.XML_ELEMENT_NODE:
  267. if state is not None:
  268. return (<ElementDefaultClassLookup>state).element_class
  269. else:
  270. return _Element
  271. elif c_node.type == tree.XML_COMMENT_NODE:
  272. if state is not None:
  273. return (<ElementDefaultClassLookup>state).comment_class
  274. else:
  275. return _Comment
  276. elif c_node.type == tree.XML_ENTITY_REF_NODE:
  277. if state is not None:
  278. return (<ElementDefaultClassLookup>state).entity_class
  279. else:
  280. return _Entity
  281. elif c_node.type == tree.XML_PI_NODE:
  282. if state is None or (<ElementDefaultClassLookup>state).pi_class is None:
  283. # special case XSLT-PI
  284. if c_node.name is not NULL and c_node.content is not NULL:
  285. if tree.xmlStrcmp(c_node.name, <unsigned char*>"xml-stylesheet") == 0:
  286. if tree.xmlStrstr(c_node.content, <unsigned char*>"text/xsl") is not NULL or \
  287. tree.xmlStrstr(c_node.content, <unsigned char*>"text/xml") is not NULL:
  288. return _XSLTProcessingInstruction
  289. return _ProcessingInstruction
  290. else:
  291. return (<ElementDefaultClassLookup>state).pi_class
  292. else:
  293. assert False, f"Unknown node type: {c_node.type}"
  294. ################################################################################
  295. # attribute based lookup scheme
  296. cdef class AttributeBasedElementClassLookup(FallbackElementClassLookup):
  297. """AttributeBasedElementClassLookup(self, attribute_name, class_mapping, fallback=None)
  298. Checks an attribute of an Element and looks up the value in a
  299. class dictionary.
  300. Arguments:
  301. - attribute name - '{ns}name' style string
  302. - class mapping - Python dict mapping attribute values to Element classes
  303. - fallback - optional fallback lookup mechanism
  304. A None key in the class mapping will be checked if the attribute is
  305. missing.
  306. """
  307. cdef object _class_mapping
  308. cdef tuple _pytag
  309. cdef const_xmlChar* _c_ns
  310. cdef const_xmlChar* _c_name
  311. def __cinit__(self):
  312. self._lookup_function = _attribute_class_lookup
  313. def __init__(self, attribute_name, class_mapping,
  314. ElementClassLookup fallback=None):
  315. self._pytag = _getNsTag(attribute_name)
  316. ns, name = self._pytag
  317. if ns is None:
  318. self._c_ns = NULL
  319. else:
  320. self._c_ns = _xcstr(ns)
  321. self._c_name = _xcstr(name)
  322. self._class_mapping = dict(class_mapping)
  323. FallbackElementClassLookup.__init__(self, fallback)
  324. cdef object _attribute_class_lookup(state, _Document doc, xmlNode* c_node):
  325. cdef AttributeBasedElementClassLookup lookup
  326. cdef python.PyObject* dict_result
  327. lookup = <AttributeBasedElementClassLookup>state
  328. if c_node.type == tree.XML_ELEMENT_NODE:
  329. value = _attributeValueFromNsName(
  330. c_node, lookup._c_ns, lookup._c_name)
  331. dict_result = python.PyDict_GetItem(lookup._class_mapping, value)
  332. if dict_result is not NULL:
  333. cls = <object>dict_result
  334. _validateNodeClass(c_node, cls)
  335. return cls
  336. return _callLookupFallback(lookup, doc, c_node)
  337. ################################################################################
  338. # per-parser lookup scheme
  339. cdef class ParserBasedElementClassLookup(FallbackElementClassLookup):
  340. """ParserBasedElementClassLookup(self, fallback=None)
  341. Element class lookup based on the XML parser.
  342. """
  343. def __cinit__(self):
  344. self._lookup_function = _parser_class_lookup
  345. cdef object _parser_class_lookup(state, _Document doc, xmlNode* c_node):
  346. if doc._parser._class_lookup is not None:
  347. return doc._parser._class_lookup._lookup_function(
  348. doc._parser._class_lookup, doc, c_node)
  349. return _callLookupFallback(<FallbackElementClassLookup>state, doc, c_node)
  350. ################################################################################
  351. # custom class lookup based on node type, namespace, name
  352. cdef class CustomElementClassLookup(FallbackElementClassLookup):
  353. """CustomElementClassLookup(self, fallback=None)
  354. Element class lookup based on a subclass method.
  355. You can inherit from this class and override the method::
  356. lookup(self, type, doc, namespace, name)
  357. to lookup the element class for a node. Arguments of the method:
  358. * type: one of 'element', 'comment', 'PI', 'entity'
  359. * doc: document that the node is in
  360. * namespace: namespace URI of the node (or None for comments/PIs/entities)
  361. * name: name of the element/entity, None for comments, target for PIs
  362. If you return None from this method, the fallback will be called.
  363. """
  364. def __cinit__(self):
  365. self._lookup_function = _custom_class_lookup
  366. def lookup(self, type, doc, namespace, name):
  367. "lookup(self, type, doc, namespace, name)"
  368. return None
  369. cdef object _custom_class_lookup(state, _Document doc, xmlNode* c_node):
  370. cdef CustomElementClassLookup lookup
  371. lookup = <CustomElementClassLookup>state
  372. if c_node.type == tree.XML_ELEMENT_NODE:
  373. element_type = "element"
  374. elif c_node.type == tree.XML_COMMENT_NODE:
  375. element_type = "comment"
  376. elif c_node.type == tree.XML_PI_NODE:
  377. element_type = "PI"
  378. elif c_node.type == tree.XML_ENTITY_REF_NODE:
  379. element_type = "entity"
  380. else:
  381. element_type = "element"
  382. if c_node.name is NULL:
  383. name = None
  384. else:
  385. name = funicode(c_node.name)
  386. c_str = tree._getNs(c_node)
  387. ns = funicode(c_str) if c_str is not NULL else None
  388. cls = lookup.lookup(element_type, doc, ns, name)
  389. if cls is not None:
  390. _validateNodeClass(c_node, cls)
  391. return cls
  392. return _callLookupFallback(lookup, doc, c_node)
  393. ################################################################################
  394. # read-only tree based class lookup
  395. cdef class PythonElementClassLookup(FallbackElementClassLookup):
  396. """PythonElementClassLookup(self, fallback=None)
  397. Element class lookup based on a subclass method.
  398. This class lookup scheme allows access to the entire XML tree in
  399. read-only mode. To use it, re-implement the ``lookup(self, doc,
  400. root)`` method in a subclass::
  401. from lxml import etree, pyclasslookup
  402. class MyElementClass(etree.ElementBase):
  403. honkey = True
  404. class MyLookup(pyclasslookup.PythonElementClassLookup):
  405. def lookup(self, doc, root):
  406. if root.tag == "sometag":
  407. return MyElementClass
  408. else:
  409. for child in root:
  410. if child.tag == "someothertag":
  411. return MyElementClass
  412. # delegate to default
  413. return None
  414. If you return None from this method, the fallback will be called.
  415. The first argument is the opaque document instance that contains
  416. the Element. The second argument is a lightweight Element proxy
  417. implementation that is only valid during the lookup. Do not try
  418. to keep a reference to it. Once the lookup is done, the proxy
  419. will be invalid.
  420. Also, you cannot wrap such a read-only Element in an ElementTree,
  421. and you must take care not to keep a reference to them outside of
  422. the `lookup()` method.
  423. Note that the API of the Element objects is not complete. It is
  424. purely read-only and does not support all features of the normal
  425. `lxml.etree` API (such as XPath, extended slicing or some
  426. iteration methods).
  427. See https://lxml.de/element_classes.html
  428. """
  429. def __cinit__(self):
  430. self._lookup_function = _python_class_lookup
  431. def lookup(self, doc, element):
  432. """lookup(self, doc, element)
  433. Override this method to implement your own lookup scheme.
  434. """
  435. return None
  436. cdef object _python_class_lookup(state, _Document doc, tree.xmlNode* c_node):
  437. cdef PythonElementClassLookup lookup
  438. cdef _ReadOnlyProxy proxy
  439. lookup = <PythonElementClassLookup>state
  440. proxy = _newReadOnlyProxy(None, c_node)
  441. cls = lookup.lookup(doc, proxy)
  442. _freeReadOnlyProxies(proxy)
  443. if cls is not None:
  444. _validateNodeClass(c_node, cls)
  445. return cls
  446. return _callLookupFallback(lookup, doc, c_node)
  447. ################################################################################
  448. # Global setup
  449. cdef _element_class_lookup_function LOOKUP_ELEMENT_CLASS
  450. cdef object ELEMENT_CLASS_LOOKUP_STATE
  451. cdef void _setElementClassLookupFunction(
  452. _element_class_lookup_function function, object state):
  453. global LOOKUP_ELEMENT_CLASS, ELEMENT_CLASS_LOOKUP_STATE
  454. if function is NULL:
  455. state = DEFAULT_ELEMENT_CLASS_LOOKUP
  456. function = DEFAULT_ELEMENT_CLASS_LOOKUP._lookup_function
  457. ELEMENT_CLASS_LOOKUP_STATE = state
  458. LOOKUP_ELEMENT_CLASS = function
  459. def set_element_class_lookup(ElementClassLookup lookup = None):
  460. """set_element_class_lookup(lookup = None)
  461. Set the global element class lookup method.
  462. This defines the main entry point for looking up element implementations.
  463. The standard implementation uses the :class:`ParserBasedElementClassLookup`
  464. to delegate to different lookup schemes for each parser.
  465. .. warning::
  466. This should only be changed by applications, not by library packages.
  467. In most cases, parser specific lookups should be preferred,
  468. which can be configured via
  469. :meth:`~lxml.etree.XMLParser.set_element_class_lookup`
  470. (and the same for HTML parsers).
  471. Globally replacing the element class lookup by something other than a
  472. :class:`ParserBasedElementClassLookup` will prevent parser specific lookup
  473. schemes from working. Several tools rely on parser specific lookups,
  474. including :mod:`lxml.html` and :mod:`lxml.objectify`.
  475. """
  476. if lookup is None or lookup._lookup_function is NULL:
  477. _setElementClassLookupFunction(NULL, None)
  478. else:
  479. _setElementClassLookupFunction(lookup._lookup_function, lookup)
  480. # default setup: parser delegation
  481. cdef ParserBasedElementClassLookup DEFAULT_ELEMENT_CLASS_LOOKUP
  482. DEFAULT_ELEMENT_CLASS_LOOKUP = ParserBasedElementClassLookup()
  483. set_element_class_lookup(DEFAULT_ELEMENT_CLASS_LOOKUP)