dsls.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. """
  2. pygments.lexers.dsls
  3. ~~~~~~~~~~~~~~~~~~~~
  4. Lexers for various domain-specific 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 ExtendedRegexLexer, RegexLexer, bygroups, words, \
  10. include, default, this, using, combined
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation, Whitespace
  13. __all__ = ['ProtoBufLexer', 'ZeekLexer', 'PuppetLexer', 'RslLexer',
  14. 'MscgenLexer', 'VGLLexer', 'AlloyLexer', 'PanLexer',
  15. 'CrmshLexer', 'ThriftLexer', 'FlatlineLexer', 'SnowballLexer']
  16. class ProtoBufLexer(RegexLexer):
  17. """
  18. Lexer for `Protocol Buffer <http://code.google.com/p/protobuf/>`_
  19. definition files.
  20. .. versionadded:: 1.4
  21. """
  22. name = 'Protocol Buffer'
  23. aliases = ['protobuf', 'proto']
  24. filenames = ['*.proto']
  25. tokens = {
  26. 'root': [
  27. (r'[ \t]+', Text),
  28. (r'[,;{}\[\]()<>]', Punctuation),
  29. (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single),
  30. (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline),
  31. (words((
  32. 'import', 'option', 'optional', 'required', 'repeated',
  33. 'reserved', 'default', 'packed', 'ctype', 'extensions', 'to',
  34. 'max', 'rpc', 'returns', 'oneof', 'syntax'), prefix=r'\b', suffix=r'\b'),
  35. Keyword),
  36. (words((
  37. 'int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64',
  38. 'fixed32', 'fixed64', 'sfixed32', 'sfixed64',
  39. 'float', 'double', 'bool', 'string', 'bytes'), suffix=r'\b'),
  40. Keyword.Type),
  41. (r'(true|false)\b', Keyword.Constant),
  42. (r'(package)(\s+)', bygroups(Keyword.Namespace, Text), 'package'),
  43. (r'(message|extend)(\s+)',
  44. bygroups(Keyword.Declaration, Text), 'message'),
  45. (r'(enum|group|service)(\s+)',
  46. bygroups(Keyword.Declaration, Text), 'type'),
  47. (r'\".*?\"', String),
  48. (r'\'.*?\'', String),
  49. (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float),
  50. (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
  51. (r'(\-?(inf|nan))\b', Number.Float),
  52. (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex),
  53. (r'0[0-7]+[LlUu]*', Number.Oct),
  54. (r'\d+[LlUu]*', Number.Integer),
  55. (r'[+-=]', Operator),
  56. (r'([a-zA-Z_][\w.]*)([ \t]*)(=)',
  57. bygroups(Name.Attribute, Text, Operator)),
  58. (r'[a-zA-Z_][\w.]*', Name),
  59. ],
  60. 'package': [
  61. (r'[a-zA-Z_]\w*', Name.Namespace, '#pop'),
  62. default('#pop'),
  63. ],
  64. 'message': [
  65. (r'[a-zA-Z_]\w*', Name.Class, '#pop'),
  66. default('#pop'),
  67. ],
  68. 'type': [
  69. (r'[a-zA-Z_]\w*', Name, '#pop'),
  70. default('#pop'),
  71. ],
  72. }
  73. class ThriftLexer(RegexLexer):
  74. """
  75. For `Thrift <https://thrift.apache.org/>`__ interface definitions.
  76. .. versionadded:: 2.1
  77. """
  78. name = 'Thrift'
  79. aliases = ['thrift']
  80. filenames = ['*.thrift']
  81. mimetypes = ['application/x-thrift']
  82. tokens = {
  83. 'root': [
  84. include('whitespace'),
  85. include('comments'),
  86. (r'"', String.Double, combined('stringescape', 'dqs')),
  87. (r'\'', String.Single, combined('stringescape', 'sqs')),
  88. (r'(namespace)(\s+)',
  89. bygroups(Keyword.Namespace, Text.Whitespace), 'namespace'),
  90. (r'(enum|union|struct|service|exception)(\s+)',
  91. bygroups(Keyword.Declaration, Text.Whitespace), 'class'),
  92. (r'((?:(?:[^\W\d]|\$)[\w.\[\]$<>]*\s+)+?)' # return arguments
  93. r'((?:[^\W\d]|\$)[\w$]*)' # method name
  94. r'(\s*)(\()', # signature start
  95. bygroups(using(this), Name.Function, Text, Operator)),
  96. include('keywords'),
  97. include('numbers'),
  98. (r'[&=]', Operator),
  99. (r'[:;,{}()<>\[\]]', Punctuation),
  100. (r'[a-zA-Z_](\.\w|\w)*', Name),
  101. ],
  102. 'whitespace': [
  103. (r'\n', Text.Whitespace),
  104. (r'\s+', Text.Whitespace),
  105. ],
  106. 'comments': [
  107. (r'#.*$', Comment),
  108. (r'//.*?\n', Comment),
  109. (r'/\*[\w\W]*?\*/', Comment.Multiline),
  110. ],
  111. 'stringescape': [
  112. (r'\\([\\nrt"\'])', String.Escape),
  113. ],
  114. 'dqs': [
  115. (r'"', String.Double, '#pop'),
  116. (r'[^\\"\n]+', String.Double),
  117. ],
  118. 'sqs': [
  119. (r"'", String.Single, '#pop'),
  120. (r'[^\\\'\n]+', String.Single),
  121. ],
  122. 'namespace': [
  123. (r'[a-z*](\.\w|\w)*', Name.Namespace, '#pop'),
  124. default('#pop'),
  125. ],
  126. 'class': [
  127. (r'[a-zA-Z_]\w*', Name.Class, '#pop'),
  128. default('#pop'),
  129. ],
  130. 'keywords': [
  131. (r'(async|oneway|extends|throws|required|optional)\b', Keyword),
  132. (r'(true|false)\b', Keyword.Constant),
  133. (r'(const|typedef)\b', Keyword.Declaration),
  134. (words((
  135. 'cpp_namespace', 'cpp_include', 'cpp_type', 'java_package',
  136. 'cocoa_prefix', 'csharp_namespace', 'delphi_namespace',
  137. 'php_namespace', 'py_module', 'perl_package',
  138. 'ruby_namespace', 'smalltalk_category', 'smalltalk_prefix',
  139. 'xsd_all', 'xsd_optional', 'xsd_nillable', 'xsd_namespace',
  140. 'xsd_attrs', 'include'), suffix=r'\b'),
  141. Keyword.Namespace),
  142. (words((
  143. 'void', 'bool', 'byte', 'i16', 'i32', 'i64', 'double',
  144. 'string', 'binary', 'map', 'list', 'set', 'slist',
  145. 'senum'), suffix=r'\b'),
  146. Keyword.Type),
  147. (words((
  148. 'BEGIN', 'END', '__CLASS__', '__DIR__', '__FILE__',
  149. '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__',
  150. 'abstract', 'alias', 'and', 'args', 'as', 'assert', 'begin',
  151. 'break', 'case', 'catch', 'class', 'clone', 'continue',
  152. 'declare', 'def', 'default', 'del', 'delete', 'do', 'dynamic',
  153. 'elif', 'else', 'elseif', 'elsif', 'end', 'enddeclare',
  154. 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile',
  155. 'ensure', 'except', 'exec', 'finally', 'float', 'for',
  156. 'foreach', 'function', 'global', 'goto', 'if', 'implements',
  157. 'import', 'in', 'inline', 'instanceof', 'interface', 'is',
  158. 'lambda', 'module', 'native', 'new', 'next', 'nil', 'not',
  159. 'or', 'pass', 'public', 'print', 'private', 'protected',
  160. 'raise', 'redo', 'rescue', 'retry', 'register', 'return',
  161. 'self', 'sizeof', 'static', 'super', 'switch', 'synchronized',
  162. 'then', 'this', 'throw', 'transient', 'try', 'undef',
  163. 'unless', 'unsigned', 'until', 'use', 'var', 'virtual',
  164. 'volatile', 'when', 'while', 'with', 'xor', 'yield'),
  165. prefix=r'\b', suffix=r'\b'),
  166. Keyword.Reserved),
  167. ],
  168. 'numbers': [
  169. (r'[+-]?(\d+\.\d+([eE][+-]?\d+)?|\.?\d+[eE][+-]?\d+)', Number.Float),
  170. (r'[+-]?0x[0-9A-Fa-f]+', Number.Hex),
  171. (r'[+-]?[0-9]+', Number.Integer),
  172. ],
  173. }
  174. class ZeekLexer(RegexLexer):
  175. """
  176. For `Zeek <https://www.zeek.org/>`_ scripts.
  177. .. versionadded:: 2.5
  178. """
  179. name = 'Zeek'
  180. aliases = ['zeek', 'bro']
  181. filenames = ['*.zeek', '*.bro']
  182. _hex = r'[0-9a-fA-F]'
  183. _float = r'((\d*\.?\d+)|(\d+\.?\d*))([eE][-+]?\d+)?'
  184. _h = r'[A-Za-z0-9][-A-Za-z0-9]*'
  185. tokens = {
  186. 'root': [
  187. include('whitespace'),
  188. include('comments'),
  189. include('directives'),
  190. include('attributes'),
  191. include('types'),
  192. include('keywords'),
  193. include('literals'),
  194. include('operators'),
  195. include('punctuation'),
  196. (r'((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(?=\s*\()',
  197. Name.Function),
  198. include('identifiers'),
  199. ],
  200. 'whitespace': [
  201. (r'\n', Text),
  202. (r'\s+', Text),
  203. (r'\\\n', Text),
  204. ],
  205. 'comments': [
  206. (r'#.*$', Comment),
  207. ],
  208. 'directives': [
  209. (r'@(load-plugin|load-sigs|load|unload)\b.*$', Comment.Preproc),
  210. (r'@(DEBUG|DIR|FILENAME|deprecated|if|ifdef|ifndef|else|endif)\b', Comment.Preproc),
  211. (r'(@prefixes)\s*(\+?=).*$', Comment.Preproc),
  212. ],
  213. 'attributes': [
  214. (words(('redef', 'priority', 'log', 'optional', 'default', 'add_func',
  215. 'delete_func', 'expire_func', 'read_expire', 'write_expire',
  216. 'create_expire', 'synchronized', 'persistent', 'rotate_interval',
  217. 'rotate_size', 'encrypt', 'raw_output', 'mergeable', 'error_handler',
  218. 'type_column', 'deprecated'),
  219. prefix=r'&', suffix=r'\b'),
  220. Keyword.Pseudo),
  221. ],
  222. 'types': [
  223. (words(('any',
  224. 'enum', 'record', 'set', 'table', 'vector',
  225. 'function', 'hook', 'event',
  226. 'addr', 'bool', 'count', 'double', 'file', 'int', 'interval',
  227. 'pattern', 'port', 'string', 'subnet', 'time'),
  228. suffix=r'\b'),
  229. Keyword.Type),
  230. (r'(opaque)(\s+)(of)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b',
  231. bygroups(Keyword.Type, Text, Operator.Word, Text, Keyword.Type)),
  232. (r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)(\s*)\b(record|enum)\b',
  233. bygroups(Keyword, Text, Name.Class, Text, Operator, Text, Keyword.Type)),
  234. (r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)',
  235. bygroups(Keyword, Text, Name, Text, Operator)),
  236. (r'(redef)(\s+)(record|enum)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b',
  237. bygroups(Keyword, Text, Keyword.Type, Text, Name.Class)),
  238. ],
  239. 'keywords': [
  240. (words(('redef', 'export', 'if', 'else', 'for', 'while',
  241. 'return', 'break', 'next', 'continue', 'fallthrough',
  242. 'switch', 'default', 'case',
  243. 'add', 'delete',
  244. 'when', 'timeout', 'schedule'),
  245. suffix=r'\b'),
  246. Keyword),
  247. (r'(print)\b', Keyword),
  248. (r'(global|local|const|option)\b', Keyword.Declaration),
  249. (r'(module)(\s+)(([A-Za-z_]\w*)(?:::([A-Za-z_]\w*))*)\b',
  250. bygroups(Keyword.Namespace, Text, Name.Namespace)),
  251. ],
  252. 'literals': [
  253. (r'"', String, 'string'),
  254. # Not the greatest match for patterns, but generally helps
  255. # disambiguate between start of a pattern and just a division
  256. # operator.
  257. (r'/(?=.*/)', String.Regex, 'regex'),
  258. (r'(T|F)\b', Keyword.Constant),
  259. # Port
  260. (r'\d{1,5}/(udp|tcp|icmp|unknown)\b', Number),
  261. # IPv4 Address
  262. (r'(\d{1,3}.){3}(\d{1,3})\b', Number),
  263. # IPv6 Address
  264. (r'\[([0-9a-fA-F]{0,4}:){2,7}([0-9a-fA-F]{0,4})?((\d{1,3}.){3}(\d{1,3}))?\]', Number),
  265. # Numeric
  266. (r'0[xX]' + _hex + r'+\b', Number.Hex),
  267. (_float + r'\s*(day|hr|min|sec|msec|usec)s?\b', Number.Float),
  268. (_float + r'\b', Number.Float),
  269. (r'(\d+)\b', Number.Integer),
  270. # Hostnames
  271. (_h + r'(\.' + _h + r')+', String),
  272. ],
  273. 'operators': [
  274. (r'[!%*/+<=>~|&^-]', Operator),
  275. (r'([-+=&|]{2}|[+=!><-]=)', Operator),
  276. (r'(in|as|is|of)\b', Operator.Word),
  277. (r'\??\$', Operator),
  278. ],
  279. 'punctuation': [
  280. (r'[{}()\[\],;.]', Punctuation),
  281. # The "ternary if", which uses '?' and ':', could instead be
  282. # treated as an Operator, but colons are more frequently used to
  283. # separate field/identifier names from their types, so the (often)
  284. # less-prominent Punctuation is used even with '?' for consistency.
  285. (r'[?:]', Punctuation),
  286. ],
  287. 'identifiers': [
  288. (r'([a-zA-Z_]\w*)(::)', bygroups(Name, Punctuation)),
  289. (r'[a-zA-Z_]\w*', Name)
  290. ],
  291. 'string': [
  292. (r'\\.', String.Escape),
  293. (r'%-?[0-9]*(\.[0-9]+)?[DTd-gsx]', String.Escape),
  294. (r'"', String, '#pop'),
  295. (r'.', String),
  296. ],
  297. 'regex': [
  298. (r'\\.', String.Escape),
  299. (r'/', String.Regex, '#pop'),
  300. (r'.', String.Regex),
  301. ],
  302. }
  303. BroLexer = ZeekLexer
  304. class PuppetLexer(RegexLexer):
  305. """
  306. For `Puppet <http://puppetlabs.com/>`__ configuration DSL.
  307. .. versionadded:: 1.6
  308. """
  309. name = 'Puppet'
  310. aliases = ['puppet']
  311. filenames = ['*.pp']
  312. tokens = {
  313. 'root': [
  314. include('comments'),
  315. include('keywords'),
  316. include('names'),
  317. include('numbers'),
  318. include('operators'),
  319. include('strings'),
  320. (r'[]{}:(),;[]', Punctuation),
  321. (r'[^\S\n]+', Text),
  322. ],
  323. 'comments': [
  324. (r'\s*#.*$', Comment),
  325. (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
  326. ],
  327. 'operators': [
  328. (r'(=>|\?|<|>|=|\+|-|/|\*|~|!|\|)', Operator),
  329. (r'(in|and|or|not)\b', Operator.Word),
  330. ],
  331. 'names': [
  332. (r'[a-zA-Z_]\w*', Name.Attribute),
  333. (r'(\$\S+)(\[)(\S+)(\])', bygroups(Name.Variable, Punctuation,
  334. String, Punctuation)),
  335. (r'\$\S+', Name.Variable),
  336. ],
  337. 'numbers': [
  338. # Copypasta from the Python lexer
  339. (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float),
  340. (r'\d+[eE][+-]?[0-9]+j?', Number.Float),
  341. (r'0[0-7]+j?', Number.Oct),
  342. (r'0[xX][a-fA-F0-9]+', Number.Hex),
  343. (r'\d+L', Number.Integer.Long),
  344. (r'\d+j?', Number.Integer)
  345. ],
  346. 'keywords': [
  347. # Left out 'group' and 'require'
  348. # Since they're often used as attributes
  349. (words((
  350. 'absent', 'alert', 'alias', 'audit', 'augeas', 'before', 'case',
  351. 'check', 'class', 'computer', 'configured', 'contained',
  352. 'create_resources', 'crit', 'cron', 'debug', 'default',
  353. 'define', 'defined', 'directory', 'else', 'elsif', 'emerg',
  354. 'err', 'exec', 'extlookup', 'fail', 'false', 'file',
  355. 'filebucket', 'fqdn_rand', 'generate', 'host', 'if', 'import',
  356. 'include', 'info', 'inherits', 'inline_template', 'installed',
  357. 'interface', 'k5login', 'latest', 'link', 'loglevel',
  358. 'macauthorization', 'mailalias', 'maillist', 'mcx', 'md5',
  359. 'mount', 'mounted', 'nagios_command', 'nagios_contact',
  360. 'nagios_contactgroup', 'nagios_host', 'nagios_hostdependency',
  361. 'nagios_hostescalation', 'nagios_hostextinfo', 'nagios_hostgroup',
  362. 'nagios_service', 'nagios_servicedependency', 'nagios_serviceescalation',
  363. 'nagios_serviceextinfo', 'nagios_servicegroup', 'nagios_timeperiod',
  364. 'node', 'noop', 'notice', 'notify', 'package', 'present', 'purged',
  365. 'realize', 'regsubst', 'resources', 'role', 'router', 'running',
  366. 'schedule', 'scheduled_task', 'search', 'selboolean', 'selmodule',
  367. 'service', 'sha1', 'shellquote', 'split', 'sprintf',
  368. 'ssh_authorized_key', 'sshkey', 'stage', 'stopped', 'subscribe',
  369. 'tag', 'tagged', 'template', 'tidy', 'true', 'undef', 'unmounted',
  370. 'user', 'versioncmp', 'vlan', 'warning', 'yumrepo', 'zfs', 'zone',
  371. 'zpool'), prefix='(?i)', suffix=r'\b'),
  372. Keyword),
  373. ],
  374. 'strings': [
  375. (r'"([^"])*"', String),
  376. (r"'(\\'|[^'])*'", String),
  377. ],
  378. }
  379. class RslLexer(RegexLexer):
  380. """
  381. `RSL <http://en.wikipedia.org/wiki/RAISE>`_ is the formal specification
  382. language used in RAISE (Rigorous Approach to Industrial Software Engineering)
  383. method.
  384. .. versionadded:: 2.0
  385. """
  386. name = 'RSL'
  387. aliases = ['rsl']
  388. filenames = ['*.rsl']
  389. mimetypes = ['text/rsl']
  390. flags = re.MULTILINE | re.DOTALL
  391. tokens = {
  392. 'root': [
  393. (words((
  394. 'Bool', 'Char', 'Int', 'Nat', 'Real', 'Text', 'Unit', 'abs',
  395. 'all', 'always', 'any', 'as', 'axiom', 'card', 'case', 'channel',
  396. 'chaos', 'class', 'devt_relation', 'dom', 'elems', 'else', 'elif',
  397. 'end', 'exists', 'extend', 'false', 'for', 'hd', 'hide', 'if',
  398. 'in', 'is', 'inds', 'initialise', 'int', 'inter', 'isin', 'len',
  399. 'let', 'local', 'ltl_assertion', 'object', 'of', 'out', 'post',
  400. 'pre', 'read', 'real', 'rng', 'scheme', 'skip', 'stop', 'swap',
  401. 'then', 'theory', 'test_case', 'tl', 'transition_system', 'true',
  402. 'type', 'union', 'until', 'use', 'value', 'variable', 'while',
  403. 'with', 'write', '~isin', '-inflist', '-infset', '-list',
  404. '-set'), prefix=r'\b', suffix=r'\b'),
  405. Keyword),
  406. (r'(variable|value)\b', Keyword.Declaration),
  407. (r'--.*?\n', Comment),
  408. (r'<:.*?:>', Comment),
  409. (r'\{!.*?!\}', Comment),
  410. (r'/\*.*?\*/', Comment),
  411. (r'^[ \t]*([\w]+)[ \t]*:[^:]', Name.Function),
  412. (r'(^[ \t]*)([\w]+)([ \t]*\([\w\s,]*\)[ \t]*)(is|as)',
  413. bygroups(Text, Name.Function, Text, Keyword)),
  414. (r'\b[A-Z]\w*\b', Keyword.Type),
  415. (r'(true|false)\b', Keyword.Constant),
  416. (r'".*"', String),
  417. (r'\'.\'', String.Char),
  418. (r'(><|->|-m->|/\\|<=|<<=|<\.|\|\||\|\^\||-~->|-~m->|\\/|>=|>>|'
  419. r'\.>|\+\+|-\\|<->|=>|:-|~=|\*\*|<<|>>=|\+>|!!|\|=\||#)',
  420. Operator),
  421. (r'[0-9]+\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
  422. (r'0x[0-9a-f]+', Number.Hex),
  423. (r'[0-9]+', Number.Integer),
  424. (r'.', Text),
  425. ],
  426. }
  427. def analyse_text(text):
  428. """
  429. Check for the most common text in the beginning of a RSL file.
  430. """
  431. if re.search(r'scheme\s*.*?=\s*class\s*type', text, re.I) is not None:
  432. return 1.0
  433. class MscgenLexer(RegexLexer):
  434. """
  435. For `Mscgen <http://www.mcternan.me.uk/mscgen/>`_ files.
  436. .. versionadded:: 1.6
  437. """
  438. name = 'Mscgen'
  439. aliases = ['mscgen', 'msc']
  440. filenames = ['*.msc']
  441. _var = r'(\w+|"(?:\\"|[^"])*")'
  442. tokens = {
  443. 'root': [
  444. (r'msc\b', Keyword.Type),
  445. # Options
  446. (r'(hscale|HSCALE|width|WIDTH|wordwraparcs|WORDWRAPARCS'
  447. r'|arcgradient|ARCGRADIENT)\b', Name.Property),
  448. # Operators
  449. (r'(abox|ABOX|rbox|RBOX|box|BOX|note|NOTE)\b', Operator.Word),
  450. (r'(\.|-|\|){3}', Keyword),
  451. (r'(?:-|=|\.|:){2}'
  452. r'|<<=>>|<->|<=>|<<>>|<:>'
  453. r'|->|=>>|>>|=>|:>|-x|-X'
  454. r'|<-|<<=|<<|<=|<:|x-|X-|=', Operator),
  455. # Names
  456. (r'\*', Name.Builtin),
  457. (_var, Name.Variable),
  458. # Other
  459. (r'\[', Punctuation, 'attrs'),
  460. (r'\{|\}|,|;', Punctuation),
  461. include('comments')
  462. ],
  463. 'attrs': [
  464. (r'\]', Punctuation, '#pop'),
  465. (_var + r'(\s*)(=)(\s*)' + _var,
  466. bygroups(Name.Attribute, Text.Whitespace, Operator, Text.Whitespace,
  467. String)),
  468. (r',', Punctuation),
  469. include('comments')
  470. ],
  471. 'comments': [
  472. (r'(?://|#).*?\n', Comment.Single),
  473. (r'/\*(?:.|\n)*?\*/', Comment.Multiline),
  474. (r'[ \t\r\n]+', Text.Whitespace)
  475. ]
  476. }
  477. class VGLLexer(RegexLexer):
  478. """
  479. For `SampleManager VGL <http://www.thermoscientific.com/samplemanager>`_
  480. source code.
  481. .. versionadded:: 1.6
  482. """
  483. name = 'VGL'
  484. aliases = ['vgl']
  485. filenames = ['*.rpf']
  486. flags = re.MULTILINE | re.DOTALL | re.IGNORECASE
  487. tokens = {
  488. 'root': [
  489. (r'\{[^}]*\}', Comment.Multiline),
  490. (r'declare', Keyword.Constant),
  491. (r'(if|then|else|endif|while|do|endwhile|and|or|prompt|object'
  492. r'|create|on|line|with|global|routine|value|endroutine|constant'
  493. r'|global|set|join|library|compile_option|file|exists|create|copy'
  494. r'|delete|enable|windows|name|notprotected)(?! *[=<>.,()])',
  495. Keyword),
  496. (r'(true|false|null|empty|error|locked)', Keyword.Constant),
  497. (r'[~^*#!%&\[\]()<>|+=:;,./?-]', Operator),
  498. (r'"[^"]*"', String),
  499. (r'(\.)([a-z_$][\w$]*)', bygroups(Operator, Name.Attribute)),
  500. (r'[0-9][0-9]*(\.[0-9]+(e[+\-]?[0-9]+)?)?', Number),
  501. (r'[a-z_$][\w$]*', Name),
  502. (r'[\r\n]+', Text),
  503. (r'\s+', Text)
  504. ]
  505. }
  506. class AlloyLexer(RegexLexer):
  507. """
  508. For `Alloy <http://alloy.mit.edu>`_ source code.
  509. .. versionadded:: 2.0
  510. """
  511. name = 'Alloy'
  512. aliases = ['alloy']
  513. filenames = ['*.als']
  514. mimetypes = ['text/x-alloy']
  515. flags = re.MULTILINE | re.DOTALL
  516. iden_rex = r'[a-zA-Z_][\w\']*'
  517. text_tuple = (r'[^\S\n]+', Text)
  518. tokens = {
  519. 'sig': [
  520. (r'(extends)\b', Keyword, '#pop'),
  521. (iden_rex, Name),
  522. text_tuple,
  523. (r',', Punctuation),
  524. (r'\{', Operator, '#pop'),
  525. ],
  526. 'module': [
  527. text_tuple,
  528. (iden_rex, Name, '#pop'),
  529. ],
  530. 'fun': [
  531. text_tuple,
  532. (r'\{', Operator, '#pop'),
  533. (iden_rex, Name, '#pop'),
  534. ],
  535. 'root': [
  536. (r'--.*?$', Comment.Single),
  537. (r'//.*?$', Comment.Single),
  538. (r'/\*.*?\*/', Comment.Multiline),
  539. text_tuple,
  540. (r'(module|open)(\s+)', bygroups(Keyword.Namespace, Text),
  541. 'module'),
  542. (r'(sig|enum)(\s+)', bygroups(Keyword.Declaration, Text), 'sig'),
  543. (r'(iden|univ|none)\b', Keyword.Constant),
  544. (r'(int|Int)\b', Keyword.Type),
  545. (r'(this|abstract|extends|set|seq|one|lone|let)\b', Keyword),
  546. (r'(all|some|no|sum|disj|when|else)\b', Keyword),
  547. (r'(run|check|for|but|exactly|expect|as)\b', Keyword),
  548. (r'(and|or|implies|iff|in)\b', Operator.Word),
  549. (r'(fun|pred|fact|assert)(\s+)', bygroups(Keyword, Text), 'fun'),
  550. (r'!|#|&&|\+\+|<<|>>|>=|<=>|<=|\.|->', Operator),
  551. (r'[-+/*%=<>&!^|~{}\[\]().]', Operator),
  552. (iden_rex, Name),
  553. (r'[:,]', Punctuation),
  554. (r'[0-9]+', Number.Integer),
  555. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  556. (r'\n', Text),
  557. ]
  558. }
  559. class PanLexer(RegexLexer):
  560. """
  561. Lexer for `pan <https://github.com/quattor/pan/>`_ source files.
  562. Based on tcsh lexer.
  563. .. versionadded:: 2.0
  564. """
  565. name = 'Pan'
  566. aliases = ['pan']
  567. filenames = ['*.pan']
  568. tokens = {
  569. 'root': [
  570. include('basic'),
  571. (r'\(', Keyword, 'paren'),
  572. (r'\{', Keyword, 'curly'),
  573. include('data'),
  574. ],
  575. 'basic': [
  576. (words((
  577. 'if', 'for', 'with', 'else', 'type', 'bind', 'while', 'valid', 'final',
  578. 'prefix', 'unique', 'object', 'foreach', 'include', 'template',
  579. 'function', 'variable', 'structure', 'extensible', 'declaration'),
  580. prefix=r'\b', suffix=r'\s*\b'),
  581. Keyword),
  582. (words((
  583. 'file_contents', 'format', 'index', 'length', 'match', 'matches',
  584. 'replace', 'splice', 'split', 'substr', 'to_lowercase', 'to_uppercase',
  585. 'debug', 'error', 'traceback', 'deprecated', 'base64_decode',
  586. 'base64_encode', 'digest', 'escape', 'unescape', 'append', 'create',
  587. 'first', 'nlist', 'key', 'list', 'merge', 'next', 'prepend', 'is_boolean',
  588. 'is_defined', 'is_double', 'is_list', 'is_long', 'is_nlist', 'is_null',
  589. 'is_number', 'is_property', 'is_resource', 'is_string', 'to_boolean',
  590. 'to_double', 'to_long', 'to_string', 'clone', 'delete', 'exists',
  591. 'path_exists', 'if_exists', 'return', 'value'),
  592. prefix=r'\b', suffix=r'\s*\b'),
  593. Name.Builtin),
  594. (r'#.*', Comment),
  595. (r'\\[\w\W]', String.Escape),
  596. (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)),
  597. (r'[\[\]{}()=]+', Operator),
  598. (r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
  599. (r';', Punctuation),
  600. ],
  601. 'data': [
  602. (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double),
  603. (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
  604. (r'\s+', Text),
  605. (r'[^=\s\[\]{}()$"\'`\\;#]+', Text),
  606. (r'\d+(?= |\Z)', Number),
  607. ],
  608. 'curly': [
  609. (r'\}', Keyword, '#pop'),
  610. (r':-', Keyword),
  611. (r'\w+', Name.Variable),
  612. (r'[^}:"\'`$]+', Punctuation),
  613. (r':', Punctuation),
  614. include('root'),
  615. ],
  616. 'paren': [
  617. (r'\)', Keyword, '#pop'),
  618. include('root'),
  619. ],
  620. }
  621. class CrmshLexer(RegexLexer):
  622. """
  623. Lexer for `crmsh <http://crmsh.github.io/>`_ configuration files
  624. for Pacemaker clusters.
  625. .. versionadded:: 2.1
  626. """
  627. name = 'Crmsh'
  628. aliases = ['crmsh', 'pcmk']
  629. filenames = ['*.crmsh', '*.pcmk']
  630. mimetypes = []
  631. elem = words((
  632. 'node', 'primitive', 'group', 'clone', 'ms', 'location',
  633. 'colocation', 'order', 'fencing_topology', 'rsc_ticket',
  634. 'rsc_template', 'property', 'rsc_defaults',
  635. 'op_defaults', 'acl_target', 'acl_group', 'user', 'role',
  636. 'tag'), suffix=r'(?![\w#$-])')
  637. sub = words((
  638. 'params', 'meta', 'operations', 'op', 'rule',
  639. 'attributes', 'utilization'), suffix=r'(?![\w#$-])')
  640. acl = words(('read', 'write', 'deny'), suffix=r'(?![\w#$-])')
  641. bin_rel = words(('and', 'or'), suffix=r'(?![\w#$-])')
  642. un_ops = words(('defined', 'not_defined'), suffix=r'(?![\w#$-])')
  643. date_exp = words(('in_range', 'date', 'spec', 'in'), suffix=r'(?![\w#$-])')
  644. acl_mod = (r'(?:tag|ref|reference|attribute|type|xpath)')
  645. bin_ops = (r'(?:lt|gt|lte|gte|eq|ne)')
  646. val_qual = (r'(?:string|version|number)')
  647. rsc_role_action = (r'(?:Master|Started|Slave|Stopped|'
  648. r'start|promote|demote|stop)')
  649. tokens = {
  650. 'root': [
  651. (r'^#.*\n?', Comment),
  652. # attr=value (nvpair)
  653. (r'([\w#$-]+)(=)("(?:""|[^"])*"|\S+)',
  654. bygroups(Name.Attribute, Punctuation, String)),
  655. # need this construct, otherwise numeric node ids
  656. # are matched as scores
  657. # elem id:
  658. (r'(node)(\s+)([\w#$-]+)(:)',
  659. bygroups(Keyword, Whitespace, Name, Punctuation)),
  660. # scores
  661. (r'([+-]?([0-9]+|inf)):', Number),
  662. # keywords (elements and other)
  663. (elem, Keyword),
  664. (sub, Keyword),
  665. (acl, Keyword),
  666. # binary operators
  667. (r'(?:%s:)?(%s)(?![\w#$-])' % (val_qual, bin_ops), Operator.Word),
  668. # other operators
  669. (bin_rel, Operator.Word),
  670. (un_ops, Operator.Word),
  671. (date_exp, Operator.Word),
  672. # builtin attributes (e.g. #uname)
  673. (r'#[a-z]+(?![\w#$-])', Name.Builtin),
  674. # acl_mod:blah
  675. (r'(%s)(:)("(?:""|[^"])*"|\S+)' % acl_mod,
  676. bygroups(Keyword, Punctuation, Name)),
  677. # rsc_id[:(role|action)]
  678. # NB: this matches all other identifiers
  679. (r'([\w#$-]+)(?:(:)(%s))?(?![\w#$-])' % rsc_role_action,
  680. bygroups(Name, Punctuation, Operator.Word)),
  681. # punctuation
  682. (r'(\\(?=\n)|[\[\](){}/:@])', Punctuation),
  683. (r'\s+|\n', Whitespace),
  684. ],
  685. }
  686. class FlatlineLexer(RegexLexer):
  687. """
  688. Lexer for `Flatline <https://github.com/bigmlcom/flatline>`_ expressions.
  689. .. versionadded:: 2.2
  690. """
  691. name = 'Flatline'
  692. aliases = ['flatline']
  693. filenames = []
  694. mimetypes = ['text/x-flatline']
  695. special_forms = ('let',)
  696. builtins = (
  697. "!=", "*", "+", "-", "<", "<=", "=", ">", ">=", "abs", "acos", "all",
  698. "all-but", "all-with-defaults", "all-with-numeric-default", "and",
  699. "asin", "atan", "avg", "avg-window", "bin-center", "bin-count", "call",
  700. "category-count", "ceil", "cond", "cond-window", "cons", "cos", "cosh",
  701. "count", "diff-window", "div", "ensure-value", "ensure-weighted-value",
  702. "epoch", "epoch-day", "epoch-fields", "epoch-hour", "epoch-millisecond",
  703. "epoch-minute", "epoch-month", "epoch-second", "epoch-weekday",
  704. "epoch-year", "exp", "f", "field", "field-prop", "fields", "filter",
  705. "first", "floor", "head", "if", "in", "integer", "language", "length",
  706. "levenshtein", "linear-regression", "list", "ln", "log", "log10", "map",
  707. "matches", "matches?", "max", "maximum", "md5", "mean", "median", "min",
  708. "minimum", "missing", "missing-count", "missing?", "missing_count",
  709. "mod", "mode", "normalize", "not", "nth", "occurrences", "or",
  710. "percentile", "percentile-label", "population", "population-fraction",
  711. "pow", "preferred", "preferred?", "quantile-label", "rand", "rand-int",
  712. "random-value", "re-quote", "real", "replace", "replace-first", "rest",
  713. "round", "row-number", "segment-label", "sha1", "sha256", "sin", "sinh",
  714. "sqrt", "square", "standard-deviation", "standard_deviation", "str",
  715. "subs", "sum", "sum-squares", "sum-window", "sum_squares", "summary",
  716. "summary-no", "summary-str", "tail", "tan", "tanh", "to-degrees",
  717. "to-radians", "variance", "vectorize", "weighted-random-value", "window",
  718. "winnow", "within-percentiles?", "z-score",
  719. )
  720. valid_name = r'(?!#)[\w!$%*+<=>?/.#-]+'
  721. tokens = {
  722. 'root': [
  723. # whitespaces - usually not relevant
  724. (r'[,\s]+', Text),
  725. # numbers
  726. (r'-?\d+\.\d+', Number.Float),
  727. (r'-?\d+', Number.Integer),
  728. (r'0x-?[a-f\d]+', Number.Hex),
  729. # strings, symbols and characters
  730. (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
  731. (r"\\(.|[a-z]+)", String.Char),
  732. # expression template placeholder
  733. (r'_', String.Symbol),
  734. # highlight the special forms
  735. (words(special_forms, suffix=' '), Keyword),
  736. # highlight the builtins
  737. (words(builtins, suffix=' '), Name.Builtin),
  738. # the remaining functions
  739. (r'(?<=\()' + valid_name, Name.Function),
  740. # find the remaining variables
  741. (valid_name, Name.Variable),
  742. # parentheses
  743. (r'(\(|\))', Punctuation),
  744. ],
  745. }
  746. class SnowballLexer(ExtendedRegexLexer):
  747. """
  748. Lexer for `Snowball <http://snowballstem.org/>`_ source code.
  749. .. versionadded:: 2.2
  750. """
  751. name = 'Snowball'
  752. aliases = ['snowball']
  753. filenames = ['*.sbl']
  754. _ws = r'\n\r\t '
  755. def __init__(self, **options):
  756. self._reset_stringescapes()
  757. ExtendedRegexLexer.__init__(self, **options)
  758. def _reset_stringescapes(self):
  759. self._start = "'"
  760. self._end = "'"
  761. def _string(do_string_first):
  762. def callback(lexer, match, ctx):
  763. s = match.start()
  764. text = match.group()
  765. string = re.compile(r'([^%s]*)(.)' % re.escape(lexer._start)).match
  766. escape = re.compile(r'([^%s]*)(.)' % re.escape(lexer._end)).match
  767. pos = 0
  768. do_string = do_string_first
  769. while pos < len(text):
  770. if do_string:
  771. match = string(text, pos)
  772. yield s + match.start(1), String.Single, match.group(1)
  773. if match.group(2) == "'":
  774. yield s + match.start(2), String.Single, match.group(2)
  775. ctx.stack.pop()
  776. break
  777. yield s + match.start(2), String.Escape, match.group(2)
  778. pos = match.end()
  779. match = escape(text, pos)
  780. yield s + match.start(), String.Escape, match.group()
  781. if match.group(2) != lexer._end:
  782. ctx.stack[-1] = 'escape'
  783. break
  784. pos = match.end()
  785. do_string = True
  786. ctx.pos = s + match.end()
  787. return callback
  788. def _stringescapes(lexer, match, ctx):
  789. lexer._start = match.group(3)
  790. lexer._end = match.group(5)
  791. return bygroups(Keyword.Reserved, Text, String.Escape, Text,
  792. String.Escape)(lexer, match, ctx)
  793. tokens = {
  794. 'root': [
  795. (words(('len', 'lenof'), suffix=r'\b'), Operator.Word),
  796. include('root1'),
  797. ],
  798. 'root1': [
  799. (r'[%s]+' % _ws, Text),
  800. (r'\d+', Number.Integer),
  801. (r"'", String.Single, 'string'),
  802. (r'[()]', Punctuation),
  803. (r'/\*[\w\W]*?\*/', Comment.Multiline),
  804. (r'//.*', Comment.Single),
  805. (r'[!*+\-/<=>]=|[-=]>|<[+-]|[$*+\-/<=>?\[\]]', Operator),
  806. (words(('as', 'get', 'hex', 'among', 'define', 'decimal',
  807. 'backwardmode'), suffix=r'\b'),
  808. Keyword.Reserved),
  809. (words(('strings', 'booleans', 'integers', 'routines', 'externals',
  810. 'groupings'), suffix=r'\b'),
  811. Keyword.Reserved, 'declaration'),
  812. (words(('do', 'or', 'and', 'for', 'hop', 'non', 'not', 'set', 'try',
  813. 'fail', 'goto', 'loop', 'next', 'test', 'true',
  814. 'false', 'unset', 'atmark', 'attach', 'delete', 'gopast',
  815. 'insert', 'repeat', 'sizeof', 'tomark', 'atleast',
  816. 'atlimit', 'reverse', 'setmark', 'tolimit', 'setlimit',
  817. 'backwards', 'substring'), suffix=r'\b'),
  818. Operator.Word),
  819. (words(('size', 'limit', 'cursor', 'maxint', 'minint'),
  820. suffix=r'\b'),
  821. Name.Builtin),
  822. (r'(stringdef\b)([%s]*)([^%s]+)' % (_ws, _ws),
  823. bygroups(Keyword.Reserved, Text, String.Escape)),
  824. (r'(stringescapes\b)([%s]*)(.)([%s]*)(.)' % (_ws, _ws),
  825. _stringescapes),
  826. (r'[A-Za-z]\w*', Name),
  827. ],
  828. 'declaration': [
  829. (r'\)', Punctuation, '#pop'),
  830. (words(('len', 'lenof'), suffix=r'\b'), Name,
  831. ('root1', 'declaration')),
  832. include('root1'),
  833. ],
  834. 'string': [
  835. (r"[^']*'", _string(True)),
  836. ],
  837. 'escape': [
  838. (r"[^']*'", _string(False)),
  839. ],
  840. }
  841. def get_tokens_unprocessed(self, text=None, context=None):
  842. self._reset_stringescapes()
  843. return ExtendedRegexLexer.get_tokens_unprocessed(self, text, context)