forked from haskell/cabal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcabaldomain.py
952 lines (762 loc) · 28.9 KB
/
cabaldomain.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
# -*- coding: utf-8 -*-
'''
Sphinx domain for documenting all things cabal
The main reason to use this instead of adding object types to std domain
is the ability to generate nice 'Reference' page and also provide some meta
data for objects described with directives described here.
Most directives have at least following optional arguments
`:since: 1.24`
version of Cabal in which feature was added.
`:deprecated: 1.24`
`:deprecated:`
Feature was deprecated, and optionally since which version.
`:removed: 3.0`
Feature was removed
`:synopsis: Short desc`
Text used as short description on reference page.
Added directives
.. rst:directive:: .. cabal::cfg-section
Describes a package.cabal section, such as library or executable.
All following `pkg-field` directives will add section name
to their fields name for disambiguating duplicates.
You can reset the section disambiguation with `.. pkg-section:: None`.
.. rst::role:: pkg-section
References section added by `.. pkg-section`
.. rst:directive:: .. cabal::pkg-field
Describes a package.cabal field.
Can have a :default: field. Will group on reference page under pkg-section
if set and parent header otherwise.
.. rst::role:: pkg-field
References field added by `.. pkg-field`, fields can be disambiguated
with section name `:pkg-field:`section:field`.
.. rst:directive:: .. cabal:cfg-section::
Same as `.. cabal::pkg-section` but does not produce any visible output
currently unused.
.. rst:directive:: .. cabal:cfg-field::
Describes a cabal.project field.
Can have multiple arguments, if arguments start with '-' then it is treated
as a cabal flag.
Can have a :default: field. Will group on reference page under pkg-section
if set and parent header otherwise.
.. rst::role:: cfg-field
References field added by `.. cfg-field`.
.. rst::role:: cfg-flag
References flag added by `.. cfg-field`.
All roles can be supplied with title as in standard sphinx references::
:pkg-field:`Build dependencies<build-depends>`
To be done:
- Directives for describing executables, their subcommands and flags.
These should act in a way similar to `.. std::option` directive, but with
extra meta. And should also end up in reference.
At least setup and 'new-build` subcommands should get special directives
- Improve rendering of flags in `.. cfg-field::` directive. It should be
possible without copy-pasting code from sphinx.directives.ObjectDescription
by examining result of ObjectDescription.run and inserting flags into
desc_content node.
Alternatively Or `.. flags::` sub-directive can be added which will be aware
of parent `.. cfg-field` directive.
- With same ObjectDescription.run trick as above, render since and deprecated
info same way as standard object fields, and use fancy rendering only on
references page.
- Add 'since_version` config value to sphinx env and use it to decide if
version meta info should be rendered on reference page and thus reduce some
clutter.
Can also be used to generate 'Whats new' reference page
'''
import re
from docutils import nodes
from docutils.parsers.rst import Directive, directives, roles
import pygments.lexer as lexer
import pygments.token as token
from distutils.version import StrictVersion
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import ObjType, Domain, Index
from sphinx.domains.std import StandardDomain
from sphinx.locale import _
from sphinx.roles import XRefRole
from sphinx.util.docfields import Field, DocFieldTransformer
from sphinx.util.nodes import make_refnode
def parse_deprecated(txt):
if txt is None:
return True
try:
return StrictVersion(txt)
except ValueError:
return True
def parse_flag(env, sig, signode):
import re
names = []
for i, flag in enumerate(sig.split(',')):
flag = flag.strip()
sep = '='
parts = flag.split('=')
if len(parts) == 1:
sep=' '
parts = flag.split()
if len(parts) == 0: continue
name = parts[0]
names.append(name)
sig = sep + ' '.join(parts[1:])
sig = re.sub(r'<([-a-zA-Z ]+)>', r'⟨\1⟩', sig)
if i > 0:
signode += addnodes.desc_name(', ', ', ')
signode += addnodes.desc_name(name, name)
if len(sig) > 0:
signode += addnodes.desc_addname(sig, sig)
return names[0]
class Meta(object):
'''
Meta data associated with object
'''
def __init__(self,
since=None,
deprecated=None,
removed=None,
synopsis=None,
title=None,
section=None,
index=0):
self.since = since
self.deprecated = deprecated
self.removed = removed
self.synopsis = synopsis
self.title = title
self.section = section
self.index = index
def find_section_title(parent):
'''
Find current section id and title if possible
'''
while parent is not None:
if isinstance(parent, nodes.section):
break
parent = parent.parent
if parent is None:
return None
section_id = parent['ids'][0]
section_name = parent['names'][0]
for kid in parent:
if isinstance(kid, nodes.title):
return kid.astext(), section_id
print(section_name, section_id)
return section_name, section_id
class CabalSection(Directive):
"""
Marks section to which following objects belong, used to disambiguate
references to fields and flags which can have similar names
Does not generate any output besides anchor.
"""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {
'name': lambda x: x,
'deprecated': parse_deprecated,
'removed': StrictVersion,
'since' : StrictVersion,
'synopsis' : lambda x:x,
}
section_key = 'cabal:pkg-section'
target_prefix = 'pkg-section-'
indextemplate = ''
indextype = 'pair'
def get_index_entry(self, name):
return self.indextemplate % name
def run(self):
env = self.state.document.settings.env
section = self.arguments[0].strip()
if ':' in self.name:
self.domain, self.objtype = self.name.split(':', 1)
else:
self.domain, self.objtype = '', self.name
if section == 'None':
env.ref_context.pop(self.section_key, None)
return []
env.ref_context[self.section_key] = section
targetname = self.target_prefix + section
node = nodes.target('', '', ids=[targetname])
self.state.document.note_explicit_target(node)
indexentry = self.get_index_entry(section)
inode = addnodes.index(
entries = [
(self.indextype, indexentry, targetname, '', None)])
# find title of parent section node
title = find_section_title(self.state.parent)
data_key = CabalDomain.types[self.objtype]
# find how many sections in this document were added
num = env.domaindata['cabal']['index-num'].get(env.docname, 0)
env.domaindata['cabal']['index-num'][env.docname] = num + 1
meta = Meta(since=self.options.get('since'),
deprecated=self.options.get('deprecated'),
removed=self.options.get('removed'),
synopsis=self.options.get('synopsis'),
index = num,
title = title)
store = env.domaindata['cabal'][data_key]
if not section in store:
store[section] = env.docname, targetname, meta
return [inode, node]
class CabalObject(ObjectDescription):
option_spec = {
'noindex' : directives.flag,
'deprecated': parse_deprecated,
'removed' : StrictVersion,
'since' : StrictVersion,
'synopsis' : lambda x:x
}
# node attribute marking which section field belongs to
section_key = ''
# template for index, it is passed a field name as argument
# used by default deg_index_entry method
indextemplate = ''
def get_meta(self):
'''
Collect meta data for fields
Reads optional arguments passed to directive and also
tries to find current section title and adds it as section
'''
env = self.state.document.settings.env
# find title of current section, will group references page by it
num = env.domaindata['cabal']['index-num'].get(env.docname, 0)
env.domaindata['cabal']['index-num'][env.docname] = num + 1
title = find_section_title(self.state.parent)
return Meta(since=self.options.get('since'),
deprecated=self.options.get('deprecated'),
removed=self.options.get('removed'),
title=title,
index = num,
synopsis=self.options.get('synopsis'))
def get_env_key(self, env, name):
'''
Should return a key used to reference this field and key in domain
data to store this object
'''
section = self.env.ref_context.get(self.section_key)
store = CabalDomain.types[self.objtype]
return (section, name), store
def get_index_entry(self, env, name):
'''
Should return index entry and anchor
By default uses indextemplate attribute to generate name and
index entry by joining directive name, section and field name
'''
section = self.env.ref_context.get(self.section_key)
if section is not None:
parts = (self.objtype, section, name)
indexentry = self.indextemplate % (section + ':' + name)
else:
parts = (self.objtype, name)
indexentry = self.indextemplate % name
targetname = '-'.join(parts)
return indexentry, targetname
def add_target_and_index(self, name, sig, signode):
'''
As in sphinx.directive.ObjectDescription
By default adds 'pair' index as returned by get_index_entry and
stores object data into domain data store as returned by get_env_data
'''
env = self.state.document.settings.env
indexentry, targetname = self.get_index_entry(self, name)
signode['ids'].append(targetname)
self.state.document.note_explicit_target(signode)
inode = addnodes.index(
entries=[('pair', indexentry, targetname, '', None)])
signode.insert(0, inode)
key, store = self.get_env_key(env, name)
env.domaindata['cabal'][store][key] = env.docname, targetname, self.cabal_meta
def run(self):
self.cabal_meta = self.get_meta()
result = super(CabalObject, self).run()
if self.cabal_meta.since is not None \
or self.cabal_meta.deprecated is not None:
#find content part of description
for item in result:
if isinstance(item, addnodes.desc):
desc = item
break
else:
return result
for item in desc:
if isinstance(item, addnodes.desc_content):
contents = item
break
else:
return result
# find exsting field list and add to it
# or create new one
for item in contents:
if isinstance(item, nodes.field_list):
field_list = item
break
else:
field_list = nodes.field_list('')
contents.insert(0, field_list)
if self.cabal_meta.since is not None:
#docutils horror
field = nodes.field('')
field_name = nodes.field_name('Since', 'Since')
since = 'Cabal ' + str(self.cabal_meta.since)
field_body = nodes.field_body(since, nodes.paragraph(since, since))
field += field_name
field += field_body
field_list.insert(0, field)
if self.cabal_meta.deprecated is not None:
field = nodes.field('')
field_name = nodes.field_name('Deprecated', 'Deprecated')
if isinstance(self.cabal_meta.deprecated, StrictVersion):
since = 'Cabal ' + str(self.cabal_meta.deprecated)
else:
since = ''
field_body = nodes.field_body(since, nodes.paragraph(since, since))
field += field_name
field += field_body
field_list.insert(0, field)
if self.cabal_meta.removed is not None:
field = nodes.field('')
field_name = nodes.field_name('Removed', 'Removed')
if isinstance(self.cabal_meta.removed, StrictVersion):
since = 'Cabal ' + str(self.cabal_meta.removed)
else:
since = ''
field_body = nodes.field_body(since, nodes.paragraph(since, since))
field += field_name
field += field_body
field_list.insert(0, field)
return result
class CabalPackageSection(CabalObject):
"""
Cabal section in package.cabal file
"""
section_key = 'cabal:pkg-section'
indextemplate = '%s; package.cabal section'
def handle_signature(self, sig, signode):
'''
As in sphinx.directives.ObjectDescription
By default make an object description from name and adding
either deprecated or since as annotation.
'''
env = self.state.document.settings.env
sig = sig.strip()
parts = sig.split(' ',1)
name = parts[0]
signode += addnodes.desc_name(name, name)
signode += addnodes.desc_addname(' ', ' ')
if len(parts) > 1:
rest = parts[1].strip()
signode += addnodes.desc_annotation(rest, rest)
return name
def get_env_key(self, env, name):
store = CabalDomain.types[self.objtype]
return name, store
def run(self):
env = self.state.document.settings.env
section = self.arguments[0].strip().split(' ',1)[0]
if section == 'None':
env.ref_context.pop('cabal:pkg-section', None)
return []
env.ref_context['cabal:pkg-section'] = section
return super(CabalPackageSection, self).run()
class CabalField(CabalObject):
'''
Base for fields in *.cabal files
'''
option_spec = {
'noindex' : directives.flag,
'deprecated': parse_deprecated,
'removed' : StrictVersion,
'since' : StrictVersion,
'synopsis' : lambda x:x
}
doc_field_types = [
Field('default', label='Default value', names=['default'], has_arg=False)
]
def handle_signature(self, sig, signode):
'''
As in sphinx.directives.ObjectDescription
By default make an object description from name and adding
either deprecated or since as annotation.
'''
env = self.state.document.settings.env
sig = sig.strip()
parts = sig.split(':',1)
name = parts[0]
signode += addnodes.desc_name(name, name)
signode += addnodes.desc_addname(': ', ': ')
if len(parts) > 1:
rest = parts[1].strip()
signode += addnodes.desc_annotation(rest, rest)
return name
class CabalPackageField(CabalField):
'''
Describes section in package.cabal file
'''
section_key = 'cabal:pkg-section'
indextemplate = '%s; package.cabal field'
class CabalFieldXRef(XRefRole):
'''
Cross ref node for all kinds of fields
Gets section_key entry from context and stores it on node, so it can
later be used by CabalDomain.resolve_xref to find target for reference to
this
'''
section_key = 'cabal:pkg-section'
def process_link(self, env, refnode, has_explicit_title, title, target):
parts = target.split(':',1)
if len(parts) == 2:
section, target = parts
section = section.strip()
target = target.strip()
refnode[self.section_key] = section
else:
refnode[self.section_key] = env.ref_context.get(self.section_key)
return title, target
#
# Directives for config files.
#
class CabalPackageFieldXRef(CabalFieldXRef):
'''
Role referencing cabal.project section
'''
section_key = 'cabal:pkg-section'
class CabalConfigSection(CabalObject):
"""
Marks section in package.cabal file
"""
indextemplate = '%s; cabal.project section'
section_key = 'cabal:cfg-section'
target_prefix = 'cfg-section-'
def handle_signature(self, sig, signode):
'''
As in sphinx.directives.ObjectDescription
By default make an object description from name and adding
either deprecated or since as annotation.
'''
env = self.state.document.settings.env
sig = sig.strip()
parts = sig.split(' ',1)
name = parts[0]
signode += addnodes.desc_name(name, name)
signode += addnodes.desc_addname(' ', ' ')
if len(parts) > 1:
rest = parts[1].strip()
signode += addnodes.desc_annotation(rest, rest)
return name
def get_env_key(self, env, name):
store = CabalDomain.types[self.objtype]
return name, store
def run(self):
env = self.state.document.settings.env
section = self.arguments[0].strip().split(' ',1)[0]
if section == 'None':
env.ref_context.pop('cabal:cfg-section', None)
return []
env.ref_context['cabal:cfg-section'] = section
return super(CabalConfigSection, self).run()
class ConfigField(CabalField):
section_key = 'cabal:cfg-section'
indextemplate = '%s ; cabal project option'
def handle_signature(self, sig, signode):
sig = sig.strip()
if sig.startswith('-'):
name = parse_flag(self, sig, signode)
else:
name = super(ConfigField, self).handle_signature(sig, signode)
return name
def get_index_entry(self, env, name):
if name.startswith('-'):
section = self.env.ref_context.get(self.section_key)
if section is not None:
parts = ('cfg-flag', section, name)
indexname = section + ':' + name
else:
parts = ('cfg-flag', name)
indexname = name
indexentry = name + '; cabal project option'
targetname = '-'.join(parts)
return indexentry, targetname
else:
return super(ConfigField,self).get_index_entry(env, name)
def get_env_key(self, env, name):
section = self.env.ref_context.get(self.section_key)
if name.startswith('-'):
return (section, name), 'cfg-flags'
return (section, name), 'cfg-fields'
class CabalConfigFieldXRef(CabalFieldXRef):
section_key = 'cabal:cfg-section'
#
# Cabal domain
#
class ConfigFieldIndex(Index):
name = 'syntax-quicklinks'
localname = "Cabal Syntax Quicklinks"
shortname = "Quicklinks"
class Entry(object):
def __init__(self, typ, name, doc, anchor, meta):
self.type = typ
self.name = name
self.doc = doc
self.anchor = anchor
self.meta = meta
def _gather_data(self, obj_types):
'''
Gather objects and return [(title, [Entry])]
'''
def massage(typ, datum):
name, (doc, anchor, meta) = datum
return self.Entry(typ, name, doc, anchor, meta)
fields = []
for typ in obj_types:
store = CabalDomain.types[typ]
fields += [massage(typ, x)
for x in self.domain.data[store].items()]
fields.sort(key=lambda x: (x.doc, x.meta.index))
if len(fields) == 0:
return []
result = []
current = []
current_title = fields[0].meta.title
for field in fields:
if field.meta.title != current_title:
result.append((current_title, current))
current = []
current_title = field.meta.title
current.append(field)
result.append((current_title, current))
return result
def generate(self, docnames=None):
'''
Try to group entries such that if entry has a section then put it
into same group.
Otherwise group it under same `title`.
Try to keep in same order as it was defined.
sort by (document, index)
group on (document, doc_section)
TODO: Check how to extract section numbers from (document,doc_section)
and add it as annotation to titles
'''
# (title, section store, fields store)
entries = [('cabal.project fields', 'cfg-section', 'cfg-field'),
('cabal project flags', 'cfg-section', 'cfg-flag'),
('package.cabal fields', 'pkg-section', 'pkg-field')]
result = []
for label, section_key, key in entries:
data = self._gather_data([section_key, key])
references = []
for section, entries in data:
if section is None:
elem_type = 0 # Normal entry
else:
elem_type = 2 # sub_entry
assert len(entries) != 0
docname = entries[0].doc
if section is not None:
section_title, section_anchor = section
references.append(
(section_title, 1, docname, section_anchor, '', '', ''))
for entry in entries:
#todo deal with if
if isinstance(entry.name, tuple):
name = entry.name[1]
else:
name = entry.name
meta = entry.meta
extra = render_meta(meta)
descr = meta.synopsis if meta.synopsis is not None else ''
field = (name, elem_type, docname,
entry.anchor, extra, '', descr)
references.append(field)
result.append((label, references))
return result, False
def make_data_keys(typ, target, node):
'''
Returns a list of keys to search for targets of this type
in domain data.
Used for resolving references
'''
if typ == 'pkg-field':
section = node.get('cabal:pkg-section')
return [(section, target),
(None, target)]
elif typ in ('cfg-field', 'cfg-flag'):
section = node.get('cabal:cfg-section')
return [(section, target), (None, target)]
else:
return [target]
def render_deprecated(deprecated):
if isinstance(deprecated, StrictVersion):
return 'deprecated since: '+str(deprecated)
else:
return 'deprecated'
def render_removed(deprecated, removed):
if isinstance(deprecated, StrictVersion):
return 'removed in: ' + str(removed) + '; deprecated since: '+str(deprecated)
else:
return 'removed in: ' + str(removed)
def render_meta(meta):
'''
Render meta as short text
Will render either deprecated or since info
'''
if meta.removed is not None:
return render_removed(meta.deprecated, meta.removed)
if meta.deprecated is not None:
return render_deprecated(meta.deprecated)
elif meta.since is not None:
return 'since version: ' + str(meta.since)
else:
return ''
def render_meta_title(meta):
'''
Render meta as suitable to use in titles
'''
rendered = render_meta(meta)
if rendered != '':
return '(' + rendered + ')'
return ''
def make_title(typ, key, meta):
'''
Render title of an object (section, field or flag)
'''
if typ == 'pkg-section':
return "package.cabal " + key + " section " + render_meta_title(meta)
elif typ == 'pkg-field':
section, name = key
if section is not None:
base = "package.cabal " + section + " section " + name + ": field"
else:
base = "package.cabal " + name + " field"
return base + render_meta_title(meta)
elif typ == 'cfg-section':
return "cabal.project " + key + " section " + render_meta_title(meta)
elif typ == 'cfg-field':
section, name = key
return "cabal.project " + name + " field " + render_meta_title(meta)
elif typ == 'cfg-flag':
section, name = key
return "cabal flag " + name + " " + render_meta_title(meta)
else:
raise ValueError("Unknown type: " + typ)
def make_full_name(typ, key, meta):
'''
Return an anchor name for object type
'''
if typ == 'pkg-section':
return 'pkg-section-' + key
elif typ == 'cfg-section':
return 'cfg-section-' + key
elif typ == 'pkg-field':
section, name = key
if section is not None:
return '-'.join(('pkg-field',section, name))
else:
return 'pkg-field-' + name
elif typ == 'cfg-field':
return 'cfg-field-' + key
else:
raise ValueError('Unknown object type: ' + typ)
class CabalDomain(Domain):
'''
Sphinx domain for cabal
needs Domain.merge_doc for parallel building, just union all dicts
'''
name = 'cabal'
label = 'Cabal'
object_types = {
'pkg-section': ObjType(_('pkg-section'), 'pkg-section'),
'pkg-field' : ObjType(_('pkg-field') , 'pkg-field' ),
'cfg-section': ObjType(_('cfg-section'), 'cfg-section'),
'cfg-field' : ObjType(_('cfg-field') , 'cfg-field' ),
}
directives = {
'pkg-section': CabalPackageSection,
'pkg-field' : CabalPackageField,
'cfg-section': CabalConfigSection,
'cfg-field' : ConfigField,
}
roles = {
'pkg-section': XRefRole(warn_dangling=True),
'pkg-field' : CabalPackageFieldXRef(warn_dangling=True),
'cfg-section': XRefRole(warn_dangling=True),
'cfg-field' : CabalConfigFieldXRef(warn_dangling=True),
'cfg-flag' : CabalConfigFieldXRef(warn_dangling=True),
}
initial_data = {
'pkg-sections': {},
'pkg-fields' : {},
'cfg-sections': {},
'index-num' : {}, #per document number of objects
# used to order references page
'cfg-fields' : {},
'cfg-flags' : {},
}
indices = [
ConfigFieldIndex
]
types = {
'pkg-section': 'pkg-sections',
'pkg-field' : 'pkg-fields',
'cfg-section': 'cfg-sections',
'cfg-field' : 'cfg-fields',
'cfg-flag' : 'cfg-flags',
}
def clear_doc(self, docname):
for k in ['pkg-sections', 'pkg-fields', 'cfg-sections',
'cfg-fields', 'cfg-flags']:
to_del = []
for name, (fn, _, _) in self.data[k].items():
if fn == docname:
to_del.append(name)
for name in to_del:
del self.data[k][name]
try:
del self.data['index-num'][docname]
except KeyError:
pass
def resolve_xref(self, env, fromdocname, builder, type, target, node, contnode):
objtypes = self.objtypes_for_role(type)
for typ, key in ((typ, key)
for typ in objtypes
for key in make_data_keys(typ, target, node)):
try:
data = env.domaindata['cabal'][self.types[typ]][key]
except KeyError:
continue
doc, ref, meta = data
title = make_title(typ, key, meta)
return make_refnode(builder, fromdocname, doc, ref, contnode, title)
def get_objects(self):
'''
Used for search functionality
'''
for typ in ['pkg-section', 'pkg-field',
'cfg-section', 'cfg-field', 'cfg-flag']:
key = self.types[typ]
for name, (fn, target, meta) in self.data[key].items():
title = make_title(typ, name, meta)
yield title, title, typ, fn, target, 0
class CabalLexer(lexer.RegexLexer):
'''
Basic cabal lexer, does not try to be smart
'''
name = 'Cabal'
aliases = ['cabal']
filenames = ['.cabal']
flags = re.MULTILINE
tokens = {
'root' : [
(r'^(\s*)(--.*)$', lexer.bygroups(token.Whitespace, token.Comment.Single)),
# key: value
(r'^(\s*)([\w\-_]+)(:)',
lexer.bygroups(token.Whitespace, token.Keyword, token.Punctuation)),
(r'^([\w\-_]+)', token.Keyword), # library, executable, flag etc.
(r'[^\S\n]+', token.Text),
(r'&&|\|\||==|<=|\^>=|>=|<|>', token.Operator),
(r',|:|{|}', token.Punctuation),
(r'.', token.Text)
],
}
def setup(app):
app.add_domain(CabalDomain)
app.add_lexer('cabal', CabalLexer)