Debian Codegraph @

doc/sphinx/_extensions/fontforge_scripting_domain.py

raw symbols SCIP
1 '''
2 Copyright (C) 2020 by Jeremy Tan
3
4 Distributed under the original FontForge BSD 3-clause license.
5
6 Based on the Sphinx Python domain implementation, which is also BSD licensed:
7 https://github.com/sphinx-doc/sphinx/blob/14e69c21ed3552afc54b8f75377317765938bb60/sphinx/domains/python.py
8
9 -------------------------------------------------------------------------------
10
11 Adds a FontForge scripting domain for the native FontForge scripting language.
12 '''
13
14 from docutils.parsers.rst import directives
15 from docutils.nodes import Element
16
17 from sphinx import addnodes
18 from sphinx.addnodes import pending_xref, desc_signature
19 from sphinx.builders import Builder
20 from sphinx.directives import ObjectDescription
21 from sphinx.domains import Domain, ObjType
22 from sphinx.environment import BuildEnvironment
23 from sphinx.locale import _, __
24 from sphinx.roles import XRefRole
25 from sphinx.util import logging
26 from sphinx.util.nodes import make_refnode
27
28 from typing import Any, Dict, Iterator, List, Tuple
29 from typing import cast
30
31 import re
32
33 ff_sig_re = re.compile(r'^\$?(\w+)(?:\(\s*(.*)\s*\))?$')
34
35 logger = logging.getLogger(__name__)
36
37
38 # Lifted straight from Sphinx
39 def _pseudo_parse_arglist(signode: desc_signature, arglist: str) -> None:
40 """"Parse" a list of arguments separated by commas.
41 Arguments can have "optional" annotations given by enclosing them in
42 brackets. Currently, this will split at any comma, even if it's inside a
43 string literal (e.g. default argument value).
44 """
45 paramlist = addnodes.desc_parameterlist()
46 stack = [paramlist] # type: List[Element]
47 try:
48 for argument in arglist.split(','):
49 argument = argument.strip()
50 ends_open = ends_close = 0
51 while argument.startswith('['):
52 stack.append(addnodes.desc_optional())
53 stack[-2] += stack[-1]
54 argument = argument[1:].strip()
55 while argument.startswith(']'):
56 stack.pop()
57 argument = argument[1:].strip()
58 while argument.endswith(']') and not argument.endswith('[]'):
59 ends_close += 1
60 argument = argument[:-1].strip()
61 while argument.endswith('['):
62 ends_open += 1
63 argument = argument[:-1].strip()
64 if argument:
65 stack[-1] += addnodes.desc_parameter(argument, argument)
66 while ends_open:
67 stack.append(addnodes.desc_optional())
68 stack[-2] += stack[-1]
69 ends_open -= 1
70 while ends_close:
71 stack.pop()
72 ends_close -= 1
73 if len(stack) != 1:
74 raise IndexError
75 except IndexError:
76 # if there are too few or too many elements on the stack, just give up
77 # and treat the whole argument list as one argument, discarding the
78 # already partially populated paramlist node
79 paramlist = addnodes.desc_parameterlist()
80 paramlist += addnodes.desc_parameter(arglist, arglist)
81 signode += paramlist
82 else:
83 signode += paramlist
84
85
86 class FontForgeScriptingObject(ObjectDescription):
87 """
88 Description of a general FontForge native scripting object.
89 """
90 option_spec = {
91 'noindex': directives.flag,
92 'annotation': directives.unchanged,
93 }
94
95 def get_signature_prefix(self, sig: str) -> str:
96 """May return a prefix to put before the object name in the
97 signature.
98 """
99 return ''
100
101 def needs_arglist(self) -> bool:
102 """May return true if an empty argument list is to be generated even if
103 the document contains none.
104 """
105 return False
106
107 def handle_signature(self, sig: str, signode: desc_signature) -> Tuple[str, str]:
108 """Transform a FontForge native scripting signature into RST nodes.
109 Return (fully qualified name of the thing, classname if any).
110 If inside a class, the current class name is handled intelligently:
111 * it is stripped from the displayed name if present
112 * it is added to the full name (return value) if not present
113 """
114 m = ff_sig_re.match(sig)
115 if m is None:
116 raise ValueError
117
118 name, arglist = m.groups()
119
120 signode['fullname'] = name
121
122 sig_prefix = self.get_signature_prefix(sig)
123 if sig_prefix:
124 signode += addnodes.desc_annotation(sig_prefix, sig_prefix)
125
126 signode += addnodes.desc_name(name, name)
127
128 if arglist:
129 _pseudo_parse_arglist(signode, arglist)
130 elif self.needs_arglist():
131 signode += addnodes.desc_parameterlist()
132
133 anno = self.options.get('annotation')
134 if anno:
135 signode += addnodes.desc_annotation(' ' + anno, ' ' + anno)
136
137 return name, ''
138
139 def get_index_text(self, name: Tuple[str, str]) -> str:
140 """Return the text for the index entry of the object."""
141 raise NotImplementedError('must be implemented in subclasses')
142
143 def add_target_and_index(self, name_cls: Tuple[str, str], sig: str,
144 signode: desc_signature) -> None:
145 fullname = name_cls[0]
146 # note target
147 if fullname not in self.state.document.ids:
148 signode['names'].append(fullname)
149 signode['ids'].append(fullname)
150 signode['first'] = (not self.names)
151 self.state.document.note_explicit_target(signode)
152
153 domain = cast(FontForgeScriptingDomain, self.env.get_domain('ff'))
154 domain.note_object(fullname, self.objtype,
155 location=(self.env.docname, self.lineno))
156
157 indextext = self.get_index_text(name_cls)
158 if indextext:
159 self.indexnode['entries'].append(('single', indextext,
160 fullname, '', None))
161
162
163 class FontForgeScriptingFunction(FontForgeScriptingObject):
164 def needs_arglist(self) -> bool:
165 return True
166
167 def get_index_text(self, name_cls: Tuple[str, str]) -> str:
168 return _('%s() (native scripting function)') % name_cls[0]
169
170
171 class FontForgeScriptingVariable(FontForgeScriptingObject):
172 def get_signature_prefix(self, sig):
173 return '$'
174
175 def get_index_text(self, name_cls: Tuple[str, str]) -> str:
176 return _('$%s (native scripting built-in variable)') % name_cls[0]
177
178
179 class FontForgeScriptingXRefRole(XRefRole):
180 def process_link(self, env: BuildEnvironment, refnode: Element,
181 has_explicit_title: bool, title: str, target: str) -> Tuple[str, str]:
182 if not has_explicit_title:
183 title = title.lstrip('.') # only has a meaning for the target
184 target = target.lstrip('~') # only has a meaning for the title
185 # if the first character is a tilde, don't display the module/class
186 # parts of the contents
187 if title[0:1] == '~':
188 title = title[1:]
189 dot = title.rfind('.')
190 if dot != -1:
191 title = title[dot + 1:]
192 # if the first character is a dot, search more specific namespaces first
193 # else search builtins first
194 if target[0:1] == '.':
195 target = target[1:]
196 refnode['refspecific'] = True
197 return title, target
198
199
200 class FontForgeScriptingDomain(Domain):
201 name = 'ff'
202 label = 'FontForge Native Scripting'
203 object_types = {
204 'function': ObjType(_('function'), 'func', 'obj'),
205 'data': ObjType(_('data'), 'data', 'obj'),
206 }
207
208 directives = {
209 'function': FontForgeScriptingFunction,
210 'data': FontForgeScriptingVariable
211 }
212
213 roles = {
214 'func': FontForgeScriptingXRefRole(),
215 'data': FontForgeScriptingXRefRole()
216 }
217 initial_data = {
218 'objects': {}, # fullname -> docname, objtype
219 } # type: Dict[str, Dict[str, Tuple[Any]]]
220
221 @property
222 def objects(self) -> Dict[str, Tuple[str, str]]:
223 # fullname -> docname, objtype
224 return self.data.setdefault('objects', {})
225
226 def note_object(self, name: str, objtype: str, location: Any = None) -> None:
227 """Note a FontForge native scripting object for cross reference.
228 """
229 if name in self.objects:
230 docname = self.objects[name][0]
231 logger.warning(__('duplicate object description of %s, '
232 'other instance in %s, use :noindex: for one of them'),
233 name, docname, location=location)
234 self.objects[name] = (self.env.docname, objtype)
235
236 def clear_doc(self, docname: str) -> None:
237 for fullname, (fn, _l) in list(self.objects.items()):
238 if fn == docname:
239 del self.objects[fullname]
240
241 def merge_domaindata(self, docnames: List[str], otherdata: Dict) -> None:
242 # XXX check duplicates?
243 for fullname, (fn, objtype) in otherdata['objects'].items():
244 if fn in docnames:
245 self.objects[fullname] = (fn, objtype)
246
247 def find_obj(self, env: BuildEnvironment,
248 name: str, type: str, searchmode: int = 0) -> List[Tuple[str, Any]]:
249 """Find a Fontforge native scripting object for "name".
250 Returns a list of (name, object entry) tuples.
251 """
252 # skip parens
253 if name[-2:] == '()':
254 name = name[:-2]
255
256 if not name:
257 return []
258
259 matches = [] # type: List[Tuple[str, Any]]
260
261 newname = None
262 if searchmode == 1:
263 if type is None:
264 objtypes = list(self.object_types)
265 else:
266 objtypes = self.objtypes_for_role(type)
267 if objtypes is not None:
268 if not newname:
269 if name in self.objects and self.objects[name][1] in objtypes:
270 newname = name
271 else:
272 # "fuzzy" searching mode
273 searchname = '.' + name
274 matches = [(oname, self.objects[oname]) for oname in self.objects
275 if oname.endswith(searchname) and
276 self.objects[oname][1] in objtypes]
277 else:
278 # NOTE: searching for exact match, object type is not considered
279 if name in self.objects:
280 newname = name
281 if newname is not None:
282 matches.append((newname, self.objects[newname]))
283 return matches
284
285 def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
286 type: str, target: str, node: pending_xref, contnode: Element
287 ) -> Element:
288 searchmode = 1 if node.hasattr('refspecific') else 0
289 matches = self.find_obj(env, target,
290 type, searchmode)
291
292 if not matches:
293 return None
294 elif len(matches) > 1:
295 logger.warning(__('more than one target found for cross-reference %r: %s'),
296 target, ', '.join(match[0] for match in matches),
297 type='ref', subtype='ff', location=node)
298
299 name, obj = matches[0]
300 return make_refnode(builder, fromdocname, obj[0], name, contnode, name)
301
302 def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
303 target: str, node: pending_xref, contnode: Element
304 ) -> List[Tuple[str, Element]]:
305 results = [] # type: List[Tuple[str, Element]]
306
307 # always search in "refspecific" mode with the :any: role
308 matches = self.find_obj(env, target, None, 1)
309 for name, obj in matches:
310 results.append(('ff:' + self.role_for_objtype(obj[1]),
311 make_refnode(builder, fromdocname, obj[0], name,
312 contnode, name)))
313 return results
314
315 def get_objects(self) -> Iterator[Tuple[str, str, str, str, str, int]]:
316 for refname, (docname, type) in self.objects.items():
317 yield (refname, refname, type, docname, refname, 1)
318
319 def get_full_qualified_name(self, node: Element) -> str:
320 target = node.get('reftarget')
321 if target is None:
322 return None
323 else:
324 return target
325
326
327 def setup(app):
328 app.add_domain(FontForgeScriptingDomain)
329
330 return {
331 'version': '1.0.0',
332 'env_version': 1,
333 'parallel_read_safe': True
334 }