erlang.py 19 KB

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