php.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.lexers.php
  4. ~~~~~~~~~~~~~~~~~~~
  5. Lexers for PHP and related languages.
  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 RegexLexer, include, bygroups, default, using, \
  11. this, words
  12. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  13. Number, Punctuation, Other
  14. from pygments.util import get_bool_opt, get_list_opt, iteritems, \
  15. shebang_matches
  16. __all__ = ['ZephirLexer', 'PhpLexer']
  17. class ZephirLexer(RegexLexer):
  18. """
  19. For `Zephir language <http://zephir-lang.com/>`_ source code.
  20. Zephir is a compiled high level language aimed
  21. to the creation of C-extensions for PHP.
  22. .. versionadded:: 2.0
  23. """
  24. name = 'Zephir'
  25. aliases = ['zephir']
  26. filenames = ['*.zep']
  27. zephir_keywords = ['fetch', 'echo', 'isset', 'empty']
  28. zephir_type = ['bit', 'bits', 'string']
  29. flags = re.DOTALL | re.MULTILINE
  30. tokens = {
  31. 'commentsandwhitespace': [
  32. (r'\s+', Text),
  33. (r'//.*?\n', Comment.Single),
  34. (r'/\*.*?\*/', Comment.Multiline)
  35. ],
  36. 'slashstartsregex': [
  37. include('commentsandwhitespace'),
  38. (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
  39. r'([gim]+\b|\B)', String.Regex, '#pop'),
  40. default('#pop')
  41. ],
  42. 'badregex': [
  43. (r'\n', Text, '#pop')
  44. ],
  45. 'root': [
  46. (r'^(?=\s|/|<!--)', Text, 'slashstartsregex'),
  47. include('commentsandwhitespace'),
  48. (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|'
  49. r'(<<|>>>?|==?|!=?|->|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'),
  50. (r'[{(\[;,]', Punctuation, 'slashstartsregex'),
  51. (r'[})\].]', Punctuation),
  52. (r'(for|in|while|do|break|return|continue|switch|case|default|if|else|loop|'
  53. r'require|inline|throw|try|catch|finally|new|delete|typeof|instanceof|void|'
  54. r'namespace|use|extends|this|fetch|isset|unset|echo|fetch|likely|unlikely|'
  55. r'empty)\b', Keyword, 'slashstartsregex'),
  56. (r'(var|let|with|function)\b', Keyword.Declaration, 'slashstartsregex'),
  57. (r'(abstract|boolean|bool|char|class|const|double|enum|export|extends|final|'
  58. r'native|goto|implements|import|int|string|interface|long|ulong|char|uchar|'
  59. r'float|unsigned|private|protected|public|short|static|self|throws|reverse|'
  60. r'transient|volatile)\b', Keyword.Reserved),
  61. (r'(true|false|null|undefined)\b', Keyword.Constant),
  62. (r'(Array|Boolean|Date|_REQUEST|_COOKIE|_SESSION|'
  63. r'_GET|_POST|_SERVER|this|stdClass|range|count|iterator|'
  64. r'window)\b', Name.Builtin),
  65. (r'[$a-zA-Z_][\w\\]*', Name.Other),
  66. (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
  67. (r'0x[0-9a-fA-F]+', Number.Hex),
  68. (r'[0-9]+', Number.Integer),
  69. (r'"(\\\\|\\"|[^"])*"', String.Double),
  70. (r"'(\\\\|\\'|[^'])*'", String.Single),
  71. ]
  72. }
  73. class PhpLexer(RegexLexer):
  74. """
  75. For `PHP <http://www.php.net/>`_ source code.
  76. For PHP embedded in HTML, use the `HtmlPhpLexer`.
  77. Additional options accepted:
  78. `startinline`
  79. If given and ``True`` the lexer starts highlighting with
  80. php code (i.e.: no starting ``<?php`` required). The default
  81. is ``False``.
  82. `funcnamehighlighting`
  83. If given and ``True``, highlight builtin function names
  84. (default: ``True``).
  85. `disabledmodules`
  86. If given, must be a list of module names whose function names
  87. should not be highlighted. By default all modules are highlighted
  88. except the special ``'unknown'`` module that includes functions
  89. that are known to php but are undocumented.
  90. To get a list of allowed modules have a look into the
  91. `_php_builtins` module:
  92. .. sourcecode:: pycon
  93. >>> from pygments.lexers._php_builtins import MODULES
  94. >>> MODULES.keys()
  95. ['PHP Options/Info', 'Zip', 'dba', ...]
  96. In fact the names of those modules match the module names from
  97. the php documentation.
  98. """
  99. name = 'PHP'
  100. aliases = ['php', 'php3', 'php4', 'php5']
  101. filenames = ['*.php', '*.php[345]', '*.inc']
  102. mimetypes = ['text/x-php']
  103. # Note that a backslash is included in the following two patterns
  104. # PHP uses a backslash as a namespace separator
  105. _ident_char = r'[\\\w]|[^\x00-\x7f]'
  106. _ident_begin = r'(?:[\\_a-z]|[^\x00-\x7f])'
  107. _ident_end = r'(?:' + _ident_char + ')*'
  108. _ident_inner = _ident_begin + _ident_end
  109. flags = re.IGNORECASE | re.DOTALL | re.MULTILINE
  110. tokens = {
  111. 'root': [
  112. (r'<\?(php)?', Comment.Preproc, 'php'),
  113. (r'[^<]+', Other),
  114. (r'<', Other)
  115. ],
  116. 'php': [
  117. (r'\?>', Comment.Preproc, '#pop'),
  118. (r'(<<<)([\'"]?)(' + _ident_inner + r')(\2\n.*?\n\s*)(\3)(;?)(\n)',
  119. bygroups(String, String, String.Delimiter, String, String.Delimiter,
  120. Punctuation, Text)),
  121. (r'\s+', Text),
  122. (r'#.*?\n', Comment.Single),
  123. (r'//.*?\n', Comment.Single),
  124. # put the empty comment here, it is otherwise seen as
  125. # the start of a docstring
  126. (r'/\*\*/', Comment.Multiline),
  127. (r'/\*\*.*?\*/', String.Doc),
  128. (r'/\*.*?\*/', Comment.Multiline),
  129. (r'(->|::)(\s*)(' + _ident_inner + ')',
  130. bygroups(Operator, Text, Name.Attribute)),
  131. (r'[~!%^&*+=|:.<>/@-]+', Operator),
  132. (r'\?', Operator), # don't add to the charclass above!
  133. (r'[\[\]{}();,]+', Punctuation),
  134. (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'),
  135. (r'(function)(\s*)(?=\()', bygroups(Keyword, Text)),
  136. (r'(function)(\s+)(&?)(\s*)',
  137. bygroups(Keyword, Text, Operator, Text), 'functionname'),
  138. (r'(const)(\s+)(' + _ident_inner + ')',
  139. bygroups(Keyword, Text, Name.Constant)),
  140. (r'(and|E_PARSE|old_function|E_ERROR|or|as|E_WARNING|parent|'
  141. r'eval|PHP_OS|break|exit|case|extends|PHP_VERSION|cfunction|'
  142. r'FALSE|print|for|require|continue|foreach|require_once|'
  143. r'declare|return|default|static|do|switch|die|stdClass|'
  144. r'echo|else|TRUE|elseif|var|empty|if|xor|enddeclare|include|'
  145. r'virtual|endfor|include_once|while|endforeach|global|'
  146. r'endif|list|endswitch|new|endwhile|not|'
  147. r'array|E_ALL|NULL|final|php_user_filter|interface|'
  148. r'implements|public|private|protected|abstract|clone|try|'
  149. r'catch|throw|this|use|namespace|trait|yield|'
  150. r'finally)\b', Keyword),
  151. (r'(true|false|null)\b', Keyword.Constant),
  152. include('magicconstants'),
  153. (r'\$\{\$+' + _ident_inner + r'\}', Name.Variable),
  154. (r'\$+' + _ident_inner, Name.Variable),
  155. (_ident_inner, Name.Other),
  156. (r'(\d+\.\d*|\d*\.\d+)(e[+-]?[0-9]+)?', Number.Float),
  157. (r'\d+e[+-]?[0-9]+', Number.Float),
  158. (r'0[0-7]+', Number.Oct),
  159. (r'0x[a-f0-9]+', Number.Hex),
  160. (r'\d+', Number.Integer),
  161. (r'0b[01]+', Number.Bin),
  162. (r"'([^'\\]*(?:\\.[^'\\]*)*)'", String.Single),
  163. (r'`([^`\\]*(?:\\.[^`\\]*)*)`', String.Backtick),
  164. (r'"', String.Double, 'string'),
  165. ],
  166. 'magicfuncs': [
  167. # source: http://php.net/manual/en/language.oop5.magic.php
  168. (words((
  169. '__construct', '__destruct', '__call', '__callStatic', '__get', '__set',
  170. '__isset', '__unset', '__sleep', '__wakeup', '__toString', '__invoke',
  171. '__set_state', '__clone', '__debugInfo',), suffix=r'\b'),
  172. Name.Function.Magic),
  173. ],
  174. 'magicconstants': [
  175. # source: http://php.net/manual/en/language.constants.predefined.php
  176. (words((
  177. '__LINE__', '__FILE__', '__DIR__', '__FUNCTION__', '__CLASS__',
  178. '__TRAIT__', '__METHOD__', '__NAMESPACE__',),
  179. suffix=r'\b'),
  180. Name.Constant),
  181. ],
  182. 'classname': [
  183. (_ident_inner, Name.Class, '#pop')
  184. ],
  185. 'functionname': [
  186. include('magicfuncs'),
  187. (_ident_inner, Name.Function, '#pop'),
  188. default('#pop')
  189. ],
  190. 'string': [
  191. (r'"', String.Double, '#pop'),
  192. (r'[^{$"\\]+', String.Double),
  193. (r'\\([nrt"$\\]|[0-7]{1,3}|x[0-9a-f]{1,2})', String.Escape),
  194. (r'\$' + _ident_inner + r'(\[\S+?\]|->' + _ident_inner + ')?',
  195. String.Interpol),
  196. (r'(\{\$\{)(.*?)(\}\})',
  197. bygroups(String.Interpol, using(this, _startinline=True),
  198. String.Interpol)),
  199. (r'(\{)(\$.*?)(\})',
  200. bygroups(String.Interpol, using(this, _startinline=True),
  201. String.Interpol)),
  202. (r'(\$\{)(\S+)(\})',
  203. bygroups(String.Interpol, Name.Variable, String.Interpol)),
  204. (r'[${\\]', String.Double)
  205. ],
  206. }
  207. def __init__(self, **options):
  208. self.funcnamehighlighting = get_bool_opt(
  209. options, 'funcnamehighlighting', True)
  210. self.disabledmodules = get_list_opt(
  211. options, 'disabledmodules', ['unknown'])
  212. self.startinline = get_bool_opt(options, 'startinline', False)
  213. # private option argument for the lexer itself
  214. if '_startinline' in options:
  215. self.startinline = options.pop('_startinline')
  216. # collect activated functions in a set
  217. self._functions = set()
  218. if self.funcnamehighlighting:
  219. from pygments.lexers._php_builtins import MODULES
  220. for key, value in iteritems(MODULES):
  221. if key not in self.disabledmodules:
  222. self._functions.update(value)
  223. RegexLexer.__init__(self, **options)
  224. def get_tokens_unprocessed(self, text):
  225. stack = ['root']
  226. if self.startinline:
  227. stack.append('php')
  228. for index, token, value in \
  229. RegexLexer.get_tokens_unprocessed(self, text, stack):
  230. if token is Name.Other:
  231. if value in self._functions:
  232. yield index, Name.Builtin, value
  233. continue
  234. yield index, token, value
  235. def analyse_text(text):
  236. if shebang_matches(text, r'php'):
  237. return True
  238. rv = 0.0
  239. if re.search(r'<\?(?!xml)', text):
  240. rv += 0.3
  241. return rv