objective.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. """
  2. pygments.lexers.objective
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for Objective-C family languages.
  5. :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. from pygments.lexer import RegexLexer, include, bygroups, using, this, words, \
  10. inherit, default
  11. from pygments.token import Text, Keyword, Name, String, Operator, \
  12. Number, Punctuation, Literal, Comment
  13. from pygments.lexers.c_cpp import CLexer, CppLexer
  14. __all__ = ['ObjectiveCLexer', 'ObjectiveCppLexer', 'LogosLexer', 'SwiftLexer']
  15. def objective(baselexer):
  16. """
  17. Generate a subclass of baselexer that accepts the Objective-C syntax
  18. extensions.
  19. """
  20. # Have to be careful not to accidentally match JavaDoc/Doxygen syntax here,
  21. # since that's quite common in ordinary C/C++ files. It's OK to match
  22. # JavaDoc/Doxygen keywords that only apply to Objective-C, mind.
  23. #
  24. # The upshot of this is that we CANNOT match @class or @interface
  25. _oc_keywords = re.compile(r'@(?:end|implementation|protocol)')
  26. # Matches [ <ws>? identifier <ws> ( identifier <ws>? ] | identifier? : )
  27. # (note the identifier is *optional* when there is a ':'!)
  28. _oc_message = re.compile(r'\[\s*[a-zA-Z_]\w*\s+'
  29. r'(?:[a-zA-Z_]\w*\s*\]|'
  30. r'(?:[a-zA-Z_]\w*)?:)')
  31. class GeneratedObjectiveCVariant(baselexer):
  32. """
  33. Implements Objective-C syntax on top of an existing C family lexer.
  34. """
  35. tokens = {
  36. 'statements': [
  37. (r'@"', String, 'string'),
  38. (r'@(YES|NO)', Number),
  39. (r"@'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char),
  40. (r'@(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float),
  41. (r'@(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
  42. (r'@0x[0-9a-fA-F]+[Ll]?', Number.Hex),
  43. (r'@0[0-7]+[Ll]?', Number.Oct),
  44. (r'@\d+[Ll]?', Number.Integer),
  45. (r'@\(', Literal, 'literal_number'),
  46. (r'@\[', Literal, 'literal_array'),
  47. (r'@\{', Literal, 'literal_dictionary'),
  48. (words((
  49. '@selector', '@private', '@protected', '@public', '@encode',
  50. '@synchronized', '@try', '@throw', '@catch', '@finally',
  51. '@end', '@property', '@synthesize', '__bridge', '__bridge_transfer',
  52. '__autoreleasing', '__block', '__weak', '__strong', 'weak', 'strong',
  53. 'copy', 'retain', 'assign', 'unsafe_unretained', 'atomic', 'nonatomic',
  54. 'readonly', 'readwrite', 'setter', 'getter', 'typeof', 'in',
  55. 'out', 'inout', 'release', 'class', '@dynamic', '@optional',
  56. '@required', '@autoreleasepool', '@import'), suffix=r'\b'),
  57. Keyword),
  58. (words(('id', 'instancetype', 'Class', 'IMP', 'SEL', 'BOOL',
  59. 'IBOutlet', 'IBAction', 'unichar'), suffix=r'\b'),
  60. Keyword.Type),
  61. (r'@(true|false|YES|NO)\n', Name.Builtin),
  62. (r'(YES|NO|nil|self|super)\b', Name.Builtin),
  63. # Carbon types
  64. (r'(Boolean|UInt8|SInt8|UInt16|SInt16|UInt32|SInt32)\b', Keyword.Type),
  65. # Carbon built-ins
  66. (r'(TRUE|FALSE)\b', Name.Builtin),
  67. (r'(@interface|@implementation)(\s+)', bygroups(Keyword, Text),
  68. ('#pop', 'oc_classname')),
  69. (r'(@class|@protocol)(\s+)', bygroups(Keyword, Text),
  70. ('#pop', 'oc_forward_classname')),
  71. # @ can also prefix other expressions like @{...} or @(...)
  72. (r'@', Punctuation),
  73. inherit,
  74. ],
  75. 'oc_classname': [
  76. # interface definition that inherits
  77. (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?(\s*)(\{)',
  78. bygroups(Name.Class, Text, Name.Class, Text, Punctuation),
  79. ('#pop', 'oc_ivars')),
  80. (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?',
  81. bygroups(Name.Class, Text, Name.Class), '#pop'),
  82. # interface definition for a category
  83. (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))(\s*)(\{)',
  84. bygroups(Name.Class, Text, Name.Label, Text, Punctuation),
  85. ('#pop', 'oc_ivars')),
  86. (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))',
  87. bygroups(Name.Class, Text, Name.Label), '#pop'),
  88. # simple interface / implementation
  89. (r'([a-zA-Z$_][\w$]*)(\s*)(\{)',
  90. bygroups(Name.Class, Text, Punctuation), ('#pop', 'oc_ivars')),
  91. (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop')
  92. ],
  93. 'oc_forward_classname': [
  94. (r'([a-zA-Z$_][\w$]*)(\s*,\s*)',
  95. bygroups(Name.Class, Text), 'oc_forward_classname'),
  96. (r'([a-zA-Z$_][\w$]*)(\s*;?)',
  97. bygroups(Name.Class, Text), '#pop')
  98. ],
  99. 'oc_ivars': [
  100. include('whitespace'),
  101. include('statements'),
  102. (';', Punctuation),
  103. (r'\{', Punctuation, '#push'),
  104. (r'\}', Punctuation, '#pop'),
  105. ],
  106. 'root': [
  107. # methods
  108. (r'^([-+])(\s*)' # method marker
  109. r'(\(.*?\))?(\s*)' # return type
  110. r'([a-zA-Z$_][\w$]*:?)', # begin of method name
  111. bygroups(Punctuation, Text, using(this),
  112. Text, Name.Function),
  113. 'method'),
  114. inherit,
  115. ],
  116. 'method': [
  117. include('whitespace'),
  118. # TODO unsure if ellipses are allowed elsewhere, see
  119. # discussion in Issue 789
  120. (r',', Punctuation),
  121. (r'\.\.\.', Punctuation),
  122. (r'(\(.*?\))(\s*)([a-zA-Z$_][\w$]*)',
  123. bygroups(using(this), Text, Name.Variable)),
  124. (r'[a-zA-Z$_][\w$]*:', Name.Function),
  125. (';', Punctuation, '#pop'),
  126. (r'\{', Punctuation, 'function'),
  127. default('#pop'),
  128. ],
  129. 'literal_number': [
  130. (r'\(', Punctuation, 'literal_number_inner'),
  131. (r'\)', Literal, '#pop'),
  132. include('statement'),
  133. ],
  134. 'literal_number_inner': [
  135. (r'\(', Punctuation, '#push'),
  136. (r'\)', Punctuation, '#pop'),
  137. include('statement'),
  138. ],
  139. 'literal_array': [
  140. (r'\[', Punctuation, 'literal_array_inner'),
  141. (r'\]', Literal, '#pop'),
  142. include('statement'),
  143. ],
  144. 'literal_array_inner': [
  145. (r'\[', Punctuation, '#push'),
  146. (r'\]', Punctuation, '#pop'),
  147. include('statement'),
  148. ],
  149. 'literal_dictionary': [
  150. (r'\}', Literal, '#pop'),
  151. include('statement'),
  152. ],
  153. }
  154. def analyse_text(text):
  155. if _oc_keywords.search(text):
  156. return 1.0
  157. elif '@"' in text: # strings
  158. return 0.8
  159. elif re.search('@[0-9]+', text):
  160. return 0.7
  161. elif _oc_message.search(text):
  162. return 0.8
  163. return 0
  164. def get_tokens_unprocessed(self, text, stack=('root',)):
  165. from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \
  166. COCOA_PROTOCOLS, COCOA_PRIMITIVES
  167. for index, token, value in \
  168. baselexer.get_tokens_unprocessed(self, text, stack):
  169. if token is Name or token is Name.Class:
  170. if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \
  171. or value in COCOA_PRIMITIVES:
  172. token = Name.Builtin.Pseudo
  173. yield index, token, value
  174. return GeneratedObjectiveCVariant
  175. class ObjectiveCLexer(objective(CLexer)):
  176. """
  177. For Objective-C source code with preprocessor directives.
  178. """
  179. name = 'Objective-C'
  180. url = 'https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html'
  181. aliases = ['objective-c', 'objectivec', 'obj-c', 'objc']
  182. filenames = ['*.m', '*.h']
  183. mimetypes = ['text/x-objective-c']
  184. version_added = ''
  185. priority = 0.05 # Lower than C
  186. class ObjectiveCppLexer(objective(CppLexer)):
  187. """
  188. For Objective-C++ source code with preprocessor directives.
  189. """
  190. name = 'Objective-C++'
  191. aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++']
  192. filenames = ['*.mm', '*.hh']
  193. mimetypes = ['text/x-objective-c++']
  194. version_added = ''
  195. priority = 0.05 # Lower than C++
  196. class LogosLexer(ObjectiveCppLexer):
  197. """
  198. For Logos + Objective-C source code with preprocessor directives.
  199. """
  200. name = 'Logos'
  201. aliases = ['logos']
  202. filenames = ['*.x', '*.xi', '*.xm', '*.xmi']
  203. mimetypes = ['text/x-logos']
  204. version_added = '1.6'
  205. priority = 0.25
  206. tokens = {
  207. 'statements': [
  208. (r'(%orig|%log)\b', Keyword),
  209. (r'(%c)\b(\()(\s*)([a-zA-Z$_][\w$]*)(\s*)(\))',
  210. bygroups(Keyword, Punctuation, Text, Name.Class, Text, Punctuation)),
  211. (r'(%init)\b(\()',
  212. bygroups(Keyword, Punctuation), 'logos_init_directive'),
  213. (r'(%init)(?=\s*;)', bygroups(Keyword)),
  214. (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)',
  215. bygroups(Keyword, Text, Name.Class), '#pop'),
  216. (r'(%subclass)(\s+)', bygroups(Keyword, Text),
  217. ('#pop', 'logos_classname')),
  218. inherit,
  219. ],
  220. 'logos_init_directive': [
  221. (r'\s+', Text),
  222. (',', Punctuation, ('logos_init_directive', '#pop')),
  223. (r'([a-zA-Z$_][\w$]*)(\s*)(=)(\s*)([^);]*)',
  224. bygroups(Name.Class, Text, Punctuation, Text, Text)),
  225. (r'([a-zA-Z$_][\w$]*)', Name.Class),
  226. (r'\)', Punctuation, '#pop'),
  227. ],
  228. 'logos_classname': [
  229. (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?',
  230. bygroups(Name.Class, Text, Name.Class), '#pop'),
  231. (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop')
  232. ],
  233. 'root': [
  234. (r'(%subclass)(\s+)', bygroups(Keyword, Text),
  235. 'logos_classname'),
  236. (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)',
  237. bygroups(Keyword, Text, Name.Class)),
  238. (r'(%config)(\s*\(\s*)(\w+)(\s*=)(.*?)(\)\s*)',
  239. bygroups(Keyword, Text, Name.Variable, Text, String, Text)),
  240. (r'(%ctor)(\s*)(\{)', bygroups(Keyword, Text, Punctuation),
  241. 'function'),
  242. (r'(%new)(\s*)(\()(.*?)(\))',
  243. bygroups(Keyword, Text, Keyword, String, Keyword)),
  244. (r'(\s*)(%end)(\s*)', bygroups(Text, Keyword, Text)),
  245. inherit,
  246. ],
  247. }
  248. _logos_keywords = re.compile(r'%(?:hook|ctor|init|c\()')
  249. def analyse_text(text):
  250. if LogosLexer._logos_keywords.search(text):
  251. return 1.0
  252. return 0
  253. class SwiftLexer(RegexLexer):
  254. """
  255. For Swift source.
  256. """
  257. name = 'Swift'
  258. url = 'https://www.swift.org/'
  259. filenames = ['*.swift']
  260. aliases = ['swift']
  261. mimetypes = ['text/x-swift']
  262. version_added = '2.0'
  263. tokens = {
  264. 'root': [
  265. # Whitespace and Comments
  266. (r'\n', Text),
  267. (r'\s+', Text),
  268. (r'//', Comment.Single, 'comment-single'),
  269. (r'/\*', Comment.Multiline, 'comment-multi'),
  270. (r'#(if|elseif|else|endif|available)\b', Comment.Preproc, 'preproc'),
  271. # Keywords
  272. include('keywords'),
  273. # Global Types
  274. (words((
  275. 'Array', 'AutoreleasingUnsafeMutablePointer', 'BidirectionalReverseView',
  276. 'Bit', 'Bool', 'CFunctionPointer', 'COpaquePointer', 'CVaListPointer',
  277. 'Character', 'ClosedInterval', 'CollectionOfOne', 'ContiguousArray',
  278. 'Dictionary', 'DictionaryGenerator', 'DictionaryIndex', 'Double',
  279. 'EmptyCollection', 'EmptyGenerator', 'EnumerateGenerator',
  280. 'EnumerateSequence', 'FilterCollectionView',
  281. 'FilterCollectionViewIndex', 'FilterGenerator', 'FilterSequenceView',
  282. 'Float', 'Float80', 'FloatingPointClassification', 'GeneratorOf',
  283. 'GeneratorOfOne', 'GeneratorSequence', 'HalfOpenInterval', 'HeapBuffer',
  284. 'HeapBufferStorage', 'ImplicitlyUnwrappedOptional', 'IndexingGenerator',
  285. 'Int', 'Int16', 'Int32', 'Int64', 'Int8', 'LazyBidirectionalCollection',
  286. 'LazyForwardCollection', 'LazyRandomAccessCollection',
  287. 'LazySequence', 'MapCollectionView', 'MapSequenceGenerator',
  288. 'MapSequenceView', 'MirrorDisposition', 'ObjectIdentifier', 'OnHeap',
  289. 'Optional', 'PermutationGenerator', 'QuickLookObject',
  290. 'RandomAccessReverseView', 'Range', 'RangeGenerator', 'RawByte', 'Repeat',
  291. 'ReverseBidirectionalIndex', 'ReverseRandomAccessIndex', 'SequenceOf',
  292. 'SinkOf', 'Slice', 'StaticString', 'StrideThrough', 'StrideThroughGenerator',
  293. 'StrideTo', 'StrideToGenerator', 'String', 'UInt', 'UInt16', 'UInt32',
  294. 'UInt64', 'UInt8', 'UTF16', 'UTF32', 'UTF8', 'UnicodeDecodingResult',
  295. 'UnicodeScalar', 'Unmanaged', 'UnsafeBufferPointer',
  296. 'UnsafeBufferPointerGenerator', 'UnsafeMutableBufferPointer',
  297. 'UnsafeMutablePointer', 'UnsafePointer', 'Zip2', 'ZipGenerator2',
  298. # Protocols
  299. 'AbsoluteValuable', 'AnyObject', 'ArrayLiteralConvertible',
  300. 'BidirectionalIndexType', 'BitwiseOperationsType',
  301. 'BooleanLiteralConvertible', 'BooleanType', 'CVarArgType',
  302. 'CollectionType', 'Comparable', 'DebugPrintable',
  303. 'DictionaryLiteralConvertible', 'Equatable',
  304. 'ExtendedGraphemeClusterLiteralConvertible',
  305. 'ExtensibleCollectionType', 'FloatLiteralConvertible',
  306. 'FloatingPointType', 'ForwardIndexType', 'GeneratorType', 'Hashable',
  307. 'IntegerArithmeticType', 'IntegerLiteralConvertible', 'IntegerType',
  308. 'IntervalType', 'MirrorType', 'MutableCollectionType', 'MutableSliceable',
  309. 'NilLiteralConvertible', 'OutputStreamType', 'Printable',
  310. 'RandomAccessIndexType', 'RangeReplaceableCollectionType',
  311. 'RawOptionSetType', 'RawRepresentable', 'Reflectable', 'SequenceType',
  312. 'SignedIntegerType', 'SignedNumberType', 'SinkType', 'Sliceable',
  313. 'Streamable', 'Strideable', 'StringInterpolationConvertible',
  314. 'StringLiteralConvertible', 'UnicodeCodecType',
  315. 'UnicodeScalarLiteralConvertible', 'UnsignedIntegerType',
  316. '_ArrayBufferType', '_BidirectionalIndexType', '_CocoaStringType',
  317. '_CollectionType', '_Comparable', '_ExtensibleCollectionType',
  318. '_ForwardIndexType', '_Incrementable', '_IntegerArithmeticType',
  319. '_IntegerType', '_ObjectiveCBridgeable', '_RandomAccessIndexType',
  320. '_RawOptionSetType', '_SequenceType', '_Sequence_Type',
  321. '_SignedIntegerType', '_SignedNumberType', '_Sliceable', '_Strideable',
  322. '_SwiftNSArrayRequiredOverridesType', '_SwiftNSArrayType',
  323. '_SwiftNSCopyingType', '_SwiftNSDictionaryRequiredOverridesType',
  324. '_SwiftNSDictionaryType', '_SwiftNSEnumeratorType',
  325. '_SwiftNSFastEnumerationType', '_SwiftNSStringRequiredOverridesType',
  326. '_SwiftNSStringType', '_UnsignedIntegerType',
  327. # Variables
  328. 'C_ARGC', 'C_ARGV', 'Process',
  329. # Typealiases
  330. 'Any', 'AnyClass', 'BooleanLiteralType', 'CBool', 'CChar', 'CChar16',
  331. 'CChar32', 'CDouble', 'CFloat', 'CInt', 'CLong', 'CLongLong', 'CShort',
  332. 'CSignedChar', 'CUnsignedInt', 'CUnsignedLong', 'CUnsignedShort',
  333. 'CWideChar', 'ExtendedGraphemeClusterType', 'Float32', 'Float64',
  334. 'FloatLiteralType', 'IntMax', 'IntegerLiteralType', 'StringLiteralType',
  335. 'UIntMax', 'UWord', 'UnicodeScalarType', 'Void', 'Word',
  336. # Foundation/Cocoa
  337. 'NSErrorPointer', 'NSObjectProtocol', 'Selector'), suffix=r'\b'),
  338. Name.Builtin),
  339. # Functions
  340. (words((
  341. 'abs', 'advance', 'alignof', 'alignofValue', 'assert', 'assertionFailure',
  342. 'contains', 'count', 'countElements', 'debugPrint', 'debugPrintln',
  343. 'distance', 'dropFirst', 'dropLast', 'dump', 'enumerate', 'equal',
  344. 'extend', 'fatalError', 'filter', 'find', 'first', 'getVaList', 'indices',
  345. 'insert', 'isEmpty', 'join', 'last', 'lazy', 'lexicographicalCompare',
  346. 'map', 'max', 'maxElement', 'min', 'minElement', 'numericCast', 'overlaps',
  347. 'partition', 'precondition', 'preconditionFailure', 'prefix', 'print',
  348. 'println', 'reduce', 'reflect', 'removeAll', 'removeAtIndex', 'removeLast',
  349. 'removeRange', 'reverse', 'sizeof', 'sizeofValue', 'sort', 'sorted',
  350. 'splice', 'split', 'startsWith', 'stride', 'strideof', 'strideofValue',
  351. 'suffix', 'swap', 'toDebugString', 'toString', 'transcode',
  352. 'underestimateCount', 'unsafeAddressOf', 'unsafeBitCast', 'unsafeDowncast',
  353. 'withExtendedLifetime', 'withUnsafeMutablePointer',
  354. 'withUnsafeMutablePointers', 'withUnsafePointer', 'withUnsafePointers',
  355. 'withVaList'), suffix=r'\b'),
  356. Name.Builtin.Pseudo),
  357. # Implicit Block Variables
  358. (r'\$\d+', Name.Variable),
  359. # Binary Literal
  360. (r'0b[01_]+', Number.Bin),
  361. # Octal Literal
  362. (r'0o[0-7_]+', Number.Oct),
  363. # Hexadecimal Literal
  364. (r'0x[0-9a-fA-F_]+', Number.Hex),
  365. # Decimal Literal
  366. (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|'
  367. r'\.[0-9_]*|[eE][+\-]?[0-9_]+)', Number.Float),
  368. (r'[0-9][0-9_]*', Number.Integer),
  369. # String Literal
  370. (r'"""', String, 'string-multi'),
  371. (r'"', String, 'string'),
  372. # Operators and Punctuation
  373. (r'[(){}\[\].,:;=@#`?]|->|[<&?](?=\w)|(?<=\w)[>!?]', Punctuation),
  374. (r'[/=\-+!*%<>&|^?~]+', Operator),
  375. # Identifier
  376. (r'[a-zA-Z_]\w*', Name)
  377. ],
  378. 'keywords': [
  379. (words((
  380. 'as', 'async', 'await', 'break', 'case', 'catch', 'continue', 'default', 'defer',
  381. 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'is',
  382. 'repeat', 'return', '#selector', 'switch', 'throw', 'try',
  383. 'where', 'while'), suffix=r'\b'),
  384. Keyword),
  385. (r'@availability\([^)]+\)', Keyword.Reserved),
  386. (words((
  387. 'associativity', 'convenience', 'dynamic', 'didSet', 'final',
  388. 'get', 'indirect', 'infix', 'inout', 'lazy', 'left', 'mutating',
  389. 'none', 'nonmutating', 'optional', 'override', 'postfix',
  390. 'precedence', 'prefix', 'Protocol', 'required', 'rethrows',
  391. 'right', 'set', 'throws', 'Type', 'unowned', 'weak', 'willSet',
  392. '@availability', '@autoclosure', '@noreturn',
  393. '@NSApplicationMain', '@NSCopying', '@NSManaged', '@objc',
  394. '@UIApplicationMain', '@IBAction', '@IBDesignable',
  395. '@IBInspectable', '@IBOutlet'), suffix=r'\b'),
  396. Keyword.Reserved),
  397. (r'(as|dynamicType|false|is|nil|self|Self|super|true|__COLUMN__'
  398. r'|__FILE__|__FUNCTION__|__LINE__|_'
  399. r'|#(?:file|line|column|function))\b', Keyword.Constant),
  400. (r'import\b', Keyword.Declaration, 'module'),
  401. (r'(class|enum|extension|struct|protocol)(\s+)([a-zA-Z_]\w*)',
  402. bygroups(Keyword.Declaration, Text, Name.Class)),
  403. (r'(func)(\s+)([a-zA-Z_]\w*)',
  404. bygroups(Keyword.Declaration, Text, Name.Function)),
  405. (r'(var|let)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration,
  406. Text, Name.Variable)),
  407. (words((
  408. 'actor', 'associatedtype', 'class', 'deinit', 'enum', 'extension', 'func', 'import',
  409. 'init', 'internal', 'let', 'operator', 'private', 'protocol', 'public',
  410. 'static', 'struct', 'subscript', 'typealias', 'var'), suffix=r'\b'),
  411. Keyword.Declaration)
  412. ],
  413. 'comment': [
  414. (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):',
  415. Comment.Special)
  416. ],
  417. # Nested
  418. 'comment-single': [
  419. (r'\n', Text, '#pop'),
  420. include('comment'),
  421. (r'[^\n]', Comment.Single)
  422. ],
  423. 'comment-multi': [
  424. include('comment'),
  425. (r'[^*/]', Comment.Multiline),
  426. (r'/\*', Comment.Multiline, '#push'),
  427. (r'\*/', Comment.Multiline, '#pop'),
  428. (r'[*/]', Comment.Multiline)
  429. ],
  430. 'module': [
  431. (r'\n', Text, '#pop'),
  432. (r'[a-zA-Z_]\w*', Name.Class),
  433. include('root')
  434. ],
  435. 'preproc': [
  436. (r'\n', Text, '#pop'),
  437. include('keywords'),
  438. (r'[A-Za-z]\w*', Comment.Preproc),
  439. include('root')
  440. ],
  441. 'string': [
  442. (r'"', String, '#pop'),
  443. include("string-common"),
  444. ],
  445. 'string-multi': [
  446. (r'"""', String, '#pop'),
  447. include("string-common"),
  448. ],
  449. 'string-common': [
  450. (r'\\\(', String.Interpol, 'string-intp'),
  451. (r"""\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}"""
  452. r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}""", String.Escape),
  453. (r'[^\\"]+', String),
  454. (r'\\', String)
  455. ],
  456. 'string-intp': [
  457. (r'\(', String.Interpol, '#push'),
  458. (r'\)', String.Interpol, '#pop'),
  459. include('root')
  460. ]
  461. }
  462. def get_tokens_unprocessed(self, text):
  463. from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \
  464. COCOA_PROTOCOLS, COCOA_PRIMITIVES
  465. for index, token, value in \
  466. RegexLexer.get_tokens_unprocessed(self, text):
  467. if token is Name or token is Name.Class:
  468. if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \
  469. or value in COCOA_PRIMITIVES:
  470. token = Name.Builtin.Pseudo
  471. yield index, token, value