1# -*- coding: utf-8 -*-
2"""
3    pygments.lexers.theorem
4    ~~~~~~~~~~~~~~~~~~~~~~~
5
6    Lexers for theorem-proving languages.
7
8    :copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
9    :license: BSD, see LICENSE for details.
10"""
11
12import re
13
14from pygments.lexer import RegexLexer, default, words
15from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
16    Number, Punctuation, Generic
17
18__all__ = ['CoqLexer', 'IsabelleLexer', 'LeanLexer']
19
20
21class CoqLexer(RegexLexer):
22    """
23    For the `Coq <http://coq.inria.fr/>`_ theorem prover.
24
25    .. versionadded:: 1.5
26    """
27
28    name = 'Coq'
29    aliases = ['coq']
30    filenames = ['*.v']
31    mimetypes = ['text/x-coq']
32
33    keywords1 = (
34        # Vernacular commands
35        'Section', 'Module', 'End', 'Require', 'Import', 'Export', 'Variable',
36        'Variables', 'Parameter', 'Parameters', 'Axiom', 'Hypothesis',
37        'Hypotheses', 'Notation', 'Local', 'Tactic', 'Reserved', 'Scope',
38        'Open', 'Close', 'Bind', 'Delimit', 'Definition', 'Let', 'Ltac',
39        'Fixpoint', 'CoFixpoint', 'Morphism', 'Relation', 'Implicit',
40        'Arguments', 'Set', 'Unset', 'Contextual', 'Strict', 'Prenex',
41        'Implicits', 'Inductive', 'CoInductive', 'Record', 'Structure',
42        'Canonical', 'Coercion', 'Theorem', 'Lemma', 'Corollary',
43        'Proposition', 'Fact', 'Remark', 'Example', 'Proof', 'Goal', 'Save',
44        'Qed', 'Defined', 'Hint', 'Resolve', 'Rewrite', 'View', 'Search',
45        'Show', 'Print', 'Printing', 'All', 'Graph', 'Projections', 'inside',
46        'outside', 'Check', 'Global', 'Instance', 'Class', 'Existing',
47        'Universe', 'Polymorphic', 'Monomorphic', 'Context'
48    )
49    keywords2 = (
50        # Gallina
51        'forall', 'exists', 'exists2', 'fun', 'fix', 'cofix', 'struct',
52        'match', 'end',  'in', 'return', 'let', 'if', 'is', 'then', 'else',
53        'for', 'of', 'nosimpl', 'with', 'as',
54    )
55    keywords3 = (
56        # Sorts
57        'Type', 'Prop',
58    )
59    keywords4 = (
60        # Tactics
61        'pose', 'set', 'move', 'case', 'elim', 'apply', 'clear', 'hnf', 'intro',
62        'intros', 'generalize', 'rename', 'pattern', 'after', 'destruct',
63        'induction', 'using', 'refine', 'inversion', 'injection', 'rewrite',
64        'congr', 'unlock', 'compute', 'ring', 'field', 'replace', 'fold',
65        'unfold', 'change', 'cutrewrite', 'simpl', 'have', 'suff', 'wlog',
66        'suffices', 'without', 'loss', 'nat_norm', 'assert', 'cut', 'trivial',
67        'revert', 'bool_congr', 'nat_congr', 'symmetry', 'transitivity', 'auto',
68        'split', 'left', 'right', 'autorewrite', 'tauto', 'setoid_rewrite',
69        'intuition', 'eauto', 'eapply', 'econstructor', 'etransitivity',
70        'constructor', 'erewrite', 'red', 'cbv', 'lazy', 'vm_compute',
71        'native_compute', 'subst',
72    )
73    keywords5 = (
74        # Terminators
75        'by', 'done', 'exact', 'reflexivity', 'tauto', 'romega', 'omega',
76        'assumption', 'solve', 'contradiction', 'discriminate',
77        'congruence',
78    )
79    keywords6 = (
80        # Control
81        'do', 'last', 'first', 'try', 'idtac', 'repeat',
82    )
83    # 'as', 'assert', 'begin', 'class', 'constraint', 'do', 'done',
84    # 'downto', 'else', 'end', 'exception', 'external', 'false',
85    # 'for', 'fun', 'function', 'functor', 'if', 'in', 'include',
86    # 'inherit', 'initializer', 'lazy', 'let', 'match', 'method',
87    # 'module', 'mutable', 'new', 'object', 'of', 'open', 'private',
88    # 'raise', 'rec', 'sig', 'struct', 'then', 'to', 'true', 'try',
89    # 'type', 'val', 'virtual', 'when', 'while', 'with'
90    keyopts = (
91        '!=', '#', '&', '&&', r'\(', r'\)', r'\*', r'\+', ',', '-', r'-\.',
92        '->', r'\.', r'\.\.', ':', '::', ':=', ':>', ';', ';;', '<', '<-',
93        '<->', '=', '>', '>]', r'>\}', r'\?', r'\?\?', r'\[', r'\[<', r'\[>',
94        r'\[\|', ']', '_', '`', r'\{', r'\{<', r'\|', r'\|]', r'\}', '~', '=>',
95        r'/\\', r'\\/', r'\{\|', r'\|\}',
96        'Π', 'λ',
97    )
98    operators = r'[!$%&*+\./:<=>?@^|~-]'
99    prefix_syms = r'[!?~]'
100    infix_syms = r'[=<>@^|&+\*/$%-]'
101
102    tokens = {
103        'root': [
104            (r'\s+', Text),
105            (r'false|true|\(\)|\[\]', Name.Builtin.Pseudo),
106            (r'\(\*', Comment, 'comment'),
107            (words(keywords1, prefix=r'\b', suffix=r'\b'), Keyword.Namespace),
108            (words(keywords2, prefix=r'\b', suffix=r'\b'), Keyword),
109            (words(keywords3, prefix=r'\b', suffix=r'\b'), Keyword.Type),
110            (words(keywords4, prefix=r'\b', suffix=r'\b'), Keyword),
111            (words(keywords5, prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
112            (words(keywords6, prefix=r'\b', suffix=r'\b'), Keyword.Reserved),
113            # (r'\b([A-Z][\w\']*)(\.)', Name.Namespace, 'dotted'),
114            (r'\b([A-Z][\w\']*)', Name),
115            (r'(%s)' % '|'.join(keyopts[::-1]), Operator),
116            (r'(%s|%s)?%s' % (infix_syms, prefix_syms, operators), Operator),
117
118            (r"[^\W\d][\w']*", Name),
119
120            (r'\d[\d_]*', Number.Integer),
121            (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex),
122            (r'0[oO][0-7][0-7_]*', Number.Oct),
123            (r'0[bB][01][01_]*', Number.Bin),
124            (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float),
125
126            (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'",
127             String.Char),
128            (r"'.'", String.Char),
129            (r"'", Keyword),  # a stray quote is another syntax element
130
131            (r'"', String.Double, 'string'),
132
133            (r'[~?][a-z][\w\']*:', Name),
134        ],
135        'comment': [
136            (r'[^(*)]+', Comment),
137            (r'\(\*', Comment, '#push'),
138            (r'\*\)', Comment, '#pop'),
139            (r'[(*)]', Comment),
140        ],
141        'string': [
142            (r'[^"]+', String.Double),
143            (r'""', String.Double),
144            (r'"', String.Double, '#pop'),
145        ],
146        'dotted': [
147            (r'\s+', Text),
148            (r'\.', Punctuation),
149            (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace),
150            (r'[A-Z][\w\']*', Name.Class, '#pop'),
151            (r'[a-z][a-z0-9_\']*', Name, '#pop'),
152            default('#pop')
153        ],
154    }
155
156    def analyse_text(text):
157        if 'qed' in text and 'tauto' in text:
158            return 1
159
160
161class IsabelleLexer(RegexLexer):
162    """
163    For the `Isabelle <http://isabelle.in.tum.de/>`_ proof assistant.
164
165    .. versionadded:: 2.0
166    """
167
168    name = 'Isabelle'
169    aliases = ['isabelle']
170    filenames = ['*.thy']
171    mimetypes = ['text/x-isabelle']
172
173    keyword_minor = (
174        'and', 'assumes', 'attach', 'avoids', 'binder', 'checking',
175        'class_instance', 'class_relation', 'code_module', 'congs',
176        'constant', 'constrains', 'datatypes', 'defines', 'file', 'fixes',
177        'for', 'functions', 'hints', 'identifier', 'if', 'imports', 'in',
178        'includes', 'infix', 'infixl', 'infixr', 'is', 'keywords', 'lazy',
179        'module_name', 'monos', 'morphisms', 'no_discs_sels', 'notes',
180        'obtains', 'open', 'output', 'overloaded', 'parametric', 'permissive',
181        'pervasive', 'rep_compat', 'shows', 'structure', 'type_class',
182        'type_constructor', 'unchecked', 'unsafe', 'where',
183    )
184
185    keyword_diag = (
186        'ML_command', 'ML_val', 'class_deps', 'code_deps', 'code_thms',
187        'display_drafts', 'find_consts', 'find_theorems', 'find_unused_assms',
188        'full_prf', 'help', 'locale_deps', 'nitpick', 'pr', 'prf',
189        'print_abbrevs', 'print_antiquotations', 'print_attributes',
190        'print_binds', 'print_bnfs', 'print_bundles',
191        'print_case_translations', 'print_cases', 'print_claset',
192        'print_classes', 'print_codeproc', 'print_codesetup',
193        'print_coercions', 'print_commands', 'print_context',
194        'print_defn_rules', 'print_dependencies', 'print_facts',
195        'print_induct_rules', 'print_inductives', 'print_interps',
196        'print_locale', 'print_locales', 'print_methods', 'print_options',
197        'print_orders', 'print_quot_maps', 'print_quotconsts',
198        'print_quotients', 'print_quotientsQ3', 'print_quotmapsQ3',
199        'print_rules', 'print_simpset', 'print_state', 'print_statement',
200        'print_syntax', 'print_theorems', 'print_theory', 'print_trans_rules',
201        'prop', 'pwd', 'quickcheck', 'refute', 'sledgehammer', 'smt_status',
202        'solve_direct', 'spark_status', 'term', 'thm', 'thm_deps', 'thy_deps',
203        'try', 'try0', 'typ', 'unused_thms', 'value', 'values', 'welcome',
204        'print_ML_antiquotations', 'print_term_bindings', 'values_prolog',
205    )
206
207    keyword_thy = ('theory', 'begin', 'end')
208
209    keyword_section = ('header', 'chapter')
210
211    keyword_subsection = (
212        'section', 'subsection', 'subsubsection', 'sect', 'subsect',
213        'subsubsect',
214    )
215
216    keyword_theory_decl = (
217        'ML', 'ML_file', 'abbreviation', 'adhoc_overloading', 'arities',
218        'atom_decl', 'attribute_setup', 'axiomatization', 'bundle',
219        'case_of_simps', 'class', 'classes', 'classrel', 'codatatype',
220        'code_abort', 'code_class', 'code_const', 'code_datatype',
221        'code_identifier', 'code_include', 'code_instance', 'code_modulename',
222        'code_monad', 'code_printing', 'code_reflect', 'code_reserved',
223        'code_type', 'coinductive', 'coinductive_set', 'consts', 'context',
224        'datatype', 'datatype_new', 'datatype_new_compat', 'declaration',
225        'declare', 'default_sort', 'defer_recdef', 'definition', 'defs',
226        'domain', 'domain_isomorphism', 'domaindef', 'equivariance',
227        'export_code', 'extract', 'extract_type', 'fixrec', 'fun',
228        'fun_cases', 'hide_class', 'hide_const', 'hide_fact', 'hide_type',
229        'import_const_map', 'import_file', 'import_tptp', 'import_type_map',
230        'inductive', 'inductive_set', 'instantiation', 'judgment', 'lemmas',
231        'lifting_forget', 'lifting_update', 'local_setup', 'locale',
232        'method_setup', 'nitpick_params', 'no_adhoc_overloading',
233        'no_notation', 'no_syntax', 'no_translations', 'no_type_notation',
234        'nominal_datatype', 'nonterminal', 'notation', 'notepad', 'oracle',
235        'overloading', 'parse_ast_translation', 'parse_translation',
236        'partial_function', 'primcorec', 'primrec', 'primrec_new',
237        'print_ast_translation', 'print_translation', 'quickcheck_generator',
238        'quickcheck_params', 'realizability', 'realizers', 'recdef', 'record',
239        'refute_params', 'setup', 'setup_lifting', 'simproc_setup',
240        'simps_of_case', 'sledgehammer_params', 'spark_end', 'spark_open',
241        'spark_open_siv', 'spark_open_vcg', 'spark_proof_functions',
242        'spark_types', 'statespace', 'syntax', 'syntax_declaration', 'text',
243        'text_raw', 'theorems', 'translations', 'type_notation',
244        'type_synonym', 'typed_print_translation', 'typedecl', 'hoarestate',
245        'install_C_file', 'install_C_types', 'wpc_setup', 'c_defs', 'c_types',
246        'memsafe', 'SML_export', 'SML_file', 'SML_import', 'approximate',
247        'bnf_axiomatization', 'cartouche', 'datatype_compat',
248        'free_constructors', 'functor', 'nominal_function',
249        'nominal_termination', 'permanent_interpretation',
250        'binds', 'defining', 'smt2_status', 'term_cartouche',
251        'boogie_file', 'text_cartouche',
252    )
253
254    keyword_theory_script = ('inductive_cases', 'inductive_simps')
255
256    keyword_theory_goal = (
257        'ax_specification', 'bnf', 'code_pred', 'corollary', 'cpodef',
258        'crunch', 'crunch_ignore',
259        'enriched_type', 'function', 'instance', 'interpretation', 'lemma',
260        'lift_definition', 'nominal_inductive', 'nominal_inductive2',
261        'nominal_primrec', 'pcpodef', 'primcorecursive',
262        'quotient_definition', 'quotient_type', 'recdef_tc', 'rep_datatype',
263        'schematic_corollary', 'schematic_lemma', 'schematic_theorem',
264        'spark_vc', 'specification', 'subclass', 'sublocale', 'termination',
265        'theorem', 'typedef', 'wrap_free_constructors',
266    )
267
268    keyword_qed = ('by', 'done', 'qed')
269    keyword_abandon_proof = ('sorry', 'oops')
270
271    keyword_proof_goal = ('have', 'hence', 'interpret')
272
273    keyword_proof_block = ('next', 'proof')
274
275    keyword_proof_chain = (
276        'finally', 'from', 'then', 'ultimately', 'with',
277    )
278
279    keyword_proof_decl = (
280        'ML_prf', 'also', 'include', 'including', 'let', 'moreover', 'note',
281        'txt', 'txt_raw', 'unfolding', 'using', 'write',
282    )
283
284    keyword_proof_asm = ('assume', 'case', 'def', 'fix', 'presume')
285
286    keyword_proof_asm_goal = ('guess', 'obtain', 'show', 'thus')
287
288    keyword_proof_script = (
289        'apply', 'apply_end', 'apply_trace', 'back', 'defer', 'prefer',
290    )
291
292    operators = (
293        '::', ':', '(', ')', '[', ']', '_', '=', ',', '|',
294        '+', '-', '!', '?',
295    )
296
297    proof_operators = ('{', '}', '.', '..')
298
299    tokens = {
300        'root': [
301            (r'\s+', Text),
302            (r'\(\*', Comment, 'comment'),
303            (r'\{\*', Comment, 'text'),
304
305            (words(operators), Operator),
306            (words(proof_operators), Operator.Word),
307
308            (words(keyword_minor, prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
309
310            (words(keyword_diag, prefix=r'\b', suffix=r'\b'), Keyword.Type),
311
312            (words(keyword_thy, prefix=r'\b', suffix=r'\b'), Keyword),
313            (words(keyword_theory_decl, prefix=r'\b', suffix=r'\b'), Keyword),
314
315            (words(keyword_section, prefix=r'\b', suffix=r'\b'), Generic.Heading),
316            (words(keyword_subsection, prefix=r'\b', suffix=r'\b'), Generic.Subheading),
317
318            (words(keyword_theory_goal, prefix=r'\b', suffix=r'\b'), Keyword.Namespace),
319            (words(keyword_theory_script, prefix=r'\b', suffix=r'\b'), Keyword.Namespace),
320
321            (words(keyword_abandon_proof, prefix=r'\b', suffix=r'\b'), Generic.Error),
322
323            (words(keyword_qed, prefix=r'\b', suffix=r'\b'), Keyword),
324            (words(keyword_proof_goal, prefix=r'\b', suffix=r'\b'), Keyword),
325            (words(keyword_proof_block, prefix=r'\b', suffix=r'\b'), Keyword),
326            (words(keyword_proof_decl, prefix=r'\b', suffix=r'\b'), Keyword),
327
328            (words(keyword_proof_chain, prefix=r'\b', suffix=r'\b'), Keyword),
329            (words(keyword_proof_asm, prefix=r'\b', suffix=r'\b'), Keyword),
330            (words(keyword_proof_asm_goal, prefix=r'\b', suffix=r'\b'), Keyword),
331
332            (words(keyword_proof_script, prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
333
334            (r'\\<\w*>', Text.Symbol),
335
336            (r"[^\W\d][.\w']*", Name),
337            (r"\?[^\W\d][.\w']*", Name),
338            (r"'[^\W\d][.\w']*", Name.Type),
339
340            (r'\d[\d_]*', Name),  # display numbers as name
341            (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex),
342            (r'0[oO][0-7][0-7_]*', Number.Oct),
343            (r'0[bB][01][01_]*', Number.Bin),
344
345            (r'"', String, 'string'),
346            (r'`', String.Other, 'fact'),
347        ],
348        'comment': [
349            (r'[^(*)]+', Comment),
350            (r'\(\*', Comment, '#push'),
351            (r'\*\)', Comment, '#pop'),
352            (r'[(*)]', Comment),
353        ],
354        'text': [
355            (r'[^*}]+', Comment),
356            (r'\*\}', Comment, '#pop'),
357            (r'\*', Comment),
358            (r'\}', Comment),
359        ],
360        'string': [
361            (r'[^"\\]+', String),
362            (r'\\<\w*>', String.Symbol),
363            (r'\\"', String),
364            (r'\\', String),
365            (r'"', String, '#pop'),
366        ],
367        'fact': [
368            (r'[^`\\]+', String.Other),
369            (r'\\<\w*>', String.Symbol),
370            (r'\\`', String.Other),
371            (r'\\', String.Other),
372            (r'`', String.Other, '#pop'),
373        ],
374    }
375
376
377class LeanLexer(RegexLexer):
378    """
379    For the `Lean <https://github.com/leanprover/lean>`_
380    theorem prover.
381
382    .. versionadded:: 2.0
383    """
384    name = 'Lean'
385    aliases = ['lean']
386    filenames = ['*.lean']
387    mimetypes = ['text/x-lean']
388
389    flags = re.MULTILINE | re.UNICODE
390
391    tokens = {
392        'root': [
393            (r'\s+', Text),
394            (r'/--', String.Doc, 'docstring'),
395            (r'/-', Comment, 'comment'),
396            (r'--.*?$', Comment.Single),
397            (words((
398                'import', 'renaming', 'hiding',
399                'namespace',
400                'local',
401                'private', 'protected', 'section',
402                'include', 'omit', 'section',
403                'protected', 'export',
404                'open',
405                'attribute',
406            ), prefix=r'\b', suffix=r'\b'), Keyword.Namespace),
407            (words((
408                'lemma', 'theorem', 'def', 'definition', 'example',
409                'axiom', 'axioms', 'constant', 'constants',
410                'universe', 'universes',
411                'inductive', 'coinductive', 'structure', 'extends',
412                'class', 'instance',
413
414                'noncomputable theory',
415
416                'noncomputable', 'mutual', 'meta',
417
418                'attribute',
419
420                'parameter', 'parameters',
421                'variable', 'variables',
422
423                'reserve', 'precedence',
424                'postfix', 'prefix', 'notation', 'infix', 'infixl', 'infixr',
425
426                'begin', 'by', 'end',
427
428                'set_option',
429                'run_cmd',
430            ), prefix=r'\b', suffix=r'\b'), Keyword.Declaration),
431            (r'@\[[^\]]*\]', Keyword.Declaration),
432            (words((
433                'forall', 'fun', 'Pi', 'from', 'have', 'show', 'assume', 'suffices',
434                'let', 'if', 'else', 'then', 'in', 'with', 'calc', 'match',
435                'do'
436            ), prefix=r'\b', suffix=r'\b'), Keyword),
437            (words(('Sort', 'Prop', 'Type'), prefix=r'\b', suffix=r'\b'), Keyword.Type),
438            (words((
439                '#eval', '#check', '#reduce', '#exit',
440                '#print', '#help',
441            ), suffix=r'\b'), Keyword),
442            (words((
443                '(', ')', ':', '{', '}', '[', ']', '⟨', '⟩', '‹', '›', '⦃', '⦄', ':=', ',',
444            )), Operator),
445            (r'[A-Za-z_\u03b1-\u03ba\u03bc-\u03fb\u1f00-\u1ffe\u2100-\u214f]'
446             r'[.A-Za-z_\'\u03b1-\u03ba\u03bc-\u03fb\u1f00-\u1ffe\u2070-\u2079'
447             r'\u207f-\u2089\u2090-\u209c\u2100-\u214f0-9]*', Name),
448            (r'0x[A-Za-z0-9]+', Number.Integer),
449            (r'0b[01]+', Number.Integer),
450            (r'\d+', Number.Integer),
451            (r'"', String.Double, 'string'),
452            (r"'(?:(\\[\\\"'nt])|(\\x[0-9a-fA-F]{2})|(\\u[0-9a-fA-F]{4})|.)'", String.Char),
453            (r'[~?][a-z][\w\']*:', Name.Variable),
454            (r'\S', Name.Builtin.Pseudo),
455        ],
456        'comment': [
457            (r'[^/-]', Comment.Multiline),
458            (r'/-', Comment.Multiline, '#push'),
459            (r'-/', Comment.Multiline, '#pop'),
460            (r'[/-]', Comment.Multiline)
461        ],
462        'docstring': [
463            (r'[^/-]', String.Doc),
464            (r'-/', String.Doc, '#pop'),
465            (r'[/-]', String.Doc)
466        ],
467        'string': [
468            (r'[^\\"]+', String.Double),
469            (r"(?:(\\[\\\"'nt])|(\\x[0-9a-fA-F]{2})|(\\u[0-9a-fA-F]{4}))", String.Escape),
470            ('"', String.Double, '#pop'),
471        ],
472    }
473