erlang.py 19 KB

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