Debian Codegraph @

mallard/ducktype/extensions/_test.py

raw
1 # Copyright (c) 2018 Shaun McCance <[email protected]>
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
12 #
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 # THE SOFTWARE.
20
21 ################################################################################
22 # This is a test extension. Its primary purpose is to fuel regression tests.
23 # Since it exercises all the extension points, it's heavily commented so you
24 # can learn from it.
25
26 import mallard.ducktype
27
28 # All extensions are a subclass of ParserExtension. When the parser encounters an
29 # extension declaration like foo/1.0, it imports mallard.ducktype.extensions.foo
30 # and tries to instantiate every ParserExtension subclass in it. It doesn't matter
31 # what you name your classes.
32
33 class TestExtension(mallard.ducktype.parser.ParserExtension):
34 def __init__(self, parser, prefix, version):
35 # Usually you'd use this to specify a version to make sure this code is
36 # compatible with what the document expects. In this case, though, we're
37 # using the version to specify which parts of the test extension to use.
38 if version == 'block':
39 self.mode = 'block'
40 elif version == 'blocknode':
41 self.mode = 'blocknode'
42 elif version == 'directive':
43 self.mode = 'directive'
44 else:
45 raise mallard.ducktype.parser.SyntaxError(
46 'Unsupported _test extension version: ' + version,
47 parser)
48 # It's important to bear in mind that parser might not always be a
49 # DuckParser object. Depending on the extension and where it's used,
50 # parser might be something like a DirectiveIncludeParser or an
51 # InlineParser.
52 self.parser = parser
53 self.prefix = prefix
54 self.version = version
55 # Feel free to do things to the parser or the document root here.
56 self.parser.document.add_namespace('test', 'http://projectmallard.org/test/')
57
58 def parse_line_block(self, line):
59 # This is the function to implement to do things in a block context,
60 # like adding a shorthand notation for a block element. It gets
61 # called only in places where a regular block element could occur.
62 # Headers, comments, and fences have already been taken care of.
63 # If you want to add a block extension with a syntax that looks
64 # like a standard block declaration, use take_block_node instead.
65 # That method will handle a lot more things for you.
66 if self.mode != 'block':
67 return False
68
69 indent = mallard.ducktype.parser.DuckParser.get_indent(line)
70 iline = line[indent:]
71
72 # Return False to indicate you're not handling this line. For
73 # this test, we're doing something with lines that start with
74 # three asterisks and a space.
75 if not iline.startswith('*** '):
76 return False
77
78 # In most cases when creating block elements, you'll want to start
79 # by calling push_text and unravel_for_block. push_text makes sure
80 # any text lines we just encountered get put into a block element.
81 # unravel_for_block gets you to the correct current element to start
82 # adding new block elements, based on indentation and the standard
83 # block nesting rules. There are other unravel functions for special
84 # nesting rules for tables and lists.
85 self.parser.push_text()
86 self.parser.unravel_for_block(indent)
87
88 # Here's the meat of what this extension does. It creates a block
89 # element, adds an attribute to it, adds the element to the current
90 # element (which unravel_for_block got us to), then sets the new
91 # element as the current element. Setting the new element as the
92 # current element lets the parser add content to it. If you want
93 # to add something that doesn't take content, don't set it as
94 # current.
95 qnode = mallard.ducktype.parser.Block('test:TEST', indent, parser=self.parser)
96 qnode.attributes = mallard.ducktype.parser.Attributes()
97 qnode.attributes.add_attribute('line', iline[4:].strip())
98 self.parser.current.add_child(qnode)
99 self.parser.current = qnode
100
101 # This lets the parser know that we've just created a block element
102 # and it's ready to take on new content. This is important because
103 # the first child element will set the inner indent of our new block
104 # element. Don't bother with this if you're adding something that
105 # doesn't take content (and you didn't set as current).
106 self.parser.state = mallard.ducktype.parser.DuckParser.STATE_BLOCK_READY
107
108 # Return True to indicate you have handled the line. The parser will
109 # stop trying to do anything else with this line.
110 return True
111
112 def take_block_node(self, node):
113 # This is the function to implement to do things with extension
114 # elements that looks like block nodes. It gets called on a Node
115 # object that has alredy been parsed as if it were a block node,
116 # but it has not been added to the document. This will only be
117 # called for nodes with a prefix matching the base name of your
118 # extension. For example, this extension is _test.py, so it will
119 # be called for things like:
120 # [_test:block]
121 # [_test:frobnicate]
122 # It will not be called for things like:
123 # [test:block]
124 # [_test_frobnicate]
125 # If you want to add block syntax that doesn't look like a
126 # standard block declaration, use parse_line_block instead.
127 if self.mode != 'blocknode':
128 return False
129
130 # Return False to indicate you're not handling this node. If no
131 # extensions handle the node, the parser will try to treat it
132 # as a regular block node, requiring a suitable namespace prefix
133 # binding. If it can't find one, it will raise an error. For this
134 # test, we're doing something with block declarations that look
135 # like [_test:block]
136 if node.name != '_test:block':
137 return False
138
139 # If you read the comments on parse_line_block, you might be tempted
140 # to call push_text and unravel_for_block here. But you don't have
141 # to. The parser has already parsed this thing as if it were a block
142 # declaration, and that includes pushing text and unraveling.
143
144 # Here's the meat of what this extension does. Instead of allowing
145 # the passed-in node to go into the document, it creates a new node.
146 # It copies over the attributes from the extension block element,
147 # and even adds its own attribute value. You could do completely
148 # different things with the attributes. If you want to add something
149 # that doesn't take content, don't set it as current.
150 qnode = mallard.ducktype.parser.Block('note', outer=node.outer, parser=self.parser)
151 qnode.attributes = mallard.ducktype.parser.Attributes()
152 # It's safe to add a style attribute and then add other attributes
153 # without checking their names. Attributes objects automatically
154 # join multiple style and type attributes into space-separated lists.
155 qnode.attributes.add_attribute('style', 'warning')
156 if node.attributes is not None:
157 for attr in node.attributes.get_attributes():
158 qnode.attributes.add_attribute(attr, node.attributes.get_attribute(attr))
159 self.parser.current.add_child(qnode)
160 self.parser.current = qnode
161
162 # If you read the comments on parse_line_block, you might be tempted
163 # to set self.parser.state here. Don't bother, unless you actually
164 # really need to set it to something other than STATE_BLOCK_READY.
165 # The parser has already entered that state by the time extensions
166 # get a crack at block declarations.
167
168 # Return True to indicate you have handled the node. The parser will
169 # stop trying to do anything else with this node.
170 return True
171
172 def take_directive(self, directive):
173 # This is the function to implement to handle parser directives at
174 # the top of a file. This will only be called for directives with
175 # a prefix matching the base name of your extension. For example,
176 # this extension is _test.py, so it will be called for things like:
177 # @_test:defines
178 # @_test:frobnicate
179 # It will not be called for things like:
180 # @test:defines
181 # @_test_frobnicate
182 if self.mode != 'directive':
183 return False
184
185 if directive.name == '_test:defines':
186 # This extension recognizes a simple directive like this:
187 # @_test:defines
188 # And treats it like it defined something lengthier. Just add
189 # that definition to the main document, and we're done. For a
190 # directive parser extension, the calling parser might be a
191 # DirectiveIncludeParser instead of a DuckParser. But that's
192 # OK, because DirectiveIncludeParser also has a document
193 # attribute that points to the right place.
194 self.parser.document.add_definition('TEST',
195 'This is a $em(test). ' +
196 'It is only a $em[.strong](test).')
197 # Return True to tell the parser we handled this directive.
198 return True
199 else:
200 return False