summaryrefslogtreecommitdiff
path: root/_exts/typescriptdomain.py
blob: ce21b3b02889c356b79d614a432c9ea3691f6080 (plain)
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
"""
TypeScript domain.

:copyright: Copyright 2019 by Taler Systems SA
:license: LGPLv3+
:author: Florian Dold
"""

import re

from docutils import nodes
from typing import List, Optional, Iterable, Dict, Tuple
from typing import cast

from pygments.lexers import get_lexer_by_name
from pygments.filter import Filter
from pygments.token import Literal, Text, Operator, Keyword, Name, Number
from pygments.token import Comment, Token, _TokenType
from pygments.token import *
from pygments.lexer import RegexLexer,  bygroups, include
from pygments.formatters import HtmlFormatter

from docutils import nodes
from docutils.nodes import Element, Node

from sphinx.roles import XRefRole
from sphinx.domains import Domain, ObjType, Index
from sphinx.directives import directives
from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import make_refnode
from sphinx.util import logging
from sphinx.highlighting import PygmentsBridge
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.pygments_styles import SphinxStyle

logger = logging.getLogger(__name__)


class TypeScriptDefinition(SphinxDirective):
    """
    Directive for a code block with special highlighting or line numbering
    settings.
    """

    has_content = True
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = False
    option_spec = {
        'force': directives.flag,
        'linenos': directives.flag,
        'dedent': int,
        'lineno-start': int,
        'emphasize-lines': directives.unchanged_required,
        'caption': directives.unchanged_required,
        'class': directives.class_option,
    }

    def run(self) -> List[Node]:
        document = self.state.document
        code = '\n'.join(self.content)
        location = self.state_machine.get_source_and_line(self.lineno)

        linespec = self.options.get('emphasize-lines')
        if linespec:
            try:
                nlines = len(self.content)
                hl_lines = parselinenos(linespec, nlines)
                if any(i >= nlines for i in hl_lines):
                    logger.warning(
                        __('line number spec is out of range(1-%d): %r') %
                        (nlines, self.options['emphasize-lines']),
                        location=location
                    )

                hl_lines = [x + 1 for x in hl_lines if x < nlines]
            except ValueError as err:
                return [document.reporter.warning(err, line=self.lineno)]
        else:
            hl_lines = None

        if 'dedent' in self.options:
            location = self.state_machine.get_source_and_line(self.lineno)
            lines = code.split('\n')
            lines = dedent_lines(
                lines, self.options['dedent'], location=location
            )
            code = '\n'.join(lines)

        literal = nodes.literal_block(code, code)  # type: Element
        if 'linenos' in self.options or 'lineno-start' in self.options:
            literal['linenos'] = True
        literal['classes'] += self.options.get('class', [])
        literal['force'] = 'force' in self.options
        literal['language'] = "tsref"
        extra_args = literal['highlight_args'] = {}
        if hl_lines is not None:
            extra_args['hl_lines'] = hl_lines
        if 'lineno-start' in self.options:
            extra_args['linenostart'] = self.options['lineno-start']
        self.set_source_info(literal)

        caption = self.options.get('caption')
        if caption:
            try:
                literal = container_wrapper(self, literal, caption)
            except ValueError as exc:
                return [document.reporter.warning(exc, line=self.lineno)]

        tsid = "tsref-type-" + self.arguments[0]
        literal['ids'].append(tsid)

        tsname = self.arguments[0]
        ts = self.env.get_domain('ts')
        ts.add_object('type', tsname, self.env.docname, tsid)

        return [literal]


class TypeScriptDomain(Domain):
    """TypeScript domain."""

    name = 'ts'
    label = 'TypeScript'

    directives = {
        'def': TypeScriptDefinition,
    }

    roles = {
        'type':
        XRefRole(
            lowercase=False, warn_dangling=True, innernodeclass=nodes.inline
        ),
    }

    dangling_warnings = {
        'type': 'undefined TypeScript type: %(target)s',
    }

    def resolve_xref(
        self, env, fromdocname, builder, typ, target, node, contnode
    ):
        try:
            info = self.objects[(str(typ), str(target))]
        except KeyError:
            logger.warn("type {}/{} not found".format(typ, target))
            return None
        else:
            anchor = "tsref-type-{}".format(str(target))
            title = typ.upper() + ' ' + target
            return make_refnode(
                builder, fromdocname, info[0], anchor, contnode, title
            )

    def resolve_any_xref(
        self, env, fromdocname, builder, target, node, contnode
    ):
        """Resolve the pending_xref *node* with the given *target*.

        The reference comes from an "any" or similar role, which means that Sphinx
        don't know the type.

        For now sphinxcontrib-httpdomain doesn't resolve any xref nodes.

        :return:
           list of tuples ``('domain:role', newnode)``, where ``'domain:role'``
           is the name of a role that could have created the same reference,
        """
        ret = []
        try:
            info = self.objects[("type", str(target))]
        except KeyError:
            pass
        else:
            anchor = "tsref-type-{}".format(str(target))
            title = "TYPE" + ' ' + target
            node = make_refnode(
                builder, fromdocname, info[0], anchor, contnode, title
            )
            ret.append(("ts:type", node))
        return ret

    @property
    def objects(self) -> Dict[Tuple[str, str], Tuple[str, str]]:
        return self.data.setdefault(
            'objects', {}
        )  # (objtype, name) -> docname, labelid

    def add_object(
        self, objtype: str, name: str, docname: str, labelid: str
    ) -> None:
        self.objects[objtype, name] = (docname, labelid)


class BetterTypeScriptLexer(RegexLexer):
    """
    For `TypeScript <https://www.typescriptlang.org/>`_ source code.
    """

    name = 'TypeScript'
    aliases = ['ts']
    filenames = ['*.ts']
    mimetypes = ['text/x-typescript']

    flags = re.DOTALL
    tokens = {
        'commentsandwhitespace': [(r'\s+', Text), (r'<!--', Comment),
                                  (r'//.*?\n', Comment.Single),
                                  (r'/\*.*?\*/', Comment.Multiline)],
        'slashstartsregex': [
            include('commentsandwhitespace'),
            (
                r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
                r'([gim]+\b|\B)', String.Regex, '#pop'
            ), (r'(?=/)', Text, ('#pop', 'badregex')), (r'', Text, '#pop')
        ],
        'badregex': [(r'\n', Text, '#pop')],
        'typeexp': [
            (r'[a-zA-Z0-9_?.$]+', Keyword.Type),
            (r'\s+', Text),
            (r'[|]', Text),
            (r'\n', Text, "#pop"),
            (r';', Text, "#pop"),
            (r'', Text, "#pop"),
        ],
        'root': [
            (r'^(?=\s|/|<!--)', Text, 'slashstartsregex'),
            include('commentsandwhitespace'),
            (
                r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|'
                r'(<<|>>>?|==?|!=?|[-<>+*%&\|\^/])=?', Operator,
                'slashstartsregex'
            ),
            (r'[{(\[;,]', Punctuation, 'slashstartsregex'),
            (r'[})\].]', Punctuation),
            (
                r'(for|in|while|do|break|return|continue|switch|case|default|if|else|'
                r'throw|try|catch|finally|new|delete|typeof|instanceof|void|'
                r'this)\b', Keyword, 'slashstartsregex'
            ),
            (
                r'(var|let|const|with|function)\b', Keyword.Declaration,
                'slashstartsregex'
            ),
            (
                r'(abstract|boolean|byte|char|class|const|debugger|double|enum|export|'
                r'extends|final|float|goto|implements|import|int|interface|long|native|'
                r'package|private|protected|public|short|static|super|synchronized|throws|'
                r'transient|volatile)\b', Keyword.Reserved
            ),
            (r'(true|false|null|NaN|Infinity|undefined)\b', Keyword.Constant),
            (
                r'(Array|Boolean|Date|Error|Function|Math|netscape|'
                r'Number|Object|Packages|RegExp|String|sun|decodeURI|'
                r'decodeURIComponent|encodeURI|encodeURIComponent|'
                r'Error|eval|isFinite|isNaN|parseFloat|parseInt|document|this|'
                r'window)\b', Name.Builtin
            ),
            # Match stuff like: module name {...}
            (
                r'\b(module)(\s*)(\s*[a-zA-Z0-9_?.$][\w?.$]*)(\s*)',
                bygroups(Keyword.Reserved, Text, Name.Other,
                         Text), 'slashstartsregex'
            ),
            # Match variable type keywords
            (r'\b(string|bool|number)\b', Keyword.Type),
            # Match stuff like: constructor
            (r'\b(constructor|declare|interface|as|AS)\b', Keyword.Reserved),
            # Match stuff like: super(argument, list)
            (
                r'(super)(\s*)\(([a-zA-Z0-9,_?.$\s]+\s*)\)',
                bygroups(Keyword.Reserved, Text), 'slashstartsregex'
            ),
            # Match stuff like: function() {...}
            (r'([a-zA-Z_?.$][\w?.$]*)\(\) \{', Name.Other, 'slashstartsregex'),
            # Match stuff like: (function: return type)
            (
                r'([a-zA-Z0-9_?.$][\w?.$]*)(\s*:\s*)',
                bygroups(Name.Other, Text), 'typeexp'
            ),
            # Match stuff like: type Foo = Bar | Baz
            (
                r'\b(type)(\s*)([a-zA-Z0-9_?.$]+)(\s*)(=)(\s*)',
                bygroups(
                    Keyword.Reserved, Text, Name.Other, Text, Operator, Text
                ), 'typeexp'
            ),
            (r'[$a-zA-Z_][a-zA-Z0-9_]*', Name.Other),
            (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
            (r'0x[0-9a-fA-F]+', Number.Hex),
            (r'[0-9]+', Number.Integer),
            (r'"(\\\\|\\"|[^"])*"', String.Double),
            (r"'(\\\\|\\'|[^'])*'", String.Single),
        ]
    }


# Map from token id to props.
# Properties can't be added to tokens
# since they derive from Python's tuple.
token_props = {}


class LinkFilter(Filter):
    def __init__(self, app, **options):
        self.app = app
        Filter.__init__(self, **options)

    def _filter_one_literal(self, ttype, value):
        last = 0
        for m in re.finditer(literal_reg, value):
            pre = value[last:m.start()]
            if pre:
                yield ttype, pre
            t = copy_token(ttype)
            tok_setprop(t, "is_literal", True)
            yield t, m.group(1)
            last = m.end()
        post = value[last:]
        if post:
            yield ttype, post


    def filter(self, lexer, stream):
        for ttype, value in stream:
            if ttype in Token.Keyword.Type:
                t = copy_token(ttype)
                tok_setprop(t, "xref", value.strip())
                tok_setprop(t, "is_identifier", True)
                yield t, value
            elif ttype in Token.Comment:
                last = 0
                for m in re.finditer(link_reg, value):
                    pre = value[last:m.start()]
                    if pre:
                        yield from self._filter_one_literal(ttype, pre)
                    t = copy_token(ttype)
                    x1, x2 = m.groups()
                    x0 = m.group(0)
                    if x2 is None:
                        caption = x1.strip()
                        xref = x1.strip()
                    else:
                        caption = x1.strip()
                        xref = x2.strip()
                    tok_setprop(t, "xref", xref)
                    tok_setprop(t, "caption", caption)
                    if x0.endswith("_"):
                        tok_setprop(t, "trailing_underscore", True)
                    yield t, m.group(1)
                    last = m.end()
                post = value[last:]
                if post:
                    yield from self._filter_one_literal(ttype, post)
            else:
                yield ttype, value


_escape_html_table = {
    ord('&'): u'&amp;',
    ord('<'): u'&lt;',
    ord('>'): u'&gt;',
    ord('"'): u'&quot;',
    ord("'"): u'&#39;',
}


class LinkingHtmlFormatter(HtmlFormatter):
    def __init__(self, **kwargs):
        super(LinkingHtmlFormatter, self).__init__(**kwargs)
        self._builder = kwargs['_builder']
        self._bridge = kwargs['_bridge']

    def _get_value(self, value, tok):
        xref = tok_getprop(tok, "xref")
        caption = tok_getprop(tok, "caption")

        if tok_getprop(tok, "is_literal"):
            return '<span style="font-weight: bolder">%s</span>' % (value,)

        if tok_getprop(tok, "trailing_underscore"):
            logger.warn(
                "{}:{}: code block contains xref to '{}' with unsupported trailing underscore"
                .format(self._bridge.path, self._bridge.line, xref)
            )

        if tok_getprop(tok, "is_identifier"):
            if xref.startswith('"'):
                return value
            if re.match("^[0-9]+$", xref) is not None:
                return value
            if xref in ("number", "object", "string", "boolean", "any", "true", "false", "null", "undefined", "Array"):
                return value

        if xref is None:
            return value
        content = caption if caption is not None else value
        ts = self._builder.env.get_domain('ts')
        r1 = ts.objects.get(("type", xref), None)
        if r1 is not None:
            rel_uri = self._builder.get_relative_uri(self._bridge.docname, r1[0]) + "#" + r1[1]
            return '<a style="color:inherit;text-decoration:underline" href="%s">%s</a>' % (
                rel_uri, content
            )

        std = self._builder.env.get_domain('std')
        r2 = std.labels.get(xref.lower(), None)
        if r2 is not None:
            rel_uri = self._builder.get_relative_uri(self._bridge.docname, r2[0]) + "#" + r2[1]
            return '<a style="color:inherit;text-decoration:underline" href="%s">%s</a>' % (
                rel_uri, content
            )
        r3 = std.anonlabels.get(xref.lower(), None)
        if r3 is not None:
            rel_uri = self._builder.get_relative_uri(self._bridge.docname, r3[0]) + "#" + r3[1]
            return '<a style="color:inherit;text-decoration:underline" href="%s">%s</a>' % (
                rel_uri, content
            )

        logger.warn("{}:{}: code block contains unresolved xref '{}'".format(self._bridge.path, self._bridge.line, xref))

        return value


    def _fmt(self, value, tok):
        cls = self._get_css_class(tok)
        value = self._get_value(value, tok)
        if cls is None or cls == "":
            return value
        return '<span class="%s">%s</span>' % (cls, value)

    def _format_lines(self, tokensource):
        """
        Just format the tokens, without any wrapping tags.
        Yield individual lines.
        """
        lsep = self.lineseparator
        escape_table = _escape_html_table

        line = ''
        for ttype, value in tokensource:
            link = get_annotation(ttype, "link")

            parts = value.translate(escape_table).split('\n')

            if len(parts) == 0:
                # empty token, usually should not happen
                pass
            elif len(parts) == 1:
                # no newline before or after token
                line += self._fmt(parts[0], ttype)
            else:
                line += self._fmt(parts[0], ttype)
                yield 1, line + lsep
                for part in parts[1:-1]:
                    yield 1, self._fmt(part, ttype) + lsep
                line = self._fmt(parts[-1], ttype)

        if line:
            yield 1, line + lsep


class MyPygmentsBridge(PygmentsBridge):
    def __init__(self, builder, trim_doctest_flags):
        self.dest = "html"
        self.trim_doctest_flags = trim_doctest_flags
        self.formatter_args = {
            'style': SphinxStyle,
            '_builder': builder,
            '_bridge': self
        }
        self.formatter = LinkingHtmlFormatter
        self.builder = builder
        self.path = None
        self.line = None
        self.docname = None

    def highlight_block(
        self, source, lang, opts=None, force=False, location=None, **kwargs
    ):
        docname, line = location
        self.line = line
        self.path = self.builder.env.doc2path(docname)
        self.docname = docname
        return super().highlight_block(
            source, lang, opts, force, location, **kwargs
        )


class MyHtmlBuilder(StandaloneHTMLBuilder):
    name = "html-linked"

    def init_highlighter(self):
        if self.config.pygments_style is not None:
            style = self.config.pygments_style
        elif self.theme:
            style = self.theme.get_confstr('theme', 'pygments_style', 'none')
        else:
            style = 'sphinx'
        self.highlighter = MyPygmentsBridge(
            self, self.config.trim_doctest_flags
        )
        self.dark_highlighter = None


def get_annotation(tok, key):
    if not hasattr(tok, "kv"):
        return None
    return tok.kv.get(key)


def copy_token(tok):
    new_tok = _TokenType(tok)
    # This part is very fragile against API changes ...
    new_tok.subtypes = set(tok.subtypes)
    new_tok.parent = tok.parent
    return new_tok


def tok_setprop(tok, key, value):
    tokid = id(tok)
    e = token_props.get(tokid)
    if e is None:
        e = token_props[tokid] = (tok, {})
    _, kv = e
    kv[key] = value


def tok_getprop(tok, key):
    tokid = id(tok)
    e = token_props.get(tokid)
    if e is None:
        return None
    _, kv = e
    return kv.get(key)


link_reg = re.compile(r"(?<!`)`([^`<]+)\s*(?:<([^>]+)>)?\s*`_?")
literal_reg = re.compile(r"``([^`]+)``")


def setup(app):
    lexer = BetterTypeScriptLexer()
    lexer.add_filter(LinkFilter(app))
    app.add_lexer('tsref', lexer)
    app.add_domain(TypeScriptDomain)
    app.add_builder(MyHtmlBuilder)