objective.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. """
  2. pygments.lexers.objective
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for Objective-C family 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, 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):
  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):
  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. aliases = ['objective-c', 'objectivec', 'obj-c', 'objc']
  181. filenames = ['*.m', '*.h']
  182. mimetypes = ['text/x-objective-c']
  183. priority = 0.05 # Lower than C
  184. class ObjectiveCppLexer(objective(CppLexer)):
  185. """
  186. For Objective-C++ source code with preprocessor directives.
  187. """
  188. name = 'Objective-C++'
  189. aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++']
  190. filenames = ['*.mm', '*.hh']
  191. mimetypes = ['text/x-objective-c++']
  192. priority = 0.05 # Lower than C++
  193. class LogosLexer(ObjectiveCppLexer):
  194. """
  195. For Logos + Objective-C source code with preprocessor directives.
  196. .. versionadded:: 1.6
  197. """
  198. name = 'Logos'
  199. aliases = ['logos']
  200. filenames = ['*.x', '*.xi', '*.xm', '*.xmi']
  201. mimetypes = ['text/x-logos']
  202. priority = 0.25
  203. tokens = {
  204. 'statements': [
  205. (r'(%orig|%log)\b', Keyword),
  206. (r'(%c)\b(\()(\s*)([a-zA-Z$_][\w$]*)(\s*)(\))',
  207. bygroups(Keyword, Punctuation, Text, Name.Class, Text, Punctuation)),
  208. (r'(%init)\b(\()',
  209. bygroups(Keyword, Punctuation), 'logos_init_directive'),
  210. (r'(%init)(?=\s*;)', bygroups(Keyword)),
  211. (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)',
  212. bygroups(Keyword, Text, Name.Class), '#pop'),
  213. (r'(%subclass)(\s+)', bygroups(Keyword, Text),
  214. ('#pop', 'logos_classname')),
  215. inherit,
  216. ],
  217. 'logos_init_directive': [
  218. (r'\s+', Text),
  219. (',', Punctuation, ('logos_init_directive', '#pop')),
  220. (r'([a-zA-Z$_][\w$]*)(\s*)(=)(\s*)([^);]*)',
  221. bygroups(Name.Class, Text, Punctuation, Text, Text)),
  222. (r'([a-zA-Z$_][\w$]*)', Name.Class),
  223. (r'\)', Punctuation, '#pop'),
  224. ],
  225. 'logos_classname': [
  226. (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?',
  227. bygroups(Name.Class, Text, Name.Class), '#pop'),
  228. (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop')
  229. ],
  230. 'root': [
  231. (r'(%subclass)(\s+)', bygroups(Keyword, Text),
  232. 'logos_classname'),
  233. (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)',
  234. bygroups(Keyword, Text, Name.Class)),
  235. (r'(%config)(\s*\(\s*)(\w+)(\s*=)(.*?)(\)\s*)',
  236. bygroups(Keyword, Text, Name.Variable, Text, String, Text)),
  237. (r'(%ctor)(\s*)(\{)', bygroups(Keyword, Text, Punctuation),
  238. 'function'),
  239. (r'(%new)(\s*)(\()(.*?)(\))',
  240. bygroups(Keyword, Text, Keyword, String, Keyword)),
  241. (r'(\s*)(%end)(\s*)', bygroups(Text, Keyword, Text)),
  242. inherit,
  243. ],
  244. }
  245. _logos_keywords = re.compile(r'%(?:hook|ctor|init|c\()')
  246. def analyse_text(text):
  247. if LogosLexer._logos_keywords.search(text):
  248. return 1.0
  249. return 0
  250. class SwiftLexer(RegexLexer):
  251. """
  252. For `Swift <https://developer.apple.com/swift/>`_ source.
  253. .. versionadded:: 2.0
  254. """
  255. name = 'Swift'
  256. filenames = ['*.swift']
  257. aliases = ['swift']
  258. mimetypes = ['text/x-swift']
  259. tokens = {
  260. 'root': [
  261. # Whitespace and Comments
  262. (r'\n', Text),
  263. (r'\s+', Text),
  264. (r'//', Comment.Single, 'comment-single'),
  265. (r'/\*', Comment.Multiline, 'comment-multi'),
  266. (r'#(if|elseif|else|endif|available)\b', Comment.Preproc, 'preproc'),
  267. # Keywords
  268. include('keywords'),
  269. # Global Types
  270. (words((
  271. 'Array', 'AutoreleasingUnsafeMutablePointer', 'BidirectionalReverseView',
  272. 'Bit', 'Bool', 'CFunctionPointer', 'COpaquePointer', 'CVaListPointer',
  273. 'Character', 'ClosedInterval', 'CollectionOfOne', 'ContiguousArray',
  274. 'Dictionary', 'DictionaryGenerator', 'DictionaryIndex', 'Double',
  275. 'EmptyCollection', 'EmptyGenerator', 'EnumerateGenerator',
  276. 'EnumerateSequence', 'FilterCollectionView',
  277. 'FilterCollectionViewIndex', 'FilterGenerator', 'FilterSequenceView',
  278. 'Float', 'Float80', 'FloatingPointClassification', 'GeneratorOf',
  279. 'GeneratorOfOne', 'GeneratorSequence', 'HalfOpenInterval', 'HeapBuffer',
  280. 'HeapBufferStorage', 'ImplicitlyUnwrappedOptional', 'IndexingGenerator',
  281. 'Int', 'Int16', 'Int32', 'Int64', 'Int8', 'LazyBidirectionalCollection',
  282. 'LazyForwardCollection', 'LazyRandomAccessCollection',
  283. 'LazySequence', 'MapCollectionView', 'MapSequenceGenerator',
  284. 'MapSequenceView', 'MirrorDisposition', 'ObjectIdentifier', 'OnHeap',
  285. 'Optional', 'PermutationGenerator', 'QuickLookObject',
  286. 'RandomAccessReverseView', 'Range', 'RangeGenerator', 'RawByte', 'Repeat',
  287. 'ReverseBidirectionalIndex', 'ReverseRandomAccessIndex', 'SequenceOf',
  288. 'SinkOf', 'Slice', 'StaticString', 'StrideThrough', 'StrideThroughGenerator',
  289. 'StrideTo', 'StrideToGenerator', 'String', 'UInt', 'UInt16', 'UInt32',
  290. 'UInt64', 'UInt8', 'UTF16', 'UTF32', 'UTF8', 'UnicodeDecodingResult',
  291. 'UnicodeScalar', 'Unmanaged', 'UnsafeBufferPointer',
  292. 'UnsafeBufferPointerGenerator', 'UnsafeMutableBufferPointer',
  293. 'UnsafeMutablePointer', 'UnsafePointer', 'Zip2', 'ZipGenerator2',
  294. # Protocols
  295. 'AbsoluteValuable', 'AnyObject', 'ArrayLiteralConvertible',
  296. 'BidirectionalIndexType', 'BitwiseOperationsType',
  297. 'BooleanLiteralConvertible', 'BooleanType', 'CVarArgType',
  298. 'CollectionType', 'Comparable', 'DebugPrintable',
  299. 'DictionaryLiteralConvertible', 'Equatable',
  300. 'ExtendedGraphemeClusterLiteralConvertible',
  301. 'ExtensibleCollectionType', 'FloatLiteralConvertible',
  302. 'FloatingPointType', 'ForwardIndexType', 'GeneratorType', 'Hashable',
  303. 'IntegerArithmeticType', 'IntegerLiteralConvertible', 'IntegerType',
  304. 'IntervalType', 'MirrorType', 'MutableCollectionType', 'MutableSliceable',
  305. 'NilLiteralConvertible', 'OutputStreamType', 'Printable',
  306. 'RandomAccessIndexType', 'RangeReplaceableCollectionType',
  307. 'RawOptionSetType', 'RawRepresentable', 'Reflectable', 'SequenceType',
  308. 'SignedIntegerType', 'SignedNumberType', 'SinkType', 'Sliceable',
  309. 'Streamable', 'Strideable', 'StringInterpolationConvertible',
  310. 'StringLiteralConvertible', 'UnicodeCodecType',
  311. 'UnicodeScalarLiteralConvertible', 'UnsignedIntegerType',
  312. '_ArrayBufferType', '_BidirectionalIndexType', '_CocoaStringType',
  313. '_CollectionType', '_Comparable', '_ExtensibleCollectionType',
  314. '_ForwardIndexType', '_Incrementable', '_IntegerArithmeticType',
  315. '_IntegerType', '_ObjectiveCBridgeable', '_RandomAccessIndexType',
  316. '_RawOptionSetType', '_SequenceType', '_Sequence_Type',
  317. '_SignedIntegerType', '_SignedNumberType', '_Sliceable', '_Strideable',
  318. '_SwiftNSArrayRequiredOverridesType', '_SwiftNSArrayType',
  319. '_SwiftNSCopyingType', '_SwiftNSDictionaryRequiredOverridesType',
  320. '_SwiftNSDictionaryType', '_SwiftNSEnumeratorType',
  321. '_SwiftNSFastEnumerationType', '_SwiftNSStringRequiredOverridesType',
  322. '_SwiftNSStringType', '_UnsignedIntegerType',
  323. # Variables
  324. 'C_ARGC', 'C_ARGV', 'Process',
  325. # Typealiases
  326. 'Any', 'AnyClass', 'BooleanLiteralType', 'CBool', 'CChar', 'CChar16',
  327. 'CChar32', 'CDouble', 'CFloat', 'CInt', 'CLong', 'CLongLong', 'CShort',
  328. 'CSignedChar', 'CUnsignedInt', 'CUnsignedLong', 'CUnsignedShort',
  329. 'CWideChar', 'ExtendedGraphemeClusterType', 'Float32', 'Float64',
  330. 'FloatLiteralType', 'IntMax', 'IntegerLiteralType', 'StringLiteralType',
  331. 'UIntMax', 'UWord', 'UnicodeScalarType', 'Void', 'Word',
  332. # Foundation/Cocoa
  333. 'NSErrorPointer', 'NSObjectProtocol', 'Selector'), suffix=r'\b'),
  334. Name.Builtin),
  335. # Functions
  336. (words((
  337. 'abs', 'advance', 'alignof', 'alignofValue', 'assert', 'assertionFailure',
  338. 'contains', 'count', 'countElements', 'debugPrint', 'debugPrintln',
  339. 'distance', 'dropFirst', 'dropLast', 'dump', 'enumerate', 'equal',
  340. 'extend', 'fatalError', 'filter', 'find', 'first', 'getVaList', 'indices',
  341. 'insert', 'isEmpty', 'join', 'last', 'lazy', 'lexicographicalCompare',
  342. 'map', 'max', 'maxElement', 'min', 'minElement', 'numericCast', 'overlaps',
  343. 'partition', 'precondition', 'preconditionFailure', 'prefix', 'print',
  344. 'println', 'reduce', 'reflect', 'removeAll', 'removeAtIndex', 'removeLast',
  345. 'removeRange', 'reverse', 'sizeof', 'sizeofValue', 'sort', 'sorted',
  346. 'splice', 'split', 'startsWith', 'stride', 'strideof', 'strideofValue',
  347. 'suffix', 'swap', 'toDebugString', 'toString', 'transcode',
  348. 'underestimateCount', 'unsafeAddressOf', 'unsafeBitCast', 'unsafeDowncast',
  349. 'withExtendedLifetime', 'withUnsafeMutablePointer',
  350. 'withUnsafeMutablePointers', 'withUnsafePointer', 'withUnsafePointers',
  351. 'withVaList'), suffix=r'\b'),
  352. Name.Builtin.Pseudo),
  353. # Implicit Block Variables
  354. (r'\$\d+', Name.Variable),
  355. # Binary Literal
  356. (r'0b[01_]+', Number.Bin),
  357. # Octal Literal
  358. (r'0o[0-7_]+', Number.Oct),
  359. # Hexadecimal Literal
  360. (r'0x[0-9a-fA-F_]+', Number.Hex),
  361. # Decimal Literal
  362. (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|'
  363. r'\.[0-9_]*|[eE][+\-]?[0-9_]+)', Number.Float),
  364. (r'[0-9][0-9_]*', Number.Integer),
  365. # String Literal
  366. (r'"', String, 'string'),
  367. # Operators and Punctuation
  368. (r'[(){}\[\].,:;=@#`?]|->|[<&?](?=\w)|(?<=\w)[>!?]', Punctuation),
  369. (r'[/=\-+!*%<>&|^?~]+', Operator),
  370. # Identifier
  371. (r'[a-zA-Z_]\w*', Name)
  372. ],
  373. 'keywords': [
  374. (words((
  375. 'as', 'break', 'case', 'catch', 'continue', 'default', 'defer',
  376. 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'is',
  377. 'repeat', 'return', '#selector', 'switch', 'throw', 'try',
  378. 'where', 'while'), suffix=r'\b'),
  379. Keyword),
  380. (r'@availability\([^)]+\)', Keyword.Reserved),
  381. (words((
  382. 'associativity', 'convenience', 'dynamic', 'didSet', 'final',
  383. 'get', 'indirect', 'infix', 'inout', 'lazy', 'left', 'mutating',
  384. 'none', 'nonmutating', 'optional', 'override', 'postfix',
  385. 'precedence', 'prefix', 'Protocol', 'required', 'rethrows',
  386. 'right', 'set', 'throws', 'Type', 'unowned', 'weak', 'willSet',
  387. '@availability', '@autoclosure', '@noreturn',
  388. '@NSApplicationMain', '@NSCopying', '@NSManaged', '@objc',
  389. '@UIApplicationMain', '@IBAction', '@IBDesignable',
  390. '@IBInspectable', '@IBOutlet'), suffix=r'\b'),
  391. Keyword.Reserved),
  392. (r'(as|dynamicType|false|is|nil|self|Self|super|true|__COLUMN__'
  393. r'|__FILE__|__FUNCTION__|__LINE__|_'
  394. r'|#(?:file|line|column|function))\b', Keyword.Constant),
  395. (r'import\b', Keyword.Declaration, 'module'),
  396. (r'(class|enum|extension|struct|protocol)(\s+)([a-zA-Z_]\w*)',
  397. bygroups(Keyword.Declaration, Text, Name.Class)),
  398. (r'(func)(\s+)([a-zA-Z_]\w*)',
  399. bygroups(Keyword.Declaration, Text, Name.Function)),
  400. (r'(var|let)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration,
  401. Text, Name.Variable)),
  402. (words((
  403. 'associatedtype', 'class', 'deinit', 'enum', 'extension', 'func', 'import',
  404. 'init', 'internal', 'let', 'operator', 'private', 'protocol', 'public',
  405. 'static', 'struct', 'subscript', 'typealias', 'var'), suffix=r'\b'),
  406. Keyword.Declaration)
  407. ],
  408. 'comment': [
  409. (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):',
  410. Comment.Special)
  411. ],
  412. # Nested
  413. 'comment-single': [
  414. (r'\n', Text, '#pop'),
  415. include('comment'),
  416. (r'[^\n]', Comment.Single)
  417. ],
  418. 'comment-multi': [
  419. include('comment'),
  420. (r'[^*/]', Comment.Multiline),
  421. (r'/\*', Comment.Multiline, '#push'),
  422. (r'\*/', Comment.Multiline, '#pop'),
  423. (r'[*/]', Comment.Multiline)
  424. ],
  425. 'module': [
  426. (r'\n', Text, '#pop'),
  427. (r'[a-zA-Z_]\w*', Name.Class),
  428. include('root')
  429. ],
  430. 'preproc': [
  431. (r'\n', Text, '#pop'),
  432. include('keywords'),
  433. (r'[A-Za-z]\w*', Comment.Preproc),
  434. include('root')
  435. ],
  436. 'string': [
  437. (r'\\\(', String.Interpol, 'string-intp'),
  438. (r'"', String, '#pop'),
  439. (r"""\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}"""
  440. r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}""", String.Escape),
  441. (r'[^\\"]+', String),
  442. (r'\\', String)
  443. ],
  444. 'string-intp': [
  445. (r'\(', String.Interpol, '#push'),
  446. (r'\)', String.Interpol, '#pop'),
  447. include('root')
  448. ]
  449. }
  450. def get_tokens_unprocessed(self, text):
  451. from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \
  452. COCOA_PROTOCOLS, COCOA_PRIMITIVES
  453. for index, token, value in \
  454. RegexLexer.get_tokens_unprocessed(self, text):
  455. if token is Name or token is Name.Class:
  456. if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \
  457. or value in COCOA_PRIMITIVES:
  458. token = Name.Builtin.Pseudo
  459. yield index, token, value