perl.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. """
  2. pygments.lexers.perl
  3. ~~~~~~~~~~~~~~~~~~~~
  4. Lexers for Perl, Raku and related languages.
  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 RegexLexer, ExtendedRegexLexer, include, bygroups, \
  10. using, this, default, words
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation
  13. from pygments.util import shebang_matches
  14. __all__ = ['PerlLexer', 'Perl6Lexer']
  15. class PerlLexer(RegexLexer):
  16. """
  17. For `Perl <https://www.perl.org>`_ source code.
  18. """
  19. name = 'Perl'
  20. aliases = ['perl', 'pl']
  21. filenames = ['*.pl', '*.pm', '*.t', '*.perl']
  22. mimetypes = ['text/x-perl', 'application/x-perl']
  23. flags = re.DOTALL | re.MULTILINE
  24. # TODO: give this to a perl guy who knows how to parse perl...
  25. tokens = {
  26. 'balanced-regex': [
  27. (r'/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*', String.Regex, '#pop'),
  28. (r'!(\\\\|\\[^\\]|[^\\!])*![egimosx]*', String.Regex, '#pop'),
  29. (r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'),
  30. (r'\{(\\\\|\\[^\\]|[^\\}])*\}[egimosx]*', String.Regex, '#pop'),
  31. (r'<(\\\\|\\[^\\]|[^\\>])*>[egimosx]*', String.Regex, '#pop'),
  32. (r'\[(\\\\|\\[^\\]|[^\\\]])*\][egimosx]*', String.Regex, '#pop'),
  33. (r'\((\\\\|\\[^\\]|[^\\)])*\)[egimosx]*', String.Regex, '#pop'),
  34. (r'@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*', String.Regex, '#pop'),
  35. (r'%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*', String.Regex, '#pop'),
  36. (r'\$(\\\\|\\[^\\]|[^\\$])*\$[egimosx]*', String.Regex, '#pop'),
  37. ],
  38. 'root': [
  39. (r'\A\#!.+?$', Comment.Hashbang),
  40. (r'\#.*?$', Comment.Single),
  41. (r'^=[a-zA-Z0-9]+\s+.*?\n=cut', Comment.Multiline),
  42. (words((
  43. 'case', 'continue', 'do', 'else', 'elsif', 'for', 'foreach',
  44. 'if', 'last', 'my', 'next', 'our', 'redo', 'reset', 'then',
  45. 'unless', 'until', 'while', 'print', 'new', 'BEGIN',
  46. 'CHECK', 'INIT', 'END', 'return'), suffix=r'\b'),
  47. Keyword),
  48. (r'(format)(\s+)(\w+)(\s*)(=)(\s*\n)',
  49. bygroups(Keyword, Text, Name, Text, Punctuation, Text), 'format'),
  50. (r'(eq|lt|gt|le|ge|ne|not|and|or|cmp)\b', Operator.Word),
  51. # common delimiters
  52. (r's/(\\\\|\\[^\\]|[^\\/])*/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*',
  53. String.Regex),
  54. (r's!(\\\\|\\!|[^!])*!(\\\\|\\!|[^!])*![egimosx]*', String.Regex),
  55. (r's\\(\\\\|[^\\])*\\(\\\\|[^\\])*\\[egimosx]*', String.Regex),
  56. (r's@(\\\\|\\[^\\]|[^\\@])*@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*',
  57. String.Regex),
  58. (r's%(\\\\|\\[^\\]|[^\\%])*%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*',
  59. String.Regex),
  60. # balanced delimiters
  61. (r's\{(\\\\|\\[^\\]|[^\\}])*\}\s*', String.Regex, 'balanced-regex'),
  62. (r's<(\\\\|\\[^\\]|[^\\>])*>\s*', String.Regex, 'balanced-regex'),
  63. (r's\[(\\\\|\\[^\\]|[^\\\]])*\]\s*', String.Regex,
  64. 'balanced-regex'),
  65. (r's\((\\\\|\\[^\\]|[^\\)])*\)\s*', String.Regex,
  66. 'balanced-regex'),
  67. (r'm?/(\\\\|\\[^\\]|[^\\/\n])*/[gcimosx]*', String.Regex),
  68. (r'm(?=[/!\\{<\[(@%$])', String.Regex, 'balanced-regex'),
  69. (r'((?<==~)|(?<=\())\s*/(\\\\|\\[^\\]|[^\\/])*/[gcimosx]*',
  70. String.Regex),
  71. (r'\s+', Text),
  72. (words((
  73. 'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller', 'chdir',
  74. 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'close', 'closedir', 'connect',
  75. 'continue', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined', 'delete', 'die',
  76. 'dump', 'each', 'endgrent', 'endhostent', 'endnetent', 'endprotoent',
  77. 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists', 'exit', 'exp', 'fcntl',
  78. 'fileno', 'flock', 'fork', 'format', 'formline', 'getc', 'getgrent', 'getgrgid',
  79. 'getgrnam', 'gethostbyaddr', 'gethostbyname', 'gethostent', 'getlogin',
  80. 'getnetbyaddr', 'getnetbyname', 'getnetent', 'getpeername', 'getpgrp',
  81. 'getppid', 'getpriority', 'getprotobyname', 'getprotobynumber',
  82. 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid', 'getservbyname',
  83. 'getservbyport', 'getservent', 'getsockname', 'getsockopt', 'glob', 'gmtime',
  84. 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl', 'join', 'keys', 'kill', 'last',
  85. 'lc', 'lcfirst', 'length', 'link', 'listen', 'local', 'localtime', 'log', 'lstat',
  86. 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'my', 'next', 'oct', 'open',
  87. 'opendir', 'ord', 'our', 'pack', 'pipe', 'pop', 'pos', 'printf',
  88. 'prototype', 'push', 'quotemeta', 'rand', 'read', 'readdir',
  89. 'readline', 'readlink', 'readpipe', 'recv', 'redo', 'ref', 'rename',
  90. 'reverse', 'rewinddir', 'rindex', 'rmdir', 'scalar', 'seek', 'seekdir',
  91. 'select', 'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent',
  92. 'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent',
  93. 'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown',
  94. 'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf', 'sqrt',
  95. 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysopen', 'sysread',
  96. 'sysseek', 'system', 'syswrite', 'tell', 'telldir', 'tie', 'tied', 'time', 'times', 'tr',
  97. 'truncate', 'uc', 'ucfirst', 'umask', 'undef', 'unlink', 'unpack', 'unshift', 'untie',
  98. 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray', 'warn', 'write'), suffix=r'\b'),
  99. Name.Builtin),
  100. (r'((__(DATA|DIE|WARN)__)|(STD(IN|OUT|ERR)))\b', Name.Builtin.Pseudo),
  101. (r'(<<)([\'"]?)([a-zA-Z_]\w*)(\2;?\n.*?\n)(\3)(\n)',
  102. bygroups(String, String, String.Delimiter, String, String.Delimiter, Text)),
  103. (r'__END__', Comment.Preproc, 'end-part'),
  104. (r'\$\^[ADEFHILMOPSTWX]', Name.Variable.Global),
  105. (r"\$[\\\"\[\]'&`+*.,;=%~?@$!<>(^|/-](?!\w)", Name.Variable.Global),
  106. (r'[$@%#]+', Name.Variable, 'varname'),
  107. (r'0_?[0-7]+(_[0-7]+)*', Number.Oct),
  108. (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex),
  109. (r'0b[01]+(_[01]+)*', Number.Bin),
  110. (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?',
  111. Number.Float),
  112. (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float),
  113. (r'\d+(_\d+)*', Number.Integer),
  114. (r"'(\\\\|\\[^\\]|[^'\\])*'", String),
  115. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  116. (r'`(\\\\|\\[^\\]|[^`\\])*`', String.Backtick),
  117. (r'<([^\s>]+)>', String.Regex),
  118. (r'(q|qq|qw|qr|qx)\{', String.Other, 'cb-string'),
  119. (r'(q|qq|qw|qr|qx)\(', String.Other, 'rb-string'),
  120. (r'(q|qq|qw|qr|qx)\[', String.Other, 'sb-string'),
  121. (r'(q|qq|qw|qr|qx)\<', String.Other, 'lt-string'),
  122. (r'(q|qq|qw|qr|qx)([\W_])(.|\n)*?\2', String.Other),
  123. (r'(package)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)',
  124. bygroups(Keyword, Text, Name.Namespace)),
  125. (r'(use|require|no)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)',
  126. bygroups(Keyword, Text, Name.Namespace)),
  127. (r'(sub)(\s+)', bygroups(Keyword, Text), 'funcname'),
  128. (words((
  129. 'no', 'package', 'require', 'use'), suffix=r'\b'),
  130. Keyword),
  131. (r'(\[\]|\*\*|::|<<|>>|>=|<=>|<=|={3}|!=|=~|'
  132. r'!~|&&?|\|\||\.{1,3})', Operator),
  133. (r'[-+/*%=<>&^|!\\~]=?', Operator),
  134. (r'[()\[\]:;,<>/?{}]', Punctuation), # yes, there's no shortage
  135. # of punctuation in Perl!
  136. (r'(?=\w)', Name, 'name'),
  137. ],
  138. 'format': [
  139. (r'\.\n', String.Interpol, '#pop'),
  140. (r'[^\n]*\n', String.Interpol),
  141. ],
  142. 'varname': [
  143. (r'\s+', Text),
  144. (r'\{', Punctuation, '#pop'), # hash syntax?
  145. (r'\)|,', Punctuation, '#pop'), # argument specifier
  146. (r'\w+::', Name.Namespace),
  147. (r'[\w:]+', Name.Variable, '#pop'),
  148. ],
  149. 'name': [
  150. (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*(::)?(?=\s*->)', Name.Namespace, '#pop'),
  151. (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*::', Name.Namespace, '#pop'),
  152. (r'[\w:]+', Name, '#pop'),
  153. (r'[A-Z_]+(?=\W)', Name.Constant, '#pop'),
  154. (r'(?=\W)', Text, '#pop'),
  155. ],
  156. 'funcname': [
  157. (r'[a-zA-Z_]\w*[!?]?', Name.Function),
  158. (r'\s+', Text),
  159. # argument declaration
  160. (r'(\([$@%]*\))(\s*)', bygroups(Punctuation, Text)),
  161. (r';', Punctuation, '#pop'),
  162. (r'.*?\{', Punctuation, '#pop'),
  163. ],
  164. 'cb-string': [
  165. (r'\\[{}\\]', String.Other),
  166. (r'\\', String.Other),
  167. (r'\{', String.Other, 'cb-string'),
  168. (r'\}', String.Other, '#pop'),
  169. (r'[^{}\\]+', String.Other)
  170. ],
  171. 'rb-string': [
  172. (r'\\[()\\]', String.Other),
  173. (r'\\', String.Other),
  174. (r'\(', String.Other, 'rb-string'),
  175. (r'\)', String.Other, '#pop'),
  176. (r'[^()]+', String.Other)
  177. ],
  178. 'sb-string': [
  179. (r'\\[\[\]\\]', String.Other),
  180. (r'\\', String.Other),
  181. (r'\[', String.Other, 'sb-string'),
  182. (r'\]', String.Other, '#pop'),
  183. (r'[^\[\]]+', String.Other)
  184. ],
  185. 'lt-string': [
  186. (r'\\[<>\\]', String.Other),
  187. (r'\\', String.Other),
  188. (r'\<', String.Other, 'lt-string'),
  189. (r'\>', String.Other, '#pop'),
  190. (r'[^<>]+', String.Other)
  191. ],
  192. 'end-part': [
  193. (r'.+', Comment.Preproc, '#pop')
  194. ]
  195. }
  196. def analyse_text(text):
  197. if shebang_matches(text, r'perl'):
  198. return True
  199. result = 0
  200. if re.search(r'(?:my|our)\s+[$@%(]', text):
  201. result += 0.9
  202. if ':=' in text:
  203. # := is not valid Perl, but it appears in unicon, so we should
  204. # become less confident if we think we found Perl with :=
  205. result /= 2
  206. return result
  207. class Perl6Lexer(ExtendedRegexLexer):
  208. """
  209. For `Raku <https://www.raku.org>`_ (a.k.a. Perl 6) source code.
  210. .. versionadded:: 2.0
  211. """
  212. name = 'Perl6'
  213. aliases = ['perl6', 'pl6', 'raku']
  214. filenames = ['*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6',
  215. '*.6pm', '*.p6m', '*.pm6', '*.t', '*.raku', '*.rakumod',
  216. '*.rakutest', '*.rakudoc']
  217. mimetypes = ['text/x-perl6', 'application/x-perl6']
  218. flags = re.MULTILINE | re.DOTALL | re.UNICODE
  219. PERL6_IDENTIFIER_RANGE = r"['\w:-]"
  220. PERL6_KEYWORDS = (
  221. #Phasers
  222. 'BEGIN','CATCH','CHECK','CLOSE','CONTROL','DOC','END','ENTER','FIRST',
  223. 'INIT','KEEP','LAST','LEAVE','NEXT','POST','PRE','QUIT','UNDO',
  224. #Keywords
  225. 'anon','augment','but','class','constant','default','does','else',
  226. 'elsif','enum','for','gather','given','grammar','has','if','import',
  227. 'is','let','loop','made','make','method','module','multi','my','need',
  228. 'orwith','our','proceed','proto','repeat','require','return',
  229. 'return-rw','returns','role','rule','state','sub','submethod','subset',
  230. 'succeed','supersede','token','try','unit','unless','until','use',
  231. 'when','while','with','without',
  232. #Traits
  233. 'export','native','repr','required','rw','symbol',
  234. )
  235. PERL6_BUILTINS = (
  236. 'ACCEPTS','abs','abs2rel','absolute','accept','accessed','acos',
  237. 'acosec','acosech','acosh','acotan','acotanh','acquire','act','action',
  238. 'actions','add','add_attribute','add_enum_value','add_fallback',
  239. 'add_method','add_parent','add_private_method','add_role','add_trustee',
  240. 'adverb','after','all','allocate','allof','allowed','alternative-names',
  241. 'annotations','antipair','antipairs','any','anyof','app_lifetime',
  242. 'append','arch','archname','args','arity','Array','asec','asech','asin',
  243. 'asinh','ASSIGN-KEY','ASSIGN-POS','assuming','ast','at','atan','atan2',
  244. 'atanh','AT-KEY','atomic-assign','atomic-dec-fetch','atomic-fetch',
  245. 'atomic-fetch-add','atomic-fetch-dec','atomic-fetch-inc',
  246. 'atomic-fetch-sub','atomic-inc-fetch','AT-POS','attributes','auth',
  247. 'await','backtrace','Bag','BagHash','bail-out','base','basename',
  248. 'base-repeating','batch','BIND-KEY','BIND-POS','bind-stderr',
  249. 'bind-stdin','bind-stdout','bind-udp','bits','bless','block','Bool',
  250. 'bool-only','bounds','break','Bridge','broken','BUILD','build-date',
  251. 'bytes','cache','callframe','calling-package','CALL-ME','callsame',
  252. 'callwith','can','cancel','candidates','cando','can-ok','canonpath',
  253. 'caps','caption','Capture','cas','catdir','categorize','categorize-list',
  254. 'catfile','catpath','cause','ceiling','cglobal','changed','Channel',
  255. 'chars','chdir','child','child-name','child-typename','chmod','chomp',
  256. 'chop','chr','chrs','chunks','cis','classify','classify-list','cleanup',
  257. 'clone','close','closed','close-stdin','cmp-ok','code','codes','collate',
  258. 'column','comb','combinations','command','comment','compiler','Complex',
  259. 'compose','compose_type','composer','condition','config',
  260. 'configure_destroy','configure_type_checking','conj','connect',
  261. 'constraints','construct','contains','contents','copy','cos','cosec',
  262. 'cosech','cosh','cotan','cotanh','count','count-only','cpu-cores',
  263. 'cpu-usage','CREATE','create_type','cross','cue','curdir','curupdir','d',
  264. 'Date','DateTime','day','daycount','day-of-month','day-of-week',
  265. 'day-of-year','days-in-month','declaration','decode','decoder','deepmap',
  266. 'default','defined','DEFINITE','delayed','DELETE-KEY','DELETE-POS',
  267. 'denominator','desc','DESTROY','destroyers','devnull','diag',
  268. 'did-you-mean','die','dies-ok','dir','dirname','dir-sep','DISTROnames',
  269. 'do','does','does-ok','done','done-testing','duckmap','dynamic','e',
  270. 'eager','earlier','elems','emit','enclosing','encode','encoder',
  271. 'encoding','end','ends-with','enum_from_value','enum_value_list',
  272. 'enum_values','enums','eof','EVAL','eval-dies-ok','EVALFILE',
  273. 'eval-lives-ok','exception','excludes-max','excludes-min','EXISTS-KEY',
  274. 'EXISTS-POS','exit','exitcode','exp','expected','explicitly-manage',
  275. 'expmod','extension','f','fail','fails-like','fc','feature','file',
  276. 'filename','find_method','find_method_qualified','finish','first','flat',
  277. 'flatmap','flip','floor','flunk','flush','fmt','format','formatter',
  278. 'freeze','from','from-list','from-loop','from-posix','full',
  279. 'full-barrier','get','get_value','getc','gist','got','grab','grabpairs',
  280. 'grep','handle','handled','handles','hardware','has_accessor','Hash',
  281. 'head','headers','hh-mm-ss','hidden','hides','hour','how','hyper','id',
  282. 'illegal','im','in','indent','index','indices','indir','infinite',
  283. 'infix','infix:<+>','infix:<->','install_method_cache','Instant',
  284. 'instead','Int','int-bounds','interval','in-timezone','invalid-str',
  285. 'invert','invocant','IO','IO::Notification.watch-path','is_trusted',
  286. 'is_type','isa','is-absolute','isa-ok','is-approx','is-deeply',
  287. 'is-hidden','is-initial-thread','is-int','is-lazy','is-leap-year',
  288. 'isNaN','isnt','is-prime','is-relative','is-routine','is-setting',
  289. 'is-win','item','iterator','join','keep','kept','KERNELnames','key',
  290. 'keyof','keys','kill','kv','kxxv','l','lang','last','lastcall','later',
  291. 'lazy','lc','leading','level','like','line','lines','link','List',
  292. 'listen','live','lives-ok','local','lock','log','log10','lookup','lsb',
  293. 'made','MAIN','make','Map','match','max','maxpairs','merge','message',
  294. 'method','method_table','methods','migrate','min','minmax','minpairs',
  295. 'minute','misplaced','Mix','MixHash','mkdir','mode','modified','month',
  296. 'move','mro','msb','multi','multiness','my','name','named','named_names',
  297. 'narrow','nativecast','native-descriptor','nativesizeof','new','new_type',
  298. 'new-from-daycount','new-from-pairs','next','nextcallee','next-handle',
  299. 'nextsame','nextwith','NFC','NFD','NFKC','NFKD','nl-in','nl-out',
  300. 'nodemap','nok','none','norm','not','note','now','nude','Num',
  301. 'numerator','Numeric','of','offset','offset-in-hours','offset-in-minutes',
  302. 'ok','old','on-close','one','on-switch','open','opened','operation',
  303. 'optional','ord','ords','orig','os-error','osname','out-buffer','pack',
  304. 'package','package-kind','package-name','packages','pair','pairs',
  305. 'pairup','parameter','params','parent','parent-name','parents','parse',
  306. 'parse-base','parsefile','parse-names','parts','pass','path','path-sep',
  307. 'payload','peer-host','peer-port','periods','perl','permutations','phaser',
  308. 'pick','pickpairs','pid','placeholder','plan','plus','polar','poll',
  309. 'polymod','pop','pos','positional','posix','postfix','postmatch',
  310. 'precomp-ext','precomp-target','pred','prefix','prematch','prepend',
  311. 'print','printf','print-nl','print-to','private','private_method_table',
  312. 'proc','produce','Promise','prompt','protect','pull-one','push',
  313. 'push-all','push-at-least','push-exactly','push-until-lazy','put',
  314. 'qualifier-type','quit','r','race','radix','rand','range','Rat','raw',
  315. 're','read','readchars','readonly','ready','Real','reallocate','reals',
  316. 'reason','rebless','receive','recv','redispatcher','redo','reduce',
  317. 'rel2abs','relative','release','rename','repeated','replacement',
  318. 'report','reserved','resolve','restore','result','resume','rethrow',
  319. 'reverse','right','rindex','rmdir','role','roles_to_compose','rolish',
  320. 'roll','rootdir','roots','rotate','rotor','round','roundrobin',
  321. 'routine-type','run','rwx','s','samecase','samemark','samewith','say',
  322. 'schedule-on','scheduler','scope','sec','sech','second','seek','self',
  323. 'send','Set','set_hidden','set_name','set_package','set_rw','set_value',
  324. 'SetHash','set-instruments','setup_finalization','shape','share','shell',
  325. 'shift','sibling','sigil','sign','signal','signals','signature','sin',
  326. 'sinh','sink','sink-all','skip','skip-at-least','skip-at-least-pull-one',
  327. 'skip-one','skip-rest','sleep','sleep-timer','sleep-until','Slip','slurp',
  328. 'slurp-rest','slurpy','snap','snapper','so','socket-host','socket-port',
  329. 'sort','source','source-package','spawn','SPEC','splice','split',
  330. 'splitdir','splitpath','sprintf','spurt','sqrt','squish','srand','stable',
  331. 'start','started','starts-with','status','stderr','stdout','Str',
  332. 'sub_signature','subbuf','subbuf-rw','subname','subparse','subst',
  333. 'subst-mutate','substr','substr-eq','substr-rw','subtest','succ','sum',
  334. 'Supply','symlink','t','tail','take','take-rw','tan','tanh','tap',
  335. 'target','target-name','tc','tclc','tell','then','throttle','throw',
  336. 'throws-like','timezone','tmpdir','to','today','todo','toggle','to-posix',
  337. 'total','trailing','trans','tree','trim','trim-leading','trim-trailing',
  338. 'truncate','truncated-to','trusts','try_acquire','trying','twigil','type',
  339. 'type_captures','typename','uc','udp','uncaught_handler','unimatch',
  340. 'uniname','uninames','uniparse','uniprop','uniprops','unique','unival',
  341. 'univals','unlike','unlink','unlock','unpack','unpolar','unshift',
  342. 'unwrap','updir','USAGE','use-ok','utc','val','value','values','VAR',
  343. 'variable','verbose-config','version','VMnames','volume','vow','w','wait',
  344. 'warn','watch','watch-path','week','weekday-of-month','week-number',
  345. 'week-year','WHAT','when','WHERE','WHEREFORE','WHICH','WHO',
  346. 'whole-second','WHY','wordcase','words','workaround','wrap','write',
  347. 'write-to','x','yada','year','yield','yyyy-mm-dd','z','zip','zip-latest',
  348. )
  349. PERL6_BUILTIN_CLASSES = (
  350. #Booleans
  351. 'False','True',
  352. #Classes
  353. 'Any','Array','Associative','AST','atomicint','Attribute','Backtrace',
  354. 'Backtrace::Frame','Bag','Baggy','BagHash','Blob','Block','Bool','Buf',
  355. 'Callable','CallFrame','Cancellation','Capture','CArray','Channel','Code',
  356. 'compiler','Complex','ComplexStr','Cool','CurrentThreadScheduler',
  357. 'Cursor','Date','Dateish','DateTime','Distro','Duration','Encoding',
  358. 'Exception','Failure','FatRat','Grammar','Hash','HyperWhatever','Instant',
  359. 'Int','int16','int32','int64','int8','IntStr','IO','IO::ArgFiles',
  360. 'IO::CatHandle','IO::Handle','IO::Notification','IO::Path',
  361. 'IO::Path::Cygwin','IO::Path::QNX','IO::Path::Unix','IO::Path::Win32',
  362. 'IO::Pipe','IO::Socket','IO::Socket::Async','IO::Socket::INET','IO::Spec',
  363. 'IO::Spec::Cygwin','IO::Spec::QNX','IO::Spec::Unix','IO::Spec::Win32',
  364. 'IO::Special','Iterable','Iterator','Junction','Kernel','Label','List',
  365. 'Lock','Lock::Async','long','longlong','Macro','Map','Match',
  366. 'Metamodel::AttributeContainer','Metamodel::C3MRO','Metamodel::ClassHOW',
  367. 'Metamodel::EnumHOW','Metamodel::Finalization','Metamodel::MethodContainer',
  368. 'Metamodel::MROBasedMethodDispatch','Metamodel::MultipleInheritance',
  369. 'Metamodel::Naming','Metamodel::Primitives','Metamodel::PrivateMethodContainer',
  370. 'Metamodel::RoleContainer','Metamodel::Trusting','Method','Mix','MixHash',
  371. 'Mixy','Mu','NFC','NFD','NFKC','NFKD','Nil','Num','num32','num64',
  372. 'Numeric','NumStr','ObjAt','Order','Pair','Parameter','Perl','Pod::Block',
  373. 'Pod::Block::Code','Pod::Block::Comment','Pod::Block::Declarator',
  374. 'Pod::Block::Named','Pod::Block::Para','Pod::Block::Table','Pod::Heading',
  375. 'Pod::Item','Pointer','Positional','PositionalBindFailover','Proc',
  376. 'Proc::Async','Promise','Proxy','PseudoStash','QuantHash','Range','Rat',
  377. 'Rational','RatStr','Real','Regex','Routine','Scalar','Scheduler',
  378. 'Semaphore','Seq','Set','SetHash','Setty','Signature','size_t','Slip',
  379. 'Stash','Str','StrDistance','Stringy','Sub','Submethod','Supplier',
  380. 'Supplier::Preserving','Supply','Systemic','Tap','Telemetry',
  381. 'Telemetry::Instrument::Thread','Telemetry::Instrument::Usage',
  382. 'Telemetry::Period','Telemetry::Sampler','Thread','ThreadPoolScheduler',
  383. 'UInt','uint16','uint32','uint64','uint8','Uni','utf8','Variable',
  384. 'Version','VM','Whatever','WhateverCode','WrapHandle'
  385. )
  386. PERL6_OPERATORS = (
  387. 'X', 'Z', 'after', 'also', 'and', 'andthen', 'before', 'cmp', 'div',
  388. 'eq', 'eqv', 'extra', 'ff', 'fff', 'ge', 'gt', 'le', 'leg', 'lt', 'm',
  389. 'mm', 'mod', 'ne', 'or', 'orelse', 'rx', 's', 'tr', 'x', 'xor', 'xx',
  390. '++', '--', '**', '!', '+', '-', '~', '?', '|', '||', '+^', '~^', '?^',
  391. '^', '*', '/', '%', '%%', '+&', '+<', '+>', '~&', '~<', '~>', '?&',
  392. 'gcd', 'lcm', '+', '-', '+|', '+^', '~|', '~^', '?|', '?^',
  393. '~', '&', '^', 'but', 'does', '<=>', '..', '..^', '^..', '^..^',
  394. '!=', '==', '<', '<=', '>', '>=', '~~', '===', '!eqv',
  395. '&&', '||', '^^', '//', 'min', 'max', '??', '!!', 'ff', 'fff', 'so',
  396. 'not', '<==', '==>', '<<==', '==>>','unicmp',
  397. )
  398. # Perl 6 has a *lot* of possible bracketing characters
  399. # this list was lifted from STD.pm6 (https://github.com/perl6/std)
  400. PERL6_BRACKETS = {
  401. '\u0028': '\u0029', '\u003c': '\u003e', '\u005b': '\u005d',
  402. '\u007b': '\u007d', '\u00ab': '\u00bb', '\u0f3a': '\u0f3b',
  403. '\u0f3c': '\u0f3d', '\u169b': '\u169c', '\u2018': '\u2019',
  404. '\u201a': '\u2019', '\u201b': '\u2019', '\u201c': '\u201d',
  405. '\u201e': '\u201d', '\u201f': '\u201d', '\u2039': '\u203a',
  406. '\u2045': '\u2046', '\u207d': '\u207e', '\u208d': '\u208e',
  407. '\u2208': '\u220b', '\u2209': '\u220c', '\u220a': '\u220d',
  408. '\u2215': '\u29f5', '\u223c': '\u223d', '\u2243': '\u22cd',
  409. '\u2252': '\u2253', '\u2254': '\u2255', '\u2264': '\u2265',
  410. '\u2266': '\u2267', '\u2268': '\u2269', '\u226a': '\u226b',
  411. '\u226e': '\u226f', '\u2270': '\u2271', '\u2272': '\u2273',
  412. '\u2274': '\u2275', '\u2276': '\u2277', '\u2278': '\u2279',
  413. '\u227a': '\u227b', '\u227c': '\u227d', '\u227e': '\u227f',
  414. '\u2280': '\u2281', '\u2282': '\u2283', '\u2284': '\u2285',
  415. '\u2286': '\u2287', '\u2288': '\u2289', '\u228a': '\u228b',
  416. '\u228f': '\u2290', '\u2291': '\u2292', '\u2298': '\u29b8',
  417. '\u22a2': '\u22a3', '\u22a6': '\u2ade', '\u22a8': '\u2ae4',
  418. '\u22a9': '\u2ae3', '\u22ab': '\u2ae5', '\u22b0': '\u22b1',
  419. '\u22b2': '\u22b3', '\u22b4': '\u22b5', '\u22b6': '\u22b7',
  420. '\u22c9': '\u22ca', '\u22cb': '\u22cc', '\u22d0': '\u22d1',
  421. '\u22d6': '\u22d7', '\u22d8': '\u22d9', '\u22da': '\u22db',
  422. '\u22dc': '\u22dd', '\u22de': '\u22df', '\u22e0': '\u22e1',
  423. '\u22e2': '\u22e3', '\u22e4': '\u22e5', '\u22e6': '\u22e7',
  424. '\u22e8': '\u22e9', '\u22ea': '\u22eb', '\u22ec': '\u22ed',
  425. '\u22f0': '\u22f1', '\u22f2': '\u22fa', '\u22f3': '\u22fb',
  426. '\u22f4': '\u22fc', '\u22f6': '\u22fd', '\u22f7': '\u22fe',
  427. '\u2308': '\u2309', '\u230a': '\u230b', '\u2329': '\u232a',
  428. '\u23b4': '\u23b5', '\u2768': '\u2769', '\u276a': '\u276b',
  429. '\u276c': '\u276d', '\u276e': '\u276f', '\u2770': '\u2771',
  430. '\u2772': '\u2773', '\u2774': '\u2775', '\u27c3': '\u27c4',
  431. '\u27c5': '\u27c6', '\u27d5': '\u27d6', '\u27dd': '\u27de',
  432. '\u27e2': '\u27e3', '\u27e4': '\u27e5', '\u27e6': '\u27e7',
  433. '\u27e8': '\u27e9', '\u27ea': '\u27eb', '\u2983': '\u2984',
  434. '\u2985': '\u2986', '\u2987': '\u2988', '\u2989': '\u298a',
  435. '\u298b': '\u298c', '\u298d': '\u298e', '\u298f': '\u2990',
  436. '\u2991': '\u2992', '\u2993': '\u2994', '\u2995': '\u2996',
  437. '\u2997': '\u2998', '\u29c0': '\u29c1', '\u29c4': '\u29c5',
  438. '\u29cf': '\u29d0', '\u29d1': '\u29d2', '\u29d4': '\u29d5',
  439. '\u29d8': '\u29d9', '\u29da': '\u29db', '\u29f8': '\u29f9',
  440. '\u29fc': '\u29fd', '\u2a2b': '\u2a2c', '\u2a2d': '\u2a2e',
  441. '\u2a34': '\u2a35', '\u2a3c': '\u2a3d', '\u2a64': '\u2a65',
  442. '\u2a79': '\u2a7a', '\u2a7d': '\u2a7e', '\u2a7f': '\u2a80',
  443. '\u2a81': '\u2a82', '\u2a83': '\u2a84', '\u2a8b': '\u2a8c',
  444. '\u2a91': '\u2a92', '\u2a93': '\u2a94', '\u2a95': '\u2a96',
  445. '\u2a97': '\u2a98', '\u2a99': '\u2a9a', '\u2a9b': '\u2a9c',
  446. '\u2aa1': '\u2aa2', '\u2aa6': '\u2aa7', '\u2aa8': '\u2aa9',
  447. '\u2aaa': '\u2aab', '\u2aac': '\u2aad', '\u2aaf': '\u2ab0',
  448. '\u2ab3': '\u2ab4', '\u2abb': '\u2abc', '\u2abd': '\u2abe',
  449. '\u2abf': '\u2ac0', '\u2ac1': '\u2ac2', '\u2ac3': '\u2ac4',
  450. '\u2ac5': '\u2ac6', '\u2acd': '\u2ace', '\u2acf': '\u2ad0',
  451. '\u2ad1': '\u2ad2', '\u2ad3': '\u2ad4', '\u2ad5': '\u2ad6',
  452. '\u2aec': '\u2aed', '\u2af7': '\u2af8', '\u2af9': '\u2afa',
  453. '\u2e02': '\u2e03', '\u2e04': '\u2e05', '\u2e09': '\u2e0a',
  454. '\u2e0c': '\u2e0d', '\u2e1c': '\u2e1d', '\u2e20': '\u2e21',
  455. '\u3008': '\u3009', '\u300a': '\u300b', '\u300c': '\u300d',
  456. '\u300e': '\u300f', '\u3010': '\u3011', '\u3014': '\u3015',
  457. '\u3016': '\u3017', '\u3018': '\u3019', '\u301a': '\u301b',
  458. '\u301d': '\u301e', '\ufd3e': '\ufd3f', '\ufe17': '\ufe18',
  459. '\ufe35': '\ufe36', '\ufe37': '\ufe38', '\ufe39': '\ufe3a',
  460. '\ufe3b': '\ufe3c', '\ufe3d': '\ufe3e', '\ufe3f': '\ufe40',
  461. '\ufe41': '\ufe42', '\ufe43': '\ufe44', '\ufe47': '\ufe48',
  462. '\ufe59': '\ufe5a', '\ufe5b': '\ufe5c', '\ufe5d': '\ufe5e',
  463. '\uff08': '\uff09', '\uff1c': '\uff1e', '\uff3b': '\uff3d',
  464. '\uff5b': '\uff5d', '\uff5f': '\uff60', '\uff62': '\uff63',
  465. }
  466. def _build_word_match(words, boundary_regex_fragment=None, prefix='', suffix=''):
  467. if boundary_regex_fragment is None:
  468. return r'\b(' + prefix + r'|'.join(re.escape(x) for x in words) + \
  469. suffix + r')\b'
  470. else:
  471. return r'(?<!' + boundary_regex_fragment + r')' + prefix + r'(' + \
  472. r'|'.join(re.escape(x) for x in words) + r')' + suffix + r'(?!' + \
  473. boundary_regex_fragment + r')'
  474. def brackets_callback(token_class):
  475. def callback(lexer, match, context):
  476. groups = match.groupdict()
  477. opening_chars = groups['delimiter']
  478. n_chars = len(opening_chars)
  479. adverbs = groups.get('adverbs')
  480. closer = Perl6Lexer.PERL6_BRACKETS.get(opening_chars[0])
  481. text = context.text
  482. if closer is None: # it's not a mirrored character, which means we
  483. # just need to look for the next occurrence
  484. end_pos = text.find(opening_chars, match.start('delimiter') + n_chars)
  485. else: # we need to look for the corresponding closing character,
  486. # keep nesting in mind
  487. closing_chars = closer * n_chars
  488. nesting_level = 1
  489. search_pos = match.start('delimiter')
  490. while nesting_level > 0:
  491. next_open_pos = text.find(opening_chars, search_pos + n_chars)
  492. next_close_pos = text.find(closing_chars, search_pos + n_chars)
  493. if next_close_pos == -1:
  494. next_close_pos = len(text)
  495. nesting_level = 0
  496. elif next_open_pos != -1 and next_open_pos < next_close_pos:
  497. nesting_level += 1
  498. search_pos = next_open_pos
  499. else: # next_close_pos < next_open_pos
  500. nesting_level -= 1
  501. search_pos = next_close_pos
  502. end_pos = next_close_pos
  503. if end_pos < 0: # if we didn't find a closer, just highlight the
  504. # rest of the text in this class
  505. end_pos = len(text)
  506. if adverbs is not None and re.search(r':to\b', adverbs):
  507. heredoc_terminator = text[match.start('delimiter') + n_chars:end_pos]
  508. end_heredoc = re.search(r'^\s*' + re.escape(heredoc_terminator) +
  509. r'\s*$', text[end_pos:], re.MULTILINE)
  510. if end_heredoc:
  511. end_pos += end_heredoc.end()
  512. else:
  513. end_pos = len(text)
  514. yield match.start(), token_class, text[match.start():end_pos + n_chars]
  515. context.pos = end_pos + n_chars
  516. return callback
  517. def opening_brace_callback(lexer, match, context):
  518. stack = context.stack
  519. yield match.start(), Text, context.text[match.start():match.end()]
  520. context.pos = match.end()
  521. # if we encounter an opening brace and we're one level
  522. # below a token state, it means we need to increment
  523. # the nesting level for braces so we know later when
  524. # we should return to the token rules.
  525. if len(stack) > 2 and stack[-2] == 'token':
  526. context.perl6_token_nesting_level += 1
  527. def closing_brace_callback(lexer, match, context):
  528. stack = context.stack
  529. yield match.start(), Text, context.text[match.start():match.end()]
  530. context.pos = match.end()
  531. # if we encounter a free closing brace and we're one level
  532. # below a token state, it means we need to check the nesting
  533. # level to see if we need to return to the token state.
  534. if len(stack) > 2 and stack[-2] == 'token':
  535. context.perl6_token_nesting_level -= 1
  536. if context.perl6_token_nesting_level == 0:
  537. stack.pop()
  538. def embedded_perl6_callback(lexer, match, context):
  539. context.perl6_token_nesting_level = 1
  540. yield match.start(), Text, context.text[match.start():match.end()]
  541. context.pos = match.end()
  542. context.stack.append('root')
  543. # If you're modifying these rules, be careful if you need to process '{' or '}'
  544. # characters. We have special logic for processing these characters (due to the fact
  545. # that you can nest Perl 6 code in regex blocks), so if you need to process one of
  546. # them, make sure you also process the corresponding one!
  547. tokens = {
  548. 'common': [
  549. (r'#[`|=](?P<delimiter>(?P<first_char>[' + ''.join(PERL6_BRACKETS) + r'])(?P=first_char)*)',
  550. brackets_callback(Comment.Multiline)),
  551. (r'#[^\n]*$', Comment.Single),
  552. (r'^(\s*)=begin\s+(\w+)\b.*?^\1=end\s+\2', Comment.Multiline),
  553. (r'^(\s*)=for.*?\n\s*?\n', Comment.Multiline),
  554. (r'^=.*?\n\s*?\n', Comment.Multiline),
  555. (r'(regex|token|rule)(\s*' + PERL6_IDENTIFIER_RANGE + '+:sym)',
  556. bygroups(Keyword, Name), 'token-sym-brackets'),
  557. (r'(regex|token|rule)(?!' + PERL6_IDENTIFIER_RANGE + r')(\s*' + PERL6_IDENTIFIER_RANGE + '+)?',
  558. bygroups(Keyword, Name), 'pre-token'),
  559. # deal with a special case in the Perl 6 grammar (role q { ... })
  560. (r'(role)(\s+)(q)(\s*)', bygroups(Keyword, Text, Name, Text)),
  561. (_build_word_match(PERL6_KEYWORDS, PERL6_IDENTIFIER_RANGE), Keyword),
  562. (_build_word_match(PERL6_BUILTIN_CLASSES, PERL6_IDENTIFIER_RANGE, suffix='(?::[UD])?'),
  563. Name.Builtin),
  564. (_build_word_match(PERL6_BUILTINS, PERL6_IDENTIFIER_RANGE), Name.Builtin),
  565. # copied from PerlLexer
  566. (r'[$@%&][.^:?=!~]?' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*',
  567. Name.Variable),
  568. (r'\$[!/](?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable.Global),
  569. (r'::\?\w+', Name.Variable.Global),
  570. (r'[$@%&]\*' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*',
  571. Name.Variable.Global),
  572. (r'\$(?:<.*?>)+', Name.Variable),
  573. (r'(?:q|qq|Q)[a-zA-Z]?\s*(?P<adverbs>:[\w\s:]+)?\s*(?P<delimiter>(?P<first_char>[^0-9a-zA-Z:\s])'
  574. r'(?P=first_char)*)', brackets_callback(String)),
  575. # copied from PerlLexer
  576. (r'0_?[0-7]+(_[0-7]+)*', Number.Oct),
  577. (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex),
  578. (r'0b[01]+(_[01]+)*', Number.Bin),
  579. (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?',
  580. Number.Float),
  581. (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float),
  582. (r'\d+(_\d+)*', Number.Integer),
  583. (r'(?<=~~)\s*/(?:\\\\|\\/|.)*?/', String.Regex),
  584. (r'(?<=[=(,])\s*/(?:\\\\|\\/|.)*?/', String.Regex),
  585. (r'm\w+(?=\()', Name),
  586. (r'(?:m|ms|rx)\s*(?P<adverbs>:[\w\s:]+)?\s*(?P<delimiter>(?P<first_char>[^\w:\s])'
  587. r'(?P=first_char)*)', brackets_callback(String.Regex)),
  588. (r'(?:s|ss|tr)\s*(?::[\w\s:]+)?\s*/(?:\\\\|\\/|.)*?/(?:\\\\|\\/|.)*?/',
  589. String.Regex),
  590. (r'<[^\s=].*?\S>', String),
  591. (_build_word_match(PERL6_OPERATORS), Operator),
  592. (r'\w' + PERL6_IDENTIFIER_RANGE + '*', Name),
  593. (r"'(\\\\|\\[^\\]|[^'\\])*'", String),
  594. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  595. ],
  596. 'root': [
  597. include('common'),
  598. (r'\{', opening_brace_callback),
  599. (r'\}', closing_brace_callback),
  600. (r'.+?', Text),
  601. ],
  602. 'pre-token': [
  603. include('common'),
  604. (r'\{', Text, ('#pop', 'token')),
  605. (r'.+?', Text),
  606. ],
  607. 'token-sym-brackets': [
  608. (r'(?P<delimiter>(?P<first_char>[' + ''.join(PERL6_BRACKETS) + '])(?P=first_char)*)',
  609. brackets_callback(Name), ('#pop', 'pre-token')),
  610. default(('#pop', 'pre-token')),
  611. ],
  612. 'token': [
  613. (r'\}', Text, '#pop'),
  614. (r'(?<=:)(?:my|our|state|constant|temp|let).*?;', using(this)),
  615. # make sure that quotes in character classes aren't treated as strings
  616. (r'<(?:[-!?+.]\s*)?\[.*?\]>', String.Regex),
  617. # make sure that '#' characters in quotes aren't treated as comments
  618. (r"(?<!\\)'(\\\\|\\[^\\]|[^'\\])*'", String.Regex),
  619. (r'(?<!\\)"(\\\\|\\[^\\]|[^"\\])*"', String.Regex),
  620. (r'#.*?$', Comment.Single),
  621. (r'\{', embedded_perl6_callback),
  622. ('.+?', String.Regex),
  623. ],
  624. }
  625. def analyse_text(text):
  626. def strip_pod(lines):
  627. in_pod = False
  628. stripped_lines = []
  629. for line in lines:
  630. if re.match(r'^=(?:end|cut)', line):
  631. in_pod = False
  632. elif re.match(r'^=\w+', line):
  633. in_pod = True
  634. elif not in_pod:
  635. stripped_lines.append(line)
  636. return stripped_lines
  637. # XXX handle block comments
  638. lines = text.splitlines()
  639. lines = strip_pod(lines)
  640. text = '\n'.join(lines)
  641. if shebang_matches(text, r'perl6|rakudo|niecza|pugs'):
  642. return True
  643. saw_perl_decl = False
  644. rating = False
  645. # check for my/our/has declarations
  646. if re.search(r"(?:my|our|has)\s+(?:" + Perl6Lexer.PERL6_IDENTIFIER_RANGE +
  647. r"+\s+)?[$@%&(]", text):
  648. rating = 0.8
  649. saw_perl_decl = True
  650. for line in lines:
  651. line = re.sub('#.*', '', line)
  652. if re.match(r'^\s*$', line):
  653. continue
  654. # match v6; use v6; use v6.0; use v6.0.0;
  655. if re.match(r'^\s*(?:use\s+)?v6(?:\.\d(?:\.\d)?)?;', line):
  656. return True
  657. # match class, module, role, enum, grammar declarations
  658. class_decl = re.match(r'^\s*(?:(?P<scope>my|our)\s+)?(?:module|class|role|enum|grammar)', line)
  659. if class_decl:
  660. if saw_perl_decl or class_decl.group('scope') is not None:
  661. return True
  662. rating = 0.05
  663. continue
  664. break
  665. if ':=' in text:
  666. # Same logic as above for PerlLexer
  667. rating /= 2
  668. return rating
  669. def __init__(self, **options):
  670. super().__init__(**options)
  671. self.encoding = options.get('encoding', 'utf-8')