PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/app/server/vendor/rouge/lib/rouge/lexers/python.rb

https://gitlab.com/hwhelchel/sonic-pi
Ruby | 227 lines | 189 code | 33 blank | 5 comment | 6 complexity | e758ce091bdbd62b145f5edca1cbb84b MD5 | raw file
  1. # -*- coding: utf-8 -*- #
  2. module Rouge
  3. module Lexers
  4. class Python < RegexLexer
  5. desc "The Python programming language (python.org)"
  6. tag 'python'
  7. aliases 'py'
  8. filenames '*.py', '*.pyw', '*.sc', 'SConstruct', 'SConscript', '*.tac'
  9. mimetypes 'text/x-python', 'application/x-python'
  10. def self.analyze_text(text)
  11. return 1 if text.shebang?(/pythonw?(3|2(\.\d)?)?/)
  12. end
  13. def self.keywords
  14. @keywords ||= %w(
  15. assert break continue del elif else except exec
  16. finally for global if lambda pass print raise
  17. return try while yield as with
  18. )
  19. end
  20. def self.builtins
  21. @builtins ||= %w(
  22. __import__ abs all any apply basestring bin bool buffer
  23. bytearray bytes callable chr classmethod cmp coerce compile
  24. complex delattr dict dir divmod enumerate eval execfile exit
  25. file filter float frozenset getattr globals hasattr hash hex id
  26. input int intern isinstance issubclass iter len list locals
  27. long map max min next object oct open ord pow property range
  28. raw_input reduce reload repr reversed round set setattr slice
  29. sorted staticmethod str sum super tuple type unichr unicode
  30. vars xrange zip
  31. )
  32. end
  33. def self.builtins_pseudo
  34. @builtins_pseudo ||= %w(self None Ellipsis NotImplemented False True)
  35. end
  36. def self.exceptions
  37. @exceptions ||= %w(
  38. ArithmeticError AssertionError AttributeError
  39. BaseException DeprecationWarning EOFError EnvironmentError
  40. Exception FloatingPointError FutureWarning GeneratorExit IOError
  41. ImportError ImportWarning IndentationError IndexError KeyError
  42. KeyboardInterrupt LookupError MemoryError NameError
  43. NotImplemented NotImplementedError OSError OverflowError
  44. OverflowWarning PendingDeprecationWarning ReferenceError
  45. RuntimeError RuntimeWarning StandardError StopIteration
  46. SyntaxError SyntaxWarning SystemError SystemExit TabError
  47. TypeError UnboundLocalError UnicodeDecodeError
  48. UnicodeEncodeError UnicodeError UnicodeTranslateError
  49. UnicodeWarning UserWarning ValueError VMSError Warning
  50. WindowsError ZeroDivisionError
  51. )
  52. end
  53. identifier = /[a-z_][a-z0-9_]*/i
  54. dotted_identifier = /[a-z_.][a-z0-9_.]*/i
  55. state :root do
  56. rule /\n+/m, Text
  57. rule /^(:)(\s*)([ru]{,2}""".*?""")/mi do
  58. groups Punctuation, Text, Str::Doc
  59. end
  60. rule /[^\S\n]+/, Text
  61. rule /#.*$/, Comment
  62. rule /[\[\]{}:(),;]/, Punctuation
  63. rule /\\\n/, Text
  64. rule /\\/, Text
  65. rule /(in|is|and|or|not)\b/, Operator::Word
  66. rule /!=|==|<<|>>|[-~+\/*%=<>&^|.]/, Operator
  67. rule /(def)((?:\s|\\\s)+)/ do
  68. groups Keyword, Text
  69. push :funcname
  70. end
  71. rule /(class)((?:\s|\\\s)+)/ do
  72. groups Keyword, Text
  73. push :classname
  74. end
  75. rule /(from)((?:\s|\\\s)+)/ do
  76. groups Keyword::Namespace, Text
  77. push :fromimport
  78. end
  79. rule /(import)((?:\s|\\\s)+)/ do
  80. groups Keyword::Namespace, Text
  81. push :import
  82. end
  83. # TODO: not in python 3
  84. rule /`.*?`/, Str::Backtick
  85. rule /(?:r|ur|ru)"""/i, Str, :tdqs
  86. rule /(?:r|ur|ru)'''/i, Str, :tsqs
  87. rule /(?:r|ur|ru)"/i, Str, :dqs
  88. rule /(?:r|ur|ru)'/i, Str, :sqs
  89. rule /u?"""/i, Str, :escape_tdqs
  90. rule /u?'''/i, Str, :escape_tsqs
  91. rule /u?"/i, Str, :escape_dqs
  92. rule /u?'/i, Str, :escape_sqs
  93. rule /@#{dotted_identifier}/i, Name::Decorator
  94. # using negative lookbehind so we don't match property names
  95. rule /(?<!\.)#{identifier}/ do |m|
  96. if self.class.keywords.include? m[0]
  97. token Keyword
  98. elsif self.class.exceptions.include? m[0]
  99. token Name::Builtin
  100. elsif self.class.builtins.include? m[0]
  101. token Name::Builtin
  102. elsif self.class.builtins_pseudo.include? m[0]
  103. token Name::Builtin::Pseudo
  104. else
  105. token Name
  106. end
  107. end
  108. rule identifier, Name
  109. rule /(\d+\.\d*|\d*\.\d+)(e[+-]?[0-9]+)?/i, Num::Float
  110. rule /\d+e[+-]?[0-9]+/i, Num::Float
  111. rule /0[0-7]+/, Num::Oct
  112. rule /0x[a-f0-9]+/i, Num::Hex
  113. rule /\d+L/, Num::Integer::Long
  114. rule /\d+/, Num::Integer
  115. end
  116. state :funcname do
  117. rule identifier, Name::Function, :pop!
  118. end
  119. state :classname do
  120. rule identifier, Name::Class, :pop!
  121. end
  122. state :import do
  123. # non-line-terminating whitespace
  124. rule /(?:[ \t]|\\\n)+/, Text
  125. rule /as\b/, Keyword::Namespace
  126. rule /,/, Operator
  127. rule dotted_identifier, Name::Namespace
  128. rule(//) { pop! } # anything else -> go back
  129. end
  130. state :fromimport do
  131. # non-line-terminating whitespace
  132. rule /(?:[ \t]|\\\n)+/, Text
  133. rule /import\b/, Keyword::Namespace, :pop!
  134. rule dotted_identifier, Name::Namespace
  135. end
  136. state :strings do
  137. rule /%(\([a-z0-9_]+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?/i, Str::Interpol
  138. end
  139. state :strings_double do
  140. rule /[^\\"%\n]+/, Str
  141. mixin :strings
  142. end
  143. state :strings_single do
  144. rule /[^\\'%\n]+/, Str
  145. mixin :strings
  146. end
  147. state :nl do
  148. rule /\n/, Str
  149. end
  150. state :escape do
  151. rule %r(\\
  152. ( [\\abfnrtv"']
  153. | \n
  154. | N{.*?}
  155. | u[a-fA-F0-9]{4}
  156. | U[a-fA-F0-9]{8}
  157. | x[a-fA-F0-9]{2}
  158. | [0-7]{1,3}
  159. )
  160. )x, Str::Escape
  161. end
  162. state :dqs do
  163. rule /"/, Str, :pop!
  164. rule /\\\\|\\"|\\\n/, Str::Escape
  165. mixin :strings_double
  166. end
  167. state :sqs do
  168. rule /'/, Str, :pop!
  169. rule /\\\\|\\'|\\\n/, Str::Escape
  170. mixin :strings_single
  171. end
  172. state :tdqs do
  173. rule /"""/, Str, :pop!
  174. rule /"/, Str
  175. mixin :strings_double
  176. mixin :nl
  177. end
  178. state :tsqs do
  179. rule /'''/, Str, :pop!
  180. rule /'/, Str
  181. mixin :strings_single
  182. mixin :nl
  183. end
  184. %w(tdqs tsqs dqs sqs).each do |qtype|
  185. state :"escape_#{qtype}" do
  186. mixin :escape
  187. mixin :"#{qtype}"
  188. end
  189. end
  190. end
  191. end
  192. end