esoteric.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """
  2. pygments.lexers.esoteric
  3. ~~~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for esoteric languages.
  5. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. from pygments.lexer import RegexLexer, include, words
  9. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  10. Number, Punctuation, Error
  11. import re
  12. __all__ = ['BrainfuckLexer', 'BefungeLexer', 'RedcodeLexer', 'CAmkESLexer',
  13. 'CapDLLexer', 'AheuiLexer']
  14. class BrainfuckLexer(RegexLexer):
  15. """
  16. Lexer for the esoteric `BrainFuck <http://www.muppetlabs.com/~breadbox/bf/>`_
  17. language.
  18. """
  19. name = 'Brainfuck'
  20. aliases = ['brainfuck', 'bf']
  21. filenames = ['*.bf', '*.b']
  22. mimetypes = ['application/x-brainfuck']
  23. tokens = {
  24. 'common': [
  25. # use different colors for different instruction types
  26. (r'[.,]+', Name.Tag),
  27. (r'[+-]+', Name.Builtin),
  28. (r'[<>]+', Name.Variable),
  29. (r'[^.,+\-<>\[\]]+', Comment),
  30. ],
  31. 'root': [
  32. (r'\[', Keyword, 'loop'),
  33. (r'\]', Error),
  34. include('common'),
  35. ],
  36. 'loop': [
  37. (r'\[', Keyword, '#push'),
  38. (r'\]', Keyword, '#pop'),
  39. include('common'),
  40. ]
  41. }
  42. def analyse_text(text):
  43. """It's safe to assume that a program which mostly consists of + -
  44. and < > is brainfuck."""
  45. plus_minus_count = 0
  46. greater_less_count = 0
  47. range_to_check = max(256, len(text))
  48. for c in text[:range_to_check]:
  49. if c == '+' or c == '-':
  50. plus_minus_count += 1
  51. if c == '<' or c == '>':
  52. greater_less_count += 1
  53. if plus_minus_count > (0.25 * range_to_check):
  54. return 1.0
  55. if greater_less_count > (0.25 * range_to_check):
  56. return 1.0
  57. result = 0
  58. if '[-]' in text:
  59. result += 0.5
  60. return result
  61. class BefungeLexer(RegexLexer):
  62. """
  63. Lexer for the esoteric `Befunge <http://en.wikipedia.org/wiki/Befunge>`_
  64. language.
  65. .. versionadded:: 0.7
  66. """
  67. name = 'Befunge'
  68. aliases = ['befunge']
  69. filenames = ['*.befunge']
  70. mimetypes = ['application/x-befunge']
  71. tokens = {
  72. 'root': [
  73. (r'[0-9a-f]', Number),
  74. (r'[+*/%!`-]', Operator), # Traditional math
  75. (r'[<>^v?\[\]rxjk]', Name.Variable), # Move, imperatives
  76. (r'[:\\$.,n]', Name.Builtin), # Stack ops, imperatives
  77. (r'[|_mw]', Keyword),
  78. (r'[{}]', Name.Tag), # Befunge-98 stack ops
  79. (r'".*?"', String.Double), # Strings don't appear to allow escapes
  80. (r'\'.', String.Single), # Single character
  81. (r'[#;]', Comment), # Trampoline... depends on direction hit
  82. (r'[pg&~=@iotsy]', Keyword), # Misc
  83. (r'[()A-Z]', Comment), # Fingerprints
  84. (r'\s+', Text), # Whitespace doesn't matter
  85. ],
  86. }
  87. class CAmkESLexer(RegexLexer):
  88. """
  89. Basic lexer for the input language for the
  90. `CAmkES <https://sel4.systems/CAmkES/>`_ component platform.
  91. .. versionadded:: 2.1
  92. """
  93. name = 'CAmkES'
  94. aliases = ['camkes', 'idl4']
  95. filenames = ['*.camkes', '*.idl4']
  96. tokens = {
  97. 'root': [
  98. # C pre-processor directive
  99. (r'^\s*#.*\n', Comment.Preproc),
  100. # Whitespace, comments
  101. (r'\s+', Text),
  102. (r'/\*(.|\n)*?\*/', Comment),
  103. (r'//.*\n', Comment),
  104. (r'[\[(){},.;\]]', Punctuation),
  105. (r'[~!%^&*+=|?:<>/-]', Operator),
  106. (words(('assembly', 'attribute', 'component', 'composition',
  107. 'configuration', 'connection', 'connector', 'consumes',
  108. 'control', 'dataport', 'Dataport', 'Dataports', 'emits',
  109. 'event', 'Event', 'Events', 'export', 'from', 'group',
  110. 'hardware', 'has', 'interface', 'Interface', 'maybe',
  111. 'procedure', 'Procedure', 'Procedures', 'provides',
  112. 'template', 'thread', 'threads', 'to', 'uses', 'with'),
  113. suffix=r'\b'), Keyword),
  114. (words(('bool', 'boolean', 'Buf', 'char', 'character', 'double',
  115. 'float', 'in', 'inout', 'int', 'int16_6', 'int32_t',
  116. 'int64_t', 'int8_t', 'integer', 'mutex', 'out', 'real',
  117. 'refin', 'semaphore', 'signed', 'string', 'struct',
  118. 'uint16_t', 'uint32_t', 'uint64_t', 'uint8_t', 'uintptr_t',
  119. 'unsigned', 'void'),
  120. suffix=r'\b'), Keyword.Type),
  121. # Recognised attributes
  122. (r'[a-zA-Z_]\w*_(priority|domain|buffer)', Keyword.Reserved),
  123. (words(('dma_pool', 'from_access', 'to_access'), suffix=r'\b'),
  124. Keyword.Reserved),
  125. # CAmkES-level include
  126. (r'import\s+(<[^>]*>|"[^"]*");', Comment.Preproc),
  127. # C-level include
  128. (r'include\s+(<[^>]*>|"[^"]*");', Comment.Preproc),
  129. # Literals
  130. (r'0[xX][\da-fA-F]+', Number.Hex),
  131. (r'-?[\d]+', Number),
  132. (r'-?[\d]+\.[\d]+', Number.Float),
  133. (r'"[^"]*"', String),
  134. (r'[Tt]rue|[Ff]alse', Name.Builtin),
  135. # Identifiers
  136. (r'[a-zA-Z_]\w*', Name),
  137. ],
  138. }
  139. class CapDLLexer(RegexLexer):
  140. """
  141. Basic lexer for
  142. `CapDL <https://ssrg.nicta.com.au/publications/nictaabstracts/Kuz_KLW_10.abstract.pml>`_.
  143. The source of the primary tool that reads such specifications is available
  144. at https://github.com/seL4/capdl/tree/master/capDL-tool. Note that this
  145. lexer only supports a subset of the grammar. For example, identifiers can
  146. shadow type names, but these instances are currently incorrectly
  147. highlighted as types. Supporting this would need a stateful lexer that is
  148. considered unnecessarily complex for now.
  149. .. versionadded:: 2.2
  150. """
  151. name = 'CapDL'
  152. aliases = ['capdl']
  153. filenames = ['*.cdl']
  154. tokens = {
  155. 'root': [
  156. # C pre-processor directive
  157. (r'^\s*#.*\n', Comment.Preproc),
  158. # Whitespace, comments
  159. (r'\s+', Text),
  160. (r'/\*(.|\n)*?\*/', Comment),
  161. (r'(//|--).*\n', Comment),
  162. (r'[<>\[(){},:;=\]]', Punctuation),
  163. (r'\.\.', Punctuation),
  164. (words(('arch', 'arm11', 'caps', 'child_of', 'ia32', 'irq', 'maps',
  165. 'objects'), suffix=r'\b'), Keyword),
  166. (words(('aep', 'asid_pool', 'cnode', 'ep', 'frame', 'io_device',
  167. 'io_ports', 'io_pt', 'notification', 'pd', 'pt', 'tcb',
  168. 'ut', 'vcpu'), suffix=r'\b'), Keyword.Type),
  169. # Properties
  170. (words(('asid', 'addr', 'badge', 'cached', 'dom', 'domainID', 'elf',
  171. 'fault_ep', 'G', 'guard', 'guard_size', 'init', 'ip',
  172. 'prio', 'sp', 'R', 'RG', 'RX', 'RW', 'RWG', 'RWX', 'W',
  173. 'WG', 'WX', 'level', 'masked', 'master_reply', 'paddr',
  174. 'ports', 'reply', 'uncached'), suffix=r'\b'),
  175. Keyword.Reserved),
  176. # Literals
  177. (r'0[xX][\da-fA-F]+', Number.Hex),
  178. (r'\d+(\.\d+)?(k|M)?', Number),
  179. (words(('bits',), suffix=r'\b'), Number),
  180. (words(('cspace', 'vspace', 'reply_slot', 'caller_slot',
  181. 'ipc_buffer_slot'), suffix=r'\b'), Number),
  182. # Identifiers
  183. (r'[a-zA-Z_][-@\.\w]*', Name),
  184. ],
  185. }
  186. class RedcodeLexer(RegexLexer):
  187. """
  188. A simple Redcode lexer based on ICWS'94.
  189. Contributed by Adam Blinkinsop <blinks@acm.org>.
  190. .. versionadded:: 0.8
  191. """
  192. name = 'Redcode'
  193. aliases = ['redcode']
  194. filenames = ['*.cw']
  195. opcodes = ('DAT', 'MOV', 'ADD', 'SUB', 'MUL', 'DIV', 'MOD',
  196. 'JMP', 'JMZ', 'JMN', 'DJN', 'CMP', 'SLT', 'SPL',
  197. 'ORG', 'EQU', 'END')
  198. modifiers = ('A', 'B', 'AB', 'BA', 'F', 'X', 'I')
  199. tokens = {
  200. 'root': [
  201. # Whitespace:
  202. (r'\s+', Text),
  203. (r';.*$', Comment.Single),
  204. # Lexemes:
  205. # Identifiers
  206. (r'\b(%s)\b' % '|'.join(opcodes), Name.Function),
  207. (r'\b(%s)\b' % '|'.join(modifiers), Name.Decorator),
  208. (r'[A-Za-z_]\w+', Name),
  209. # Operators
  210. (r'[-+*/%]', Operator),
  211. (r'[#$@<>]', Operator), # mode
  212. (r'[.,]', Punctuation), # mode
  213. # Numbers
  214. (r'[-+]?\d+', Number.Integer),
  215. ],
  216. }
  217. class AheuiLexer(RegexLexer):
  218. """
  219. Aheui_ Lexer.
  220. Aheui_ is esoteric language based on Korean alphabets.
  221. .. _Aheui: http://aheui.github.io/
  222. """
  223. name = 'Aheui'
  224. aliases = ['aheui']
  225. filenames = ['*.aheui']
  226. tokens = {
  227. 'root': [
  228. ('['
  229. '나-낳냐-냫너-넣녀-녛노-놓뇨-눟뉴-닇'
  230. '다-닿댜-댷더-덯뎌-뎧도-돟됴-둫듀-딓'
  231. '따-땋땨-떃떠-떻뗘-뗳또-똫뚀-뚷뜌-띟'
  232. '라-랗랴-럏러-렇려-렿로-롷료-뤃류-릫'
  233. '마-맣먀-먛머-멓며-몋모-뫃묘-뭏뮤-믷'
  234. '바-밯뱌-뱧버-벟벼-볗보-봏뵤-붛뷰-빃'
  235. '빠-빻뺘-뺳뻐-뻫뼈-뼣뽀-뽛뾰-뿧쀼-삏'
  236. '사-샇샤-샿서-섷셔-셯소-솧쇼-숳슈-싛'
  237. '싸-쌓쌰-썋써-쎃쎠-쎻쏘-쏳쑈-쑿쓔-씧'
  238. '자-잫쟈-쟣저-젛져-졓조-좋죠-줗쥬-즿'
  239. '차-챃챠-챻처-첳쳐-쳫초-촣쵸-춯츄-칗'
  240. '카-캏캬-컇커-컿켜-켷코-콯쿄-쿻큐-킣'
  241. '타-탛탸-턓터-텋텨-톃토-톻툐-퉇튜-틯'
  242. '파-팧퍄-퍟퍼-펗펴-폏포-퐇표-풓퓨-픻'
  243. '하-핳햐-햫허-헣혀-혛호-홓효-훟휴-힇'
  244. ']', Operator),
  245. ('.', Comment),
  246. ],
  247. }