julia.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """
  2. pygments.lexers.julia
  3. ~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for the Julia language.
  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, do_insertions, \
  10. words, include
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation, Generic
  13. from pygments.util import shebang_matches
  14. from pygments.lexers._julia_builtins import OPERATORS_LIST, DOTTED_OPERATORS_LIST, \
  15. KEYWORD_LIST, BUILTIN_LIST, LITERAL_LIST
  16. __all__ = ['JuliaLexer', 'JuliaConsoleLexer']
  17. # see https://docs.julialang.org/en/v1/manual/variables/#Allowed-Variable-Names
  18. allowed_variable = \
  19. '(?:[a-zA-Z_\u00A1-\U0010ffff][a-zA-Z_0-9!\u00A1-\U0010ffff]*)'
  20. # see https://github.com/JuliaLang/julia/blob/master/src/flisp/julia_opsuffs.h
  21. operator_suffixes = r'[²³¹ʰʲʳʷʸˡˢˣᴬᴮᴰᴱᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᴿᵀᵁᵂᵃᵇᵈᵉᵍᵏᵐᵒᵖᵗᵘᵛᵝᵞᵟᵠᵡᵢᵣᵤᵥᵦᵧᵨᵩᵪᶜᶠᶥᶦᶫᶰᶸᶻᶿ′″‴‵‶‷⁗⁰ⁱ⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ⁿ₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎ₐₑₒₓₕₖₗₘₙₚₛₜⱼⱽ]*'
  22. class JuliaLexer(RegexLexer):
  23. """
  24. For `Julia <http://julialang.org/>`_ source code.
  25. .. versionadded:: 1.6
  26. """
  27. name = 'Julia'
  28. aliases = ['julia', 'jl']
  29. filenames = ['*.jl']
  30. mimetypes = ['text/x-julia', 'application/x-julia']
  31. flags = re.MULTILINE | re.UNICODE
  32. tokens = {
  33. 'root': [
  34. (r'\n', Text),
  35. (r'[^\S\n]+', Text),
  36. (r'#=', Comment.Multiline, "blockcomment"),
  37. (r'#.*$', Comment),
  38. (r'[\[\](),;]', Punctuation),
  39. # symbols
  40. # intercept range expressions first
  41. (r'(' + allowed_variable + r')(\s*)(:)(' + allowed_variable + ')',
  42. bygroups(Name, Text, Operator, Name)),
  43. # then match :name which does not follow closing brackets, digits, or the
  44. # ::, <:, and :> operators
  45. (r'(?<![\]):<>\d.])(:' + allowed_variable + ')', String.Symbol),
  46. # type assertions - excludes expressions like ::typeof(sin) and ::avec[1]
  47. (r'(?<=::)(\s*)(' + allowed_variable + r')\b(?![(\[])', bygroups(Text, Keyword.Type)),
  48. # type comparisons
  49. # - MyType <: A or MyType >: A
  50. ('(' + allowed_variable + r')(\s*)([<>]:)(\s*)(' + allowed_variable + r')\b(?![(\[])',
  51. bygroups(Keyword.Type, Text, Operator, Text, Keyword.Type)),
  52. # - <: B or >: B
  53. (r'([<>]:)(\s*)(' + allowed_variable + r')\b(?![(\[])',
  54. bygroups(Operator, Text, Keyword.Type)),
  55. # - A <: or A >:
  56. (r'\b(' + allowed_variable + r')(\s*)([<>]:)',
  57. bygroups(Keyword.Type, Text, Operator)),
  58. # operators
  59. # Suffixes aren't actually allowed on all operators, but we'll ignore that
  60. # since those cases are invalid Julia code.
  61. (words([*OPERATORS_LIST, *DOTTED_OPERATORS_LIST], suffix=operator_suffixes), Operator),
  62. (words(['.' + o for o in DOTTED_OPERATORS_LIST], suffix=operator_suffixes), Operator),
  63. (words(['...', '..']), Operator),
  64. # NOTE
  65. # Patterns below work only for definition sites and thus hardly reliable.
  66. #
  67. # functions
  68. # (r'(function)(\s+)(' + allowed_variable + ')',
  69. # bygroups(Keyword, Text, Name.Function)),
  70. # chars
  71. (r"'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,3}|\\u[a-fA-F0-9]{1,4}|"
  72. r"\\U[a-fA-F0-9]{1,6}|[^\\\'\n])'", String.Char),
  73. # try to match trailing transpose
  74. (r'(?<=[.\w)\]])(\'' + operator_suffixes + ')+', Operator),
  75. # raw strings
  76. (r'(raw)(""")', bygroups(String.Affix, String), 'tqrawstring'),
  77. (r'(raw)(")', bygroups(String.Affix, String), 'rawstring'),
  78. # regular expressions
  79. (r'(r)(""")', bygroups(String.Affix, String.Regex), 'tqregex'),
  80. (r'(r)(")', bygroups(String.Affix, String.Regex), 'regex'),
  81. # other strings
  82. (r'(' + allowed_variable + ')?(""")', bygroups(String.Affix, String), 'tqstring'),
  83. (r'(' + allowed_variable + ')?(")', bygroups(String.Affix, String), 'string'),
  84. # backticks
  85. (r'(' + allowed_variable + ')?(```)', bygroups(String.Affix, String.Backtick), 'tqcommand'),
  86. (r'(' + allowed_variable + ')?(`)', bygroups(String.Affix, String.Backtick), 'command'),
  87. # type names
  88. # - names that begin a curly expression
  89. ('(' + allowed_variable + r')(\{)',
  90. bygroups(Keyword.Type, Punctuation), 'curly'),
  91. # - names as part of bare 'where'
  92. (r'(where)(\s+)(' + allowed_variable + ')',
  93. bygroups(Keyword, Text, Keyword.Type)),
  94. # - curly expressions in general
  95. (r'(\{)', Punctuation, 'curly'),
  96. # - names as part of type declaration
  97. (r'(abstract[ \t]+type|primitive[ \t]+type|mutable[ \t]+struct|struct)([\s()]+)(' +
  98. allowed_variable + r')', bygroups(Keyword, Text, Keyword.Type)),
  99. # macros
  100. (r'@' + allowed_variable, Name.Decorator),
  101. (words([*OPERATORS_LIST, '..', '.', *DOTTED_OPERATORS_LIST],
  102. prefix='@', suffix=operator_suffixes), Name.Decorator),
  103. # keywords
  104. (words(KEYWORD_LIST, suffix=r'\b'), Keyword),
  105. # builtin types
  106. (words(BUILTIN_LIST, suffix=r'\b'), Keyword.Type),
  107. # builtin literals
  108. (words(LITERAL_LIST, suffix=r'\b'), Name.Builtin),
  109. # names
  110. (allowed_variable, Name),
  111. # numbers
  112. (r'(\d+((_\d+)+)?\.(?!\.)(\d+((_\d+)+)?)?|\.\d+((_\d+)+)?)([eEf][+-]?[0-9]+)?', Number.Float),
  113. (r'\d+((_\d+)+)?[eEf][+-]?[0-9]+', Number.Float),
  114. (r'0x[a-fA-F0-9]+((_[a-fA-F0-9]+)+)?(\.([a-fA-F0-9]+((_[a-fA-F0-9]+)+)?)?)?p[+-]?\d+', Number.Float),
  115. (r'0b[01]+((_[01]+)+)?', Number.Bin),
  116. (r'0o[0-7]+((_[0-7]+)+)?', Number.Oct),
  117. (r'0x[a-fA-F0-9]+((_[a-fA-F0-9]+)+)?', Number.Hex),
  118. (r'\d+((_\d+)+)?', Number.Integer),
  119. # single dot operator matched last to permit e.g. ".1" as a float
  120. (words(['.']), Operator),
  121. ],
  122. "blockcomment": [
  123. (r'[^=#]', Comment.Multiline),
  124. (r'#=', Comment.Multiline, '#push'),
  125. (r'=#', Comment.Multiline, '#pop'),
  126. (r'[=#]', Comment.Multiline),
  127. ],
  128. 'curly': [
  129. (r'\{', Punctuation, '#push'),
  130. (r'\}', Punctuation, '#pop'),
  131. (allowed_variable, Keyword.Type),
  132. include('root'),
  133. ],
  134. 'tqrawstring': [
  135. (r'"""', String, '#pop'),
  136. (r'([^"]|"[^"][^"])+', String),
  137. ],
  138. 'rawstring': [
  139. (r'"', String, '#pop'),
  140. (r'\\"', String.Escape),
  141. (r'([^"\\]|\\[^"])+', String),
  142. ],
  143. # Interpolation is defined as "$" followed by the shortest full expression, which is
  144. # something we can't parse.
  145. # Include the most common cases here: $word, and $(paren'd expr).
  146. 'interp': [
  147. (r'\$' + allowed_variable, String.Interpol),
  148. (r'(\$)(\()', bygroups(String.Interpol, Punctuation), 'in-intp'),
  149. ],
  150. 'in-intp': [
  151. (r'\(', Punctuation, '#push'),
  152. (r'\)', Punctuation, '#pop'),
  153. include('root'),
  154. ],
  155. 'string': [
  156. (r'(")(' + allowed_variable + r'|\d+)?', bygroups(String, String.Affix), '#pop'),
  157. # FIXME: This escape pattern is not perfect.
  158. (r'\\([\\"\'$nrbtfav]|(x|u|U)[a-fA-F0-9]+|\d+)', String.Escape),
  159. include('interp'),
  160. # @printf and @sprintf formats
  161. (r'%[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?[hlL]?[E-GXc-giorsux%]',
  162. String.Interpol),
  163. (r'[^"$%\\]+', String),
  164. (r'.', String),
  165. ],
  166. 'tqstring': [
  167. (r'(""")(' + allowed_variable + r'|\d+)?', bygroups(String, String.Affix), '#pop'),
  168. (r'\\([\\"\'$nrbtfav]|(x|u|U)[a-fA-F0-9]+|\d+)', String.Escape),
  169. include('interp'),
  170. (r'[^"$%\\]+', String),
  171. (r'.', String),
  172. ],
  173. 'regex': [
  174. (r'(")([imsxa]*)?', bygroups(String.Regex, String.Affix), '#pop'),
  175. (r'\\"', String.Regex),
  176. (r'[^\\"]+', String.Regex),
  177. ],
  178. 'tqregex': [
  179. (r'(""")([imsxa]*)?', bygroups(String.Regex, String.Affix), '#pop'),
  180. (r'[^"]+', String.Regex),
  181. ],
  182. 'command': [
  183. (r'(`)(' + allowed_variable + r'|\d+)?', bygroups(String.Backtick, String.Affix), '#pop'),
  184. (r'\\[`$]', String.Escape),
  185. include('interp'),
  186. (r'[^\\`$]+', String.Backtick),
  187. (r'.', String.Backtick),
  188. ],
  189. 'tqcommand': [
  190. (r'(```)(' + allowed_variable + r'|\d+)?', bygroups(String.Backtick, String.Affix), '#pop'),
  191. (r'\\\$', String.Escape),
  192. include('interp'),
  193. (r'[^\\`$]+', String.Backtick),
  194. (r'.', String.Backtick),
  195. ],
  196. }
  197. def analyse_text(text):
  198. return shebang_matches(text, r'julia')
  199. class JuliaConsoleLexer(Lexer):
  200. """
  201. For Julia console sessions. Modeled after MatlabSessionLexer.
  202. .. versionadded:: 1.6
  203. """
  204. name = 'Julia console'
  205. aliases = ['jlcon', 'julia-repl']
  206. def get_tokens_unprocessed(self, text):
  207. jllexer = JuliaLexer(**self.options)
  208. start = 0
  209. curcode = ''
  210. insertions = []
  211. output = False
  212. error = False
  213. for line in text.splitlines(True):
  214. if line.startswith('julia>'):
  215. insertions.append((len(curcode), [(0, Generic.Prompt, line[:6])]))
  216. curcode += line[6:]
  217. output = False
  218. error = False
  219. elif line.startswith('help?>') or line.startswith('shell>'):
  220. yield start, Generic.Prompt, line[:6]
  221. yield start + 6, Text, line[6:]
  222. output = False
  223. error = False
  224. elif line.startswith(' ') and not output:
  225. insertions.append((len(curcode), [(0, Text, line[:6])]))
  226. curcode += line[6:]
  227. else:
  228. if curcode:
  229. yield from do_insertions(
  230. insertions, jllexer.get_tokens_unprocessed(curcode))
  231. curcode = ''
  232. insertions = []
  233. if line.startswith('ERROR: ') or error:
  234. yield start, Generic.Error, line
  235. error = True
  236. else:
  237. yield start, Generic.Output, line
  238. output = True
  239. start += len(line)
  240. if curcode:
  241. yield from do_insertions(
  242. insertions, jllexer.get_tokens_unprocessed(curcode))