erlang.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """
  2. pygments.lexers.erlang
  3. ~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for Erlang.
  5. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions, \
  10. include, default
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation, Generic
  13. __all__ = ['ErlangLexer', 'ErlangShellLexer', 'ElixirConsoleLexer',
  14. 'ElixirLexer']
  15. line_re = re.compile('.*?\n')
  16. class ErlangLexer(RegexLexer):
  17. """
  18. For the Erlang functional programming language.
  19. Blame Jeremy Thurgood (http://jerith.za.net/).
  20. .. versionadded:: 0.9
  21. """
  22. name = 'Erlang'
  23. aliases = ['erlang']
  24. filenames = ['*.erl', '*.hrl', '*.es', '*.escript']
  25. mimetypes = ['text/x-erlang']
  26. keywords = (
  27. 'after', 'begin', 'case', 'catch', 'cond', 'end', 'fun', 'if',
  28. 'let', 'of', 'query', 'receive', 'try', 'when',
  29. )
  30. builtins = ( # See erlang(3) man page
  31. 'abs', 'append_element', 'apply', 'atom_to_list', 'binary_to_list',
  32. 'bitstring_to_list', 'binary_to_term', 'bit_size', 'bump_reductions',
  33. 'byte_size', 'cancel_timer', 'check_process_code', 'delete_module',
  34. 'demonitor', 'disconnect_node', 'display', 'element', 'erase', 'exit',
  35. 'float', 'float_to_list', 'fun_info', 'fun_to_list',
  36. 'function_exported', 'garbage_collect', 'get', 'get_keys',
  37. 'group_leader', 'hash', 'hd', 'integer_to_list', 'iolist_to_binary',
  38. 'iolist_size', 'is_atom', 'is_binary', 'is_bitstring', 'is_boolean',
  39. 'is_builtin', 'is_float', 'is_function', 'is_integer', 'is_list',
  40. 'is_number', 'is_pid', 'is_port', 'is_process_alive', 'is_record',
  41. 'is_reference', 'is_tuple', 'length', 'link', 'list_to_atom',
  42. 'list_to_binary', 'list_to_bitstring', 'list_to_existing_atom',
  43. 'list_to_float', 'list_to_integer', 'list_to_pid', 'list_to_tuple',
  44. 'load_module', 'localtime_to_universaltime', 'make_tuple', 'md5',
  45. 'md5_final', 'md5_update', 'memory', 'module_loaded', 'monitor',
  46. 'monitor_node', 'node', 'nodes', 'open_port', 'phash', 'phash2',
  47. 'pid_to_list', 'port_close', 'port_command', 'port_connect',
  48. 'port_control', 'port_call', 'port_info', 'port_to_list',
  49. 'process_display', 'process_flag', 'process_info', 'purge_module',
  50. 'put', 'read_timer', 'ref_to_list', 'register', 'resume_process',
  51. 'round', 'send', 'send_after', 'send_nosuspend', 'set_cookie',
  52. 'setelement', 'size', 'spawn', 'spawn_link', 'spawn_monitor',
  53. 'spawn_opt', 'split_binary', 'start_timer', 'statistics',
  54. 'suspend_process', 'system_flag', 'system_info', 'system_monitor',
  55. 'system_profile', 'term_to_binary', 'tl', 'trace', 'trace_delivered',
  56. 'trace_info', 'trace_pattern', 'trunc', 'tuple_size', 'tuple_to_list',
  57. 'universaltime_to_localtime', 'unlink', 'unregister', 'whereis'
  58. )
  59. operators = r'(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)'
  60. word_operators = (
  61. 'and', 'andalso', 'band', 'bnot', 'bor', 'bsl', 'bsr', 'bxor',
  62. 'div', 'not', 'or', 'orelse', 'rem', 'xor'
  63. )
  64. atom_re = r"(?:[a-z]\w*|'[^\n']*[^\\]')"
  65. variable_re = r'(?:[A-Z_]\w*)'
  66. esc_char_re = r'[bdefnrstv\'"\\]'
  67. esc_octal_re = r'[0-7][0-7]?[0-7]?'
  68. esc_hex_re = r'(?:x[0-9a-fA-F]{2}|x\{[0-9a-fA-F]+\})'
  69. esc_ctrl_re = r'\^[a-zA-Z]'
  70. escape_re = r'(?:\\(?:'+esc_char_re+r'|'+esc_octal_re+r'|'+esc_hex_re+r'|'+esc_ctrl_re+r'))'
  71. macro_re = r'(?:'+variable_re+r'|'+atom_re+r')'
  72. base_re = r'(?:[2-9]|[12][0-9]|3[0-6])'
  73. tokens = {
  74. 'root': [
  75. (r'\s+', Text),
  76. (r'%.*\n', Comment),
  77. (words(keywords, suffix=r'\b'), Keyword),
  78. (words(builtins, suffix=r'\b'), Name.Builtin),
  79. (words(word_operators, suffix=r'\b'), Operator.Word),
  80. (r'^-', Punctuation, 'directive'),
  81. (operators, Operator),
  82. (r'"', String, 'string'),
  83. (r'<<', Name.Label),
  84. (r'>>', Name.Label),
  85. ('(' + atom_re + ')(:)', bygroups(Name.Namespace, Punctuation)),
  86. ('(?:^|(?<=:))(' + atom_re + r')(\s*)(\()',
  87. bygroups(Name.Function, Text, Punctuation)),
  88. (r'[+-]?' + base_re + r'#[0-9a-zA-Z]+', Number.Integer),
  89. (r'[+-]?\d+', Number.Integer),
  90. (r'[+-]?\d+.\d+', Number.Float),
  91. (r'[]\[:_@\".{}()|;,]', Punctuation),
  92. (variable_re, Name.Variable),
  93. (atom_re, Name),
  94. (r'\?'+macro_re, Name.Constant),
  95. (r'\$(?:'+escape_re+r'|\\[ %]|[^\\])', String.Char),
  96. (r'#'+atom_re+r'(:?\.'+atom_re+r')?', Name.Label),
  97. # Erlang script shebang
  98. (r'\A#!.+\n', Comment.Hashbang),
  99. # EEP 43: Maps
  100. # http://www.erlang.org/eeps/eep-0043.html
  101. (r'#\{', Punctuation, 'map_key'),
  102. ],
  103. 'string': [
  104. (escape_re, String.Escape),
  105. (r'"', String, '#pop'),
  106. (r'~[0-9.*]*[~#+BPWXb-ginpswx]', String.Interpol),
  107. (r'[^"\\~]+', String),
  108. (r'~', String),
  109. ],
  110. 'directive': [
  111. (r'(define)(\s*)(\()('+macro_re+r')',
  112. bygroups(Name.Entity, Text, Punctuation, Name.Constant), '#pop'),
  113. (r'(record)(\s*)(\()('+macro_re+r')',
  114. bygroups(Name.Entity, Text, Punctuation, Name.Label), '#pop'),
  115. (atom_re, Name.Entity, '#pop'),
  116. ],
  117. 'map_key': [
  118. include('root'),
  119. (r'=>', Punctuation, 'map_val'),
  120. (r':=', Punctuation, 'map_val'),
  121. (r'\}', Punctuation, '#pop'),
  122. ],
  123. 'map_val': [
  124. include('root'),
  125. (r',', Punctuation, '#pop'),
  126. (r'(?=\})', Punctuation, '#pop'),
  127. ],
  128. }
  129. class ErlangShellLexer(Lexer):
  130. """
  131. Shell sessions in erl (for Erlang code).
  132. .. versionadded:: 1.1
  133. """
  134. name = 'Erlang erl session'
  135. aliases = ['erl']
  136. filenames = ['*.erl-sh']
  137. mimetypes = ['text/x-erl-shellsession']
  138. _prompt_re = re.compile(r'(?:\([\w@_.]+\))?\d+>(?=\s|\Z)')
  139. def get_tokens_unprocessed(self, text):
  140. erlexer = ErlangLexer(**self.options)
  141. curcode = ''
  142. insertions = []
  143. for match in line_re.finditer(text):
  144. line = match.group()
  145. m = self._prompt_re.match(line)
  146. if m is not None:
  147. end = m.end()
  148. insertions.append((len(curcode),
  149. [(0, Generic.Prompt, line[:end])]))
  150. curcode += line[end:]
  151. else:
  152. if curcode:
  153. yield from do_insertions(insertions,
  154. erlexer.get_tokens_unprocessed(curcode))
  155. curcode = ''
  156. insertions = []
  157. if line.startswith('*'):
  158. yield match.start(), Generic.Traceback, line
  159. else:
  160. yield match.start(), Generic.Output, line
  161. if curcode:
  162. yield from do_insertions(insertions,
  163. erlexer.get_tokens_unprocessed(curcode))
  164. def gen_elixir_string_rules(name, symbol, token):
  165. states = {}
  166. states['string_' + name] = [
  167. (r'[^#%s\\]+' % (symbol,), token),
  168. include('escapes'),
  169. (r'\\.', token),
  170. (r'(%s)' % (symbol,), bygroups(token), "#pop"),
  171. include('interpol')
  172. ]
  173. return states
  174. def gen_elixir_sigstr_rules(term, term_class, token, interpol=True):
  175. if interpol:
  176. return [
  177. (r'[^#%s\\]+' % (term_class,), token),
  178. include('escapes'),
  179. (r'\\.', token),
  180. (r'%s[a-zA-Z]*' % (term,), token, '#pop'),
  181. include('interpol')
  182. ]
  183. else:
  184. return [
  185. (r'[^%s\\]+' % (term_class,), token),
  186. (r'\\.', token),
  187. (r'%s[a-zA-Z]*' % (term,), token, '#pop'),
  188. ]
  189. class ElixirLexer(RegexLexer):
  190. """
  191. For the `Elixir language <http://elixir-lang.org>`_.
  192. .. versionadded:: 1.5
  193. """
  194. name = 'Elixir'
  195. aliases = ['elixir', 'ex', 'exs']
  196. filenames = ['*.ex', '*.eex', '*.exs', '*.leex']
  197. mimetypes = ['text/x-elixir']
  198. KEYWORD = ('fn', 'do', 'end', 'after', 'else', 'rescue', 'catch')
  199. KEYWORD_OPERATOR = ('not', 'and', 'or', 'when', 'in')
  200. BUILTIN = (
  201. 'case', 'cond', 'for', 'if', 'unless', 'try', 'receive', 'raise',
  202. 'quote', 'unquote', 'unquote_splicing', 'throw', 'super',
  203. )
  204. BUILTIN_DECLARATION = (
  205. 'def', 'defp', 'defmodule', 'defprotocol', 'defmacro', 'defmacrop',
  206. 'defdelegate', 'defexception', 'defstruct', 'defimpl', 'defcallback',
  207. )
  208. BUILTIN_NAMESPACE = ('import', 'require', 'use', 'alias')
  209. CONSTANT = ('nil', 'true', 'false')
  210. PSEUDO_VAR = ('_', '__MODULE__', '__DIR__', '__ENV__', '__CALLER__')
  211. OPERATORS3 = (
  212. '<<<', '>>>', '|||', '&&&', '^^^', '~~~', '===', '!==',
  213. '~>>', '<~>', '|~>', '<|>',
  214. )
  215. OPERATORS2 = (
  216. '==', '!=', '<=', '>=', '&&', '||', '<>', '++', '--', '|>', '=~',
  217. '->', '<-', '|', '.', '=', '~>', '<~',
  218. )
  219. OPERATORS1 = ('<', '>', '+', '-', '*', '/', '!', '^', '&')
  220. PUNCTUATION = (
  221. '\\\\', '<<', '>>', '=>', '(', ')', ':', ';', ',', '[', ']',
  222. )
  223. def get_tokens_unprocessed(self, text):
  224. for index, token, value in RegexLexer.get_tokens_unprocessed(self, text):
  225. if token is Name:
  226. if value in self.KEYWORD:
  227. yield index, Keyword, value
  228. elif value in self.KEYWORD_OPERATOR:
  229. yield index, Operator.Word, value
  230. elif value in self.BUILTIN:
  231. yield index, Keyword, value
  232. elif value in self.BUILTIN_DECLARATION:
  233. yield index, Keyword.Declaration, value
  234. elif value in self.BUILTIN_NAMESPACE:
  235. yield index, Keyword.Namespace, value
  236. elif value in self.CONSTANT:
  237. yield index, Name.Constant, value
  238. elif value in self.PSEUDO_VAR:
  239. yield index, Name.Builtin.Pseudo, value
  240. else:
  241. yield index, token, value
  242. else:
  243. yield index, token, value
  244. def gen_elixir_sigil_rules():
  245. # all valid sigil terminators (excluding heredocs)
  246. terminators = [
  247. (r'\{', r'\}', '}', 'cb'),
  248. (r'\[', r'\]', r'\]', 'sb'),
  249. (r'\(', r'\)', ')', 'pa'),
  250. ('<', '>', '>', 'ab'),
  251. ('/', '/', '/', 'slas'),
  252. (r'\|', r'\|', '|', 'pipe'),
  253. ('"', '"', '"', 'quot'),
  254. ("'", "'", "'", 'apos'),
  255. ]
  256. # heredocs have slightly different rules
  257. triquotes = [(r'"""', 'triquot'), (r"'''", 'triapos')]
  258. token = String.Other
  259. states = {'sigils': []}
  260. for term, name in triquotes:
  261. states['sigils'] += [
  262. (r'(~[a-z])(%s)' % (term,), bygroups(token, String.Heredoc),
  263. (name + '-end', name + '-intp')),
  264. (r'(~[A-Z])(%s)' % (term,), bygroups(token, String.Heredoc),
  265. (name + '-end', name + '-no-intp')),
  266. ]
  267. states[name + '-end'] = [
  268. (r'[a-zA-Z]+', token, '#pop'),
  269. default('#pop'),
  270. ]
  271. states[name + '-intp'] = [
  272. (r'^\s*' + term, String.Heredoc, '#pop'),
  273. include('heredoc_interpol'),
  274. ]
  275. states[name + '-no-intp'] = [
  276. (r'^\s*' + term, String.Heredoc, '#pop'),
  277. include('heredoc_no_interpol'),
  278. ]
  279. for lterm, rterm, rterm_class, name in terminators:
  280. states['sigils'] += [
  281. (r'~[a-z]' + lterm, token, name + '-intp'),
  282. (r'~[A-Z]' + lterm, token, name + '-no-intp'),
  283. ]
  284. states[name + '-intp'] = \
  285. gen_elixir_sigstr_rules(rterm, rterm_class, token)
  286. states[name + '-no-intp'] = \
  287. gen_elixir_sigstr_rules(rterm, rterm_class, token, interpol=False)
  288. return states
  289. op3_re = "|".join(re.escape(s) for s in OPERATORS3)
  290. op2_re = "|".join(re.escape(s) for s in OPERATORS2)
  291. op1_re = "|".join(re.escape(s) for s in OPERATORS1)
  292. ops_re = r'(?:%s|%s|%s)' % (op3_re, op2_re, op1_re)
  293. punctuation_re = "|".join(re.escape(s) for s in PUNCTUATION)
  294. alnum = r'\w'
  295. name_re = r'(?:\.\.\.|[a-z_]%s*[!?]?)' % alnum
  296. modname_re = r'[A-Z]%(alnum)s*(?:\.[A-Z]%(alnum)s*)*' % {'alnum': alnum}
  297. complex_name_re = r'(?:%s|%s|%s)' % (name_re, modname_re, ops_re)
  298. special_atom_re = r'(?:\.\.\.|<<>>|%\{\}|%|\{\})'
  299. long_hex_char_re = r'(\\x\{)([\da-fA-F]+)(\})'
  300. hex_char_re = r'(\\x[\da-fA-F]{1,2})'
  301. escape_char_re = r'(\\[abdefnrstv])'
  302. tokens = {
  303. 'root': [
  304. (r'\s+', Text),
  305. (r'#.*$', Comment.Single),
  306. # Various kinds of characters
  307. (r'(\?)' + long_hex_char_re,
  308. bygroups(String.Char,
  309. String.Escape, Number.Hex, String.Escape)),
  310. (r'(\?)' + hex_char_re,
  311. bygroups(String.Char, String.Escape)),
  312. (r'(\?)' + escape_char_re,
  313. bygroups(String.Char, String.Escape)),
  314. (r'\?\\?.', String.Char),
  315. # '::' has to go before atoms
  316. (r':::', String.Symbol),
  317. (r'::', Operator),
  318. # atoms
  319. (r':' + special_atom_re, String.Symbol),
  320. (r':' + complex_name_re, String.Symbol),
  321. (r':"', String.Symbol, 'string_double_atom'),
  322. (r":'", String.Symbol, 'string_single_atom'),
  323. # [keywords: ...]
  324. (r'(%s|%s)(:)(?=\s|\n)' % (special_atom_re, complex_name_re),
  325. bygroups(String.Symbol, Punctuation)),
  326. # @attributes
  327. (r'@' + name_re, Name.Attribute),
  328. # identifiers
  329. (name_re, Name),
  330. (r'(%%?)(%s)' % (modname_re,), bygroups(Punctuation, Name.Class)),
  331. # operators and punctuation
  332. (op3_re, Operator),
  333. (op2_re, Operator),
  334. (punctuation_re, Punctuation),
  335. (r'&\d', Name.Entity), # anon func arguments
  336. (op1_re, Operator),
  337. # numbers
  338. (r'0b[01]+', Number.Bin),
  339. (r'0o[0-7]+', Number.Oct),
  340. (r'0x[\da-fA-F]+', Number.Hex),
  341. (r'\d(_?\d)*\.\d(_?\d)*([eE][-+]?\d(_?\d)*)?', Number.Float),
  342. (r'\d(_?\d)*', Number.Integer),
  343. # strings and heredocs
  344. (r'"""\s*', String.Heredoc, 'heredoc_double'),
  345. (r"'''\s*$", String.Heredoc, 'heredoc_single'),
  346. (r'"', String.Double, 'string_double'),
  347. (r"'", String.Single, 'string_single'),
  348. include('sigils'),
  349. (r'%\{', Punctuation, 'map_key'),
  350. (r'\{', Punctuation, 'tuple'),
  351. ],
  352. 'heredoc_double': [
  353. (r'^\s*"""', String.Heredoc, '#pop'),
  354. include('heredoc_interpol'),
  355. ],
  356. 'heredoc_single': [
  357. (r"^\s*'''", String.Heredoc, '#pop'),
  358. include('heredoc_interpol'),
  359. ],
  360. 'heredoc_interpol': [
  361. (r'[^#\\\n]+', String.Heredoc),
  362. include('escapes'),
  363. (r'\\.', String.Heredoc),
  364. (r'\n+', String.Heredoc),
  365. include('interpol'),
  366. ],
  367. 'heredoc_no_interpol': [
  368. (r'[^\\\n]+', String.Heredoc),
  369. (r'\\.', String.Heredoc),
  370. (r'\n+', String.Heredoc),
  371. ],
  372. 'escapes': [
  373. (long_hex_char_re,
  374. bygroups(String.Escape, Number.Hex, String.Escape)),
  375. (hex_char_re, String.Escape),
  376. (escape_char_re, String.Escape),
  377. ],
  378. 'interpol': [
  379. (r'#\{', String.Interpol, 'interpol_string'),
  380. ],
  381. 'interpol_string': [
  382. (r'\}', String.Interpol, "#pop"),
  383. include('root')
  384. ],
  385. 'map_key': [
  386. include('root'),
  387. (r':', Punctuation, 'map_val'),
  388. (r'=>', Punctuation, 'map_val'),
  389. (r'\}', Punctuation, '#pop'),
  390. ],
  391. 'map_val': [
  392. include('root'),
  393. (r',', Punctuation, '#pop'),
  394. (r'(?=\})', Punctuation, '#pop'),
  395. ],
  396. 'tuple': [
  397. include('root'),
  398. (r'\}', Punctuation, '#pop'),
  399. ],
  400. }
  401. tokens.update(gen_elixir_string_rules('double', '"', String.Double))
  402. tokens.update(gen_elixir_string_rules('single', "'", String.Single))
  403. tokens.update(gen_elixir_string_rules('double_atom', '"', String.Symbol))
  404. tokens.update(gen_elixir_string_rules('single_atom', "'", String.Symbol))
  405. tokens.update(gen_elixir_sigil_rules())
  406. class ElixirConsoleLexer(Lexer):
  407. """
  408. For Elixir interactive console (iex) output like:
  409. .. sourcecode:: iex
  410. iex> [head | tail] = [1,2,3]
  411. [1,2,3]
  412. iex> head
  413. 1
  414. iex> tail
  415. [2,3]
  416. iex> [head | tail]
  417. [1,2,3]
  418. iex> length [head | tail]
  419. 3
  420. .. versionadded:: 1.5
  421. """
  422. name = 'Elixir iex session'
  423. aliases = ['iex']
  424. mimetypes = ['text/x-elixir-shellsession']
  425. _prompt_re = re.compile(r'(iex|\.{3})((?:\([\w@_.]+\))?\d+|\(\d+\))?> ')
  426. def get_tokens_unprocessed(self, text):
  427. exlexer = ElixirLexer(**self.options)
  428. curcode = ''
  429. in_error = False
  430. insertions = []
  431. for match in line_re.finditer(text):
  432. line = match.group()
  433. if line.startswith('** '):
  434. in_error = True
  435. insertions.append((len(curcode),
  436. [(0, Generic.Error, line[:-1])]))
  437. curcode += line[-1:]
  438. else:
  439. m = self._prompt_re.match(line)
  440. if m is not None:
  441. in_error = False
  442. end = m.end()
  443. insertions.append((len(curcode),
  444. [(0, Generic.Prompt, line[:end])]))
  445. curcode += line[end:]
  446. else:
  447. if curcode:
  448. yield from do_insertions(
  449. insertions, exlexer.get_tokens_unprocessed(curcode))
  450. curcode = ''
  451. insertions = []
  452. token = Generic.Error if in_error else Generic.Output
  453. yield match.start(), token, line
  454. if curcode:
  455. yield from do_insertions(
  456. insertions, exlexer.get_tokens_unprocessed(curcode))