pascal.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. """
  2. pygments.lexers.pascal
  3. ~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for Pascal 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 Lexer
  10. from pygments.util import get_bool_opt, get_list_opt
  11. from pygments.token import Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation, Error, Whitespace
  13. from pygments.scanner import Scanner
  14. # compatibility import
  15. from pygments.lexers.modula2 import Modula2Lexer # noqa: F401
  16. __all__ = ['DelphiLexer', 'PortugolLexer']
  17. class PortugolLexer(Lexer):
  18. """For Portugol, a Pascal dialect with keywords in Portuguese."""
  19. name = 'Portugol'
  20. aliases = ['portugol']
  21. filenames = ['*.alg', '*.portugol']
  22. mimetypes = []
  23. url = "https://www.apoioinformatica.inf.br/produtos/visualg/linguagem"
  24. version_added = ''
  25. def __init__(self, **options):
  26. Lexer.__init__(self, **options)
  27. self.lexer = DelphiLexer(**options, portugol=True)
  28. def get_tokens_unprocessed(self, text):
  29. return self.lexer.get_tokens_unprocessed(text)
  30. class DelphiLexer(Lexer):
  31. """
  32. For Delphi (Borland Object Pascal),
  33. Turbo Pascal and Free Pascal source code.
  34. Additional options accepted:
  35. `turbopascal`
  36. Highlight Turbo Pascal specific keywords (default: ``True``).
  37. `delphi`
  38. Highlight Borland Delphi specific keywords (default: ``True``).
  39. `freepascal`
  40. Highlight Free Pascal specific keywords (default: ``True``).
  41. `units`
  42. A list of units that should be considered builtin, supported are
  43. ``System``, ``SysUtils``, ``Classes`` and ``Math``.
  44. Default is to consider all of them builtin.
  45. """
  46. name = 'Delphi'
  47. aliases = ['delphi', 'pas', 'pascal', 'objectpascal']
  48. filenames = ['*.pas', '*.dpr']
  49. mimetypes = ['text/x-pascal']
  50. url = 'https://www.embarcadero.com/products/delphi'
  51. version_added = ''
  52. TURBO_PASCAL_KEYWORDS = (
  53. 'absolute', 'and', 'array', 'asm', 'begin', 'break', 'case',
  54. 'const', 'constructor', 'continue', 'destructor', 'div', 'do',
  55. 'downto', 'else', 'end', 'file', 'for', 'function', 'goto',
  56. 'if', 'implementation', 'in', 'inherited', 'inline', 'interface',
  57. 'label', 'mod', 'nil', 'not', 'object', 'of', 'on', 'operator',
  58. 'or', 'packed', 'procedure', 'program', 'record', 'reintroduce',
  59. 'repeat', 'self', 'set', 'shl', 'shr', 'string', 'then', 'to',
  60. 'type', 'unit', 'until', 'uses', 'var', 'while', 'with', 'xor'
  61. )
  62. DELPHI_KEYWORDS = (
  63. 'as', 'class', 'except', 'exports', 'finalization', 'finally',
  64. 'initialization', 'is', 'library', 'on', 'property', 'raise',
  65. 'threadvar', 'try'
  66. )
  67. FREE_PASCAL_KEYWORDS = (
  68. 'dispose', 'exit', 'false', 'new', 'true'
  69. )
  70. BLOCK_KEYWORDS = {
  71. 'begin', 'class', 'const', 'constructor', 'destructor', 'end',
  72. 'finalization', 'function', 'implementation', 'initialization',
  73. 'label', 'library', 'operator', 'procedure', 'program', 'property',
  74. 'record', 'threadvar', 'type', 'unit', 'uses', 'var'
  75. }
  76. FUNCTION_MODIFIERS = {
  77. 'alias', 'cdecl', 'export', 'inline', 'interrupt', 'nostackframe',
  78. 'pascal', 'register', 'safecall', 'softfloat', 'stdcall',
  79. 'varargs', 'name', 'dynamic', 'near', 'virtual', 'external',
  80. 'override', 'assembler'
  81. }
  82. # XXX: those aren't global. but currently we know no way for defining
  83. # them just for the type context.
  84. DIRECTIVES = {
  85. 'absolute', 'abstract', 'assembler', 'cppdecl', 'default', 'far',
  86. 'far16', 'forward', 'index', 'oldfpccall', 'private', 'protected',
  87. 'published', 'public'
  88. }
  89. BUILTIN_TYPES = {
  90. 'ansichar', 'ansistring', 'bool', 'boolean', 'byte', 'bytebool',
  91. 'cardinal', 'char', 'comp', 'currency', 'double', 'dword',
  92. 'extended', 'int64', 'integer', 'iunknown', 'longbool', 'longint',
  93. 'longword', 'pansichar', 'pansistring', 'pbool', 'pboolean',
  94. 'pbyte', 'pbytearray', 'pcardinal', 'pchar', 'pcomp', 'pcurrency',
  95. 'pdate', 'pdatetime', 'pdouble', 'pdword', 'pextended', 'phandle',
  96. 'pint64', 'pinteger', 'plongint', 'plongword', 'pointer',
  97. 'ppointer', 'pshortint', 'pshortstring', 'psingle', 'psmallint',
  98. 'pstring', 'pvariant', 'pwidechar', 'pwidestring', 'pword',
  99. 'pwordarray', 'pwordbool', 'real', 'real48', 'shortint',
  100. 'shortstring', 'single', 'smallint', 'string', 'tclass', 'tdate',
  101. 'tdatetime', 'textfile', 'thandle', 'tobject', 'ttime', 'variant',
  102. 'widechar', 'widestring', 'word', 'wordbool'
  103. }
  104. BUILTIN_UNITS = {
  105. 'System': (
  106. 'abs', 'acquireexceptionobject', 'addr', 'ansitoutf8',
  107. 'append', 'arctan', 'assert', 'assigned', 'assignfile',
  108. 'beginthread', 'blockread', 'blockwrite', 'break', 'chdir',
  109. 'chr', 'close', 'closefile', 'comptocurrency', 'comptodouble',
  110. 'concat', 'continue', 'copy', 'cos', 'dec', 'delete',
  111. 'dispose', 'doubletocomp', 'endthread', 'enummodules',
  112. 'enumresourcemodules', 'eof', 'eoln', 'erase', 'exceptaddr',
  113. 'exceptobject', 'exclude', 'exit', 'exp', 'filepos', 'filesize',
  114. 'fillchar', 'finalize', 'findclasshinstance', 'findhinstance',
  115. 'findresourcehinstance', 'flush', 'frac', 'freemem',
  116. 'get8087cw', 'getdir', 'getlasterror', 'getmem',
  117. 'getmemorymanager', 'getmodulefilename', 'getvariantmanager',
  118. 'halt', 'hi', 'high', 'inc', 'include', 'initialize', 'insert',
  119. 'int', 'ioresult', 'ismemorymanagerset', 'isvariantmanagerset',
  120. 'length', 'ln', 'lo', 'low', 'mkdir', 'move', 'new', 'odd',
  121. 'olestrtostring', 'olestrtostrvar', 'ord', 'paramcount',
  122. 'paramstr', 'pi', 'pos', 'pred', 'ptr', 'pucs4chars', 'random',
  123. 'randomize', 'read', 'readln', 'reallocmem',
  124. 'releaseexceptionobject', 'rename', 'reset', 'rewrite', 'rmdir',
  125. 'round', 'runerror', 'seek', 'seekeof', 'seekeoln',
  126. 'set8087cw', 'setlength', 'setlinebreakstyle',
  127. 'setmemorymanager', 'setstring', 'settextbuf',
  128. 'setvariantmanager', 'sin', 'sizeof', 'slice', 'sqr', 'sqrt',
  129. 'str', 'stringofchar', 'stringtoolestr', 'stringtowidechar',
  130. 'succ', 'swap', 'trunc', 'truncate', 'typeinfo',
  131. 'ucs4stringtowidestring', 'unicodetoutf8', 'uniquestring',
  132. 'upcase', 'utf8decode', 'utf8encode', 'utf8toansi',
  133. 'utf8tounicode', 'val', 'vararrayredim', 'varclear',
  134. 'widecharlentostring', 'widecharlentostrvar',
  135. 'widechartostring', 'widechartostrvar',
  136. 'widestringtoucs4string', 'write', 'writeln'
  137. ),
  138. 'SysUtils': (
  139. 'abort', 'addexitproc', 'addterminateproc', 'adjustlinebreaks',
  140. 'allocmem', 'ansicomparefilename', 'ansicomparestr',
  141. 'ansicomparetext', 'ansidequotedstr', 'ansiextractquotedstr',
  142. 'ansilastchar', 'ansilowercase', 'ansilowercasefilename',
  143. 'ansipos', 'ansiquotedstr', 'ansisamestr', 'ansisametext',
  144. 'ansistrcomp', 'ansistricomp', 'ansistrlastchar', 'ansistrlcomp',
  145. 'ansistrlicomp', 'ansistrlower', 'ansistrpos', 'ansistrrscan',
  146. 'ansistrscan', 'ansistrupper', 'ansiuppercase',
  147. 'ansiuppercasefilename', 'appendstr', 'assignstr', 'beep',
  148. 'booltostr', 'bytetocharindex', 'bytetocharlen', 'bytetype',
  149. 'callterminateprocs', 'changefileext', 'charlength',
  150. 'chartobyteindex', 'chartobytelen', 'comparemem', 'comparestr',
  151. 'comparetext', 'createdir', 'createguid', 'currentyear',
  152. 'currtostr', 'currtostrf', 'date', 'datetimetofiledate',
  153. 'datetimetostr', 'datetimetostring', 'datetimetosystemtime',
  154. 'datetimetotimestamp', 'datetostr', 'dayofweek', 'decodedate',
  155. 'decodedatefully', 'decodetime', 'deletefile', 'directoryexists',
  156. 'diskfree', 'disksize', 'disposestr', 'encodedate', 'encodetime',
  157. 'exceptionerrormessage', 'excludetrailingbackslash',
  158. 'excludetrailingpathdelimiter', 'expandfilename',
  159. 'expandfilenamecase', 'expanduncfilename', 'extractfiledir',
  160. 'extractfiledrive', 'extractfileext', 'extractfilename',
  161. 'extractfilepath', 'extractrelativepath', 'extractshortpathname',
  162. 'fileage', 'fileclose', 'filecreate', 'filedatetodatetime',
  163. 'fileexists', 'filegetattr', 'filegetdate', 'fileisreadonly',
  164. 'fileopen', 'fileread', 'filesearch', 'fileseek', 'filesetattr',
  165. 'filesetdate', 'filesetreadonly', 'filewrite', 'finalizepackage',
  166. 'findclose', 'findcmdlineswitch', 'findfirst', 'findnext',
  167. 'floattocurr', 'floattodatetime', 'floattodecimal', 'floattostr',
  168. 'floattostrf', 'floattotext', 'floattotextfmt', 'fmtloadstr',
  169. 'fmtstr', 'forcedirectories', 'format', 'formatbuf', 'formatcurr',
  170. 'formatdatetime', 'formatfloat', 'freeandnil', 'getcurrentdir',
  171. 'getenvironmentvariable', 'getfileversion', 'getformatsettings',
  172. 'getlocaleformatsettings', 'getmodulename', 'getpackagedescription',
  173. 'getpackageinfo', 'gettime', 'guidtostring', 'incamonth',
  174. 'includetrailingbackslash', 'includetrailingpathdelimiter',
  175. 'incmonth', 'initializepackage', 'interlockeddecrement',
  176. 'interlockedexchange', 'interlockedexchangeadd',
  177. 'interlockedincrement', 'inttohex', 'inttostr', 'isdelimiter',
  178. 'isequalguid', 'isleapyear', 'ispathdelimiter', 'isvalidident',
  179. 'languages', 'lastdelimiter', 'loadpackage', 'loadstr',
  180. 'lowercase', 'msecstotimestamp', 'newstr', 'nextcharindex', 'now',
  181. 'outofmemoryerror', 'quotedstr', 'raiselastoserror',
  182. 'raiselastwin32error', 'removedir', 'renamefile', 'replacedate',
  183. 'replacetime', 'safeloadlibrary', 'samefilename', 'sametext',
  184. 'setcurrentdir', 'showexception', 'sleep', 'stralloc', 'strbufsize',
  185. 'strbytetype', 'strcat', 'strcharlength', 'strcomp', 'strcopy',
  186. 'strdispose', 'strecopy', 'strend', 'strfmt', 'stricomp',
  187. 'stringreplace', 'stringtoguid', 'strlcat', 'strlcomp', 'strlcopy',
  188. 'strlen', 'strlfmt', 'strlicomp', 'strlower', 'strmove', 'strnew',
  189. 'strnextchar', 'strpas', 'strpcopy', 'strplcopy', 'strpos',
  190. 'strrscan', 'strscan', 'strtobool', 'strtobooldef', 'strtocurr',
  191. 'strtocurrdef', 'strtodate', 'strtodatedef', 'strtodatetime',
  192. 'strtodatetimedef', 'strtofloat', 'strtofloatdef', 'strtoint',
  193. 'strtoint64', 'strtoint64def', 'strtointdef', 'strtotime',
  194. 'strtotimedef', 'strupper', 'supports', 'syserrormessage',
  195. 'systemtimetodatetime', 'texttofloat', 'time', 'timestamptodatetime',
  196. 'timestamptomsecs', 'timetostr', 'trim', 'trimleft', 'trimright',
  197. 'tryencodedate', 'tryencodetime', 'tryfloattocurr', 'tryfloattodatetime',
  198. 'trystrtobool', 'trystrtocurr', 'trystrtodate', 'trystrtodatetime',
  199. 'trystrtofloat', 'trystrtoint', 'trystrtoint64', 'trystrtotime',
  200. 'unloadpackage', 'uppercase', 'widecomparestr', 'widecomparetext',
  201. 'widefmtstr', 'wideformat', 'wideformatbuf', 'widelowercase',
  202. 'widesamestr', 'widesametext', 'wideuppercase', 'win32check',
  203. 'wraptext'
  204. ),
  205. 'Classes': (
  206. 'activateclassgroup', 'allocatehwnd', 'bintohex', 'checksynchronize',
  207. 'collectionsequal', 'countgenerations', 'deallocatehwnd', 'equalrect',
  208. 'extractstrings', 'findclass', 'findglobalcomponent', 'getclass',
  209. 'groupdescendantswith', 'hextobin', 'identtoint',
  210. 'initinheritedcomponent', 'inttoident', 'invalidpoint',
  211. 'isuniqueglobalcomponentname', 'linestart', 'objectbinarytotext',
  212. 'objectresourcetotext', 'objecttexttobinary', 'objecttexttoresource',
  213. 'pointsequal', 'readcomponentres', 'readcomponentresex',
  214. 'readcomponentresfile', 'rect', 'registerclass', 'registerclassalias',
  215. 'registerclasses', 'registercomponents', 'registerintegerconsts',
  216. 'registernoicon', 'registernonactivex', 'smallpoint', 'startclassgroup',
  217. 'teststreamformat', 'unregisterclass', 'unregisterclasses',
  218. 'unregisterintegerconsts', 'unregistermoduleclasses',
  219. 'writecomponentresfile'
  220. ),
  221. 'Math': (
  222. 'arccos', 'arccosh', 'arccot', 'arccoth', 'arccsc', 'arccsch', 'arcsec',
  223. 'arcsech', 'arcsin', 'arcsinh', 'arctan2', 'arctanh', 'ceil',
  224. 'comparevalue', 'cosecant', 'cosh', 'cot', 'cotan', 'coth', 'csc',
  225. 'csch', 'cycletodeg', 'cycletograd', 'cycletorad', 'degtocycle',
  226. 'degtograd', 'degtorad', 'divmod', 'doubledecliningbalance',
  227. 'ensurerange', 'floor', 'frexp', 'futurevalue', 'getexceptionmask',
  228. 'getprecisionmode', 'getroundmode', 'gradtocycle', 'gradtodeg',
  229. 'gradtorad', 'hypot', 'inrange', 'interestpayment', 'interestrate',
  230. 'internalrateofreturn', 'intpower', 'isinfinite', 'isnan', 'iszero',
  231. 'ldexp', 'lnxp1', 'log10', 'log2', 'logn', 'max', 'maxintvalue',
  232. 'maxvalue', 'mean', 'meanandstddev', 'min', 'minintvalue', 'minvalue',
  233. 'momentskewkurtosis', 'netpresentvalue', 'norm', 'numberofperiods',
  234. 'payment', 'periodpayment', 'poly', 'popnstddev', 'popnvariance',
  235. 'power', 'presentvalue', 'radtocycle', 'radtodeg', 'radtograd',
  236. 'randg', 'randomrange', 'roundto', 'samevalue', 'sec', 'secant',
  237. 'sech', 'setexceptionmask', 'setprecisionmode', 'setroundmode',
  238. 'sign', 'simpleroundto', 'sincos', 'sinh', 'slndepreciation', 'stddev',
  239. 'sum', 'sumint', 'sumofsquares', 'sumsandsquares', 'syddepreciation',
  240. 'tan', 'tanh', 'totalvariance', 'variance'
  241. )
  242. }
  243. ASM_REGISTERS = {
  244. 'ah', 'al', 'ax', 'bh', 'bl', 'bp', 'bx', 'ch', 'cl', 'cr0',
  245. 'cr1', 'cr2', 'cr3', 'cr4', 'cs', 'cx', 'dh', 'di', 'dl', 'dr0',
  246. 'dr1', 'dr2', 'dr3', 'dr4', 'dr5', 'dr6', 'dr7', 'ds', 'dx',
  247. 'eax', 'ebp', 'ebx', 'ecx', 'edi', 'edx', 'es', 'esi', 'esp',
  248. 'fs', 'gs', 'mm0', 'mm1', 'mm2', 'mm3', 'mm4', 'mm5', 'mm6',
  249. 'mm7', 'si', 'sp', 'ss', 'st0', 'st1', 'st2', 'st3', 'st4', 'st5',
  250. 'st6', 'st7', 'xmm0', 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5',
  251. 'xmm6', 'xmm7'
  252. }
  253. ASM_INSTRUCTIONS = {
  254. 'aaa', 'aad', 'aam', 'aas', 'adc', 'add', 'and', 'arpl', 'bound',
  255. 'bsf', 'bsr', 'bswap', 'bt', 'btc', 'btr', 'bts', 'call', 'cbw',
  256. 'cdq', 'clc', 'cld', 'cli', 'clts', 'cmc', 'cmova', 'cmovae',
  257. 'cmovb', 'cmovbe', 'cmovc', 'cmovcxz', 'cmove', 'cmovg',
  258. 'cmovge', 'cmovl', 'cmovle', 'cmovna', 'cmovnae', 'cmovnb',
  259. 'cmovnbe', 'cmovnc', 'cmovne', 'cmovng', 'cmovnge', 'cmovnl',
  260. 'cmovnle', 'cmovno', 'cmovnp', 'cmovns', 'cmovnz', 'cmovo',
  261. 'cmovp', 'cmovpe', 'cmovpo', 'cmovs', 'cmovz', 'cmp', 'cmpsb',
  262. 'cmpsd', 'cmpsw', 'cmpxchg', 'cmpxchg486', 'cmpxchg8b', 'cpuid',
  263. 'cwd', 'cwde', 'daa', 'das', 'dec', 'div', 'emms', 'enter', 'hlt',
  264. 'ibts', 'icebp', 'idiv', 'imul', 'in', 'inc', 'insb', 'insd',
  265. 'insw', 'int', 'int01', 'int03', 'int1', 'int3', 'into', 'invd',
  266. 'invlpg', 'iret', 'iretd', 'iretw', 'ja', 'jae', 'jb', 'jbe',
  267. 'jc', 'jcxz', 'jcxz', 'je', 'jecxz', 'jg', 'jge', 'jl', 'jle',
  268. 'jmp', 'jna', 'jnae', 'jnb', 'jnbe', 'jnc', 'jne', 'jng', 'jnge',
  269. 'jnl', 'jnle', 'jno', 'jnp', 'jns', 'jnz', 'jo', 'jp', 'jpe',
  270. 'jpo', 'js', 'jz', 'lahf', 'lar', 'lcall', 'lds', 'lea', 'leave',
  271. 'les', 'lfs', 'lgdt', 'lgs', 'lidt', 'ljmp', 'lldt', 'lmsw',
  272. 'loadall', 'loadall286', 'lock', 'lodsb', 'lodsd', 'lodsw',
  273. 'loop', 'loope', 'loopne', 'loopnz', 'loopz', 'lsl', 'lss', 'ltr',
  274. 'mov', 'movd', 'movq', 'movsb', 'movsd', 'movsw', 'movsx',
  275. 'movzx', 'mul', 'neg', 'nop', 'not', 'or', 'out', 'outsb', 'outsd',
  276. 'outsw', 'pop', 'popa', 'popad', 'popaw', 'popf', 'popfd', 'popfw',
  277. 'push', 'pusha', 'pushad', 'pushaw', 'pushf', 'pushfd', 'pushfw',
  278. 'rcl', 'rcr', 'rdmsr', 'rdpmc', 'rdshr', 'rdtsc', 'rep', 'repe',
  279. 'repne', 'repnz', 'repz', 'ret', 'retf', 'retn', 'rol', 'ror',
  280. 'rsdc', 'rsldt', 'rsm', 'sahf', 'sal', 'salc', 'sar', 'sbb',
  281. 'scasb', 'scasd', 'scasw', 'seta', 'setae', 'setb', 'setbe',
  282. 'setc', 'setcxz', 'sete', 'setg', 'setge', 'setl', 'setle',
  283. 'setna', 'setnae', 'setnb', 'setnbe', 'setnc', 'setne', 'setng',
  284. 'setnge', 'setnl', 'setnle', 'setno', 'setnp', 'setns', 'setnz',
  285. 'seto', 'setp', 'setpe', 'setpo', 'sets', 'setz', 'sgdt', 'shl',
  286. 'shld', 'shr', 'shrd', 'sidt', 'sldt', 'smi', 'smint', 'smintold',
  287. 'smsw', 'stc', 'std', 'sti', 'stosb', 'stosd', 'stosw', 'str',
  288. 'sub', 'svdc', 'svldt', 'svts', 'syscall', 'sysenter', 'sysexit',
  289. 'sysret', 'test', 'ud1', 'ud2', 'umov', 'verr', 'verw', 'wait',
  290. 'wbinvd', 'wrmsr', 'wrshr', 'xadd', 'xbts', 'xchg', 'xlat',
  291. 'xlatb', 'xor'
  292. }
  293. PORTUGOL_KEYWORDS = (
  294. 'aleatorio',
  295. 'algoritmo',
  296. 'arquivo',
  297. 'ate',
  298. 'caso',
  299. 'cronometro',
  300. 'debug',
  301. 'e',
  302. 'eco',
  303. 'enquanto',
  304. 'entao',
  305. 'escolha',
  306. 'escreva',
  307. 'escreval',
  308. 'faca',
  309. 'falso',
  310. 'fimalgoritmo',
  311. 'fimenquanto',
  312. 'fimescolha',
  313. 'fimfuncao',
  314. 'fimpara',
  315. 'fimprocedimento',
  316. 'fimrepita',
  317. 'fimse',
  318. 'funcao',
  319. 'inicio',
  320. 'int',
  321. 'interrompa',
  322. 'leia',
  323. 'limpatela',
  324. 'mod',
  325. 'nao',
  326. 'ou',
  327. 'outrocaso',
  328. 'para',
  329. 'passo',
  330. 'pausa',
  331. 'procedimento',
  332. 'repita',
  333. 'retorne',
  334. 'se',
  335. 'senao',
  336. 'timer',
  337. 'var',
  338. 'vetor',
  339. 'verdadeiro',
  340. 'xou',
  341. 'div',
  342. 'mod',
  343. 'abs',
  344. 'arccos',
  345. 'arcsen',
  346. 'arctan',
  347. 'cos',
  348. 'cotan',
  349. 'Exp',
  350. 'grauprad',
  351. 'int',
  352. 'log',
  353. 'logn',
  354. 'pi',
  355. 'quad',
  356. 'radpgrau',
  357. 'raizq',
  358. 'rand',
  359. 'randi',
  360. 'sen',
  361. 'Tan',
  362. 'asc',
  363. 'carac',
  364. 'caracpnum',
  365. 'compr',
  366. 'copia',
  367. 'maiusc',
  368. 'minusc',
  369. 'numpcarac',
  370. 'pos',
  371. )
  372. PORTUGOL_BUILTIN_TYPES = {
  373. 'inteiro', 'real', 'caractere', 'logico'
  374. }
  375. def __init__(self, **options):
  376. Lexer.__init__(self, **options)
  377. self.keywords = set()
  378. self.builtins = set()
  379. if get_bool_opt(options, 'portugol', False):
  380. self.keywords.update(self.PORTUGOL_KEYWORDS)
  381. self.builtins.update(self.PORTUGOL_BUILTIN_TYPES)
  382. self.is_portugol = True
  383. else:
  384. self.is_portugol = False
  385. if get_bool_opt(options, 'turbopascal', True):
  386. self.keywords.update(self.TURBO_PASCAL_KEYWORDS)
  387. if get_bool_opt(options, 'delphi', True):
  388. self.keywords.update(self.DELPHI_KEYWORDS)
  389. if get_bool_opt(options, 'freepascal', True):
  390. self.keywords.update(self.FREE_PASCAL_KEYWORDS)
  391. for unit in get_list_opt(options, 'units', list(self.BUILTIN_UNITS)):
  392. self.builtins.update(self.BUILTIN_UNITS[unit])
  393. def get_tokens_unprocessed(self, text):
  394. scanner = Scanner(text, re.DOTALL | re.MULTILINE | re.IGNORECASE)
  395. stack = ['initial']
  396. in_function_block = False
  397. in_property_block = False
  398. was_dot = False
  399. next_token_is_function = False
  400. next_token_is_property = False
  401. collect_labels = False
  402. block_labels = set()
  403. brace_balance = [0, 0]
  404. while not scanner.eos:
  405. token = Error
  406. if stack[-1] == 'initial':
  407. if scanner.scan(r'\s+'):
  408. token = Whitespace
  409. elif not self.is_portugol and scanner.scan(r'\{.*?\}|\(\*.*?\*\)'):
  410. if scanner.match.startswith('$'):
  411. token = Comment.Preproc
  412. else:
  413. token = Comment.Multiline
  414. elif scanner.scan(r'//.*?$'):
  415. token = Comment.Single
  416. elif self.is_portugol and scanner.scan(r'(<\-)|(>=)|(<=)|%|<|>|-|\+|\*|\=|(<>)|\/|\.|:|,'):
  417. token = Operator
  418. elif not self.is_portugol and scanner.scan(r'[-+*\/=<>:;,.@\^]'):
  419. token = Operator
  420. # stop label highlighting on next ";"
  421. if collect_labels and scanner.match == ';':
  422. collect_labels = False
  423. elif scanner.scan(r'[\(\)\[\]]+'):
  424. token = Punctuation
  425. # abort function naming ``foo = Function(...)``
  426. next_token_is_function = False
  427. # if we are in a function block we count the open
  428. # braces because ootherwise it's impossible to
  429. # determine the end of the modifier context
  430. if in_function_block or in_property_block:
  431. if scanner.match == '(':
  432. brace_balance[0] += 1
  433. elif scanner.match == ')':
  434. brace_balance[0] -= 1
  435. elif scanner.match == '[':
  436. brace_balance[1] += 1
  437. elif scanner.match == ']':
  438. brace_balance[1] -= 1
  439. elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'):
  440. lowercase_name = scanner.match.lower()
  441. if lowercase_name == 'result':
  442. token = Name.Builtin.Pseudo
  443. elif lowercase_name in self.keywords:
  444. token = Keyword
  445. # if we are in a special block and a
  446. # block ending keyword occurs (and the parenthesis
  447. # is balanced) we end the current block context
  448. if self.is_portugol:
  449. if lowercase_name in ('funcao', 'procedimento'):
  450. in_function_block = True
  451. next_token_is_function = True
  452. else:
  453. if (in_function_block or in_property_block) and \
  454. lowercase_name in self.BLOCK_KEYWORDS and \
  455. brace_balance[0] <= 0 and \
  456. brace_balance[1] <= 0:
  457. in_function_block = False
  458. in_property_block = False
  459. brace_balance = [0, 0]
  460. block_labels = set()
  461. if lowercase_name in ('label', 'goto'):
  462. collect_labels = True
  463. elif lowercase_name == 'asm':
  464. stack.append('asm')
  465. elif lowercase_name == 'property':
  466. in_property_block = True
  467. next_token_is_property = True
  468. elif lowercase_name in ('procedure', 'operator',
  469. 'function', 'constructor',
  470. 'destructor'):
  471. in_function_block = True
  472. next_token_is_function = True
  473. # we are in a function block and the current name
  474. # is in the set of registered modifiers. highlight
  475. # it as pseudo keyword
  476. elif not self.is_portugol and in_function_block and \
  477. lowercase_name in self.FUNCTION_MODIFIERS:
  478. token = Keyword.Pseudo
  479. # if we are in a property highlight some more
  480. # modifiers
  481. elif not self.is_portugol and in_property_block and \
  482. lowercase_name in ('read', 'write'):
  483. token = Keyword.Pseudo
  484. next_token_is_function = True
  485. # if the last iteration set next_token_is_function
  486. # to true we now want this name highlighted as
  487. # function. so do that and reset the state
  488. elif next_token_is_function:
  489. # Look if the next token is a dot. If yes it's
  490. # not a function, but a class name and the
  491. # part after the dot a function name
  492. if not self.is_portugol and scanner.test(r'\s*\.\s*'):
  493. token = Name.Class
  494. # it's not a dot, our job is done
  495. else:
  496. token = Name.Function
  497. next_token_is_function = False
  498. if self.is_portugol:
  499. block_labels.add(scanner.match.lower())
  500. # same for properties
  501. elif not self.is_portugol and next_token_is_property:
  502. token = Name.Property
  503. next_token_is_property = False
  504. # Highlight this token as label and add it
  505. # to the list of known labels
  506. elif not self.is_portugol and collect_labels:
  507. token = Name.Label
  508. block_labels.add(scanner.match.lower())
  509. # name is in list of known labels
  510. elif lowercase_name in block_labels:
  511. token = Name.Label
  512. elif self.is_portugol and lowercase_name in self.PORTUGOL_BUILTIN_TYPES:
  513. token = Keyword.Type
  514. elif not self.is_portugol and lowercase_name in self.BUILTIN_TYPES:
  515. token = Keyword.Type
  516. elif not self.is_portugol and lowercase_name in self.DIRECTIVES:
  517. token = Keyword.Pseudo
  518. # builtins are just builtins if the token
  519. # before isn't a dot
  520. elif not self.is_portugol and not was_dot and lowercase_name in self.builtins:
  521. token = Name.Builtin
  522. else:
  523. token = Name
  524. elif self.is_portugol and scanner.scan(r"\""):
  525. token = String
  526. stack.append('string')
  527. elif not self.is_portugol and scanner.scan(r"'"):
  528. token = String
  529. stack.append('string')
  530. elif not self.is_portugol and scanner.scan(r'\#(\d+|\$[0-9A-Fa-f]+)'):
  531. token = String.Char
  532. elif not self.is_portugol and scanner.scan(r'\$[0-9A-Fa-f]+'):
  533. token = Number.Hex
  534. elif scanner.scan(r'\d+(?![eE]|\.[^.])'):
  535. token = Number.Integer
  536. elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'):
  537. token = Number.Float
  538. else:
  539. # if the stack depth is deeper than once, pop
  540. if len(stack) > 1:
  541. stack.pop()
  542. scanner.get_char()
  543. elif stack[-1] == 'string':
  544. if self.is_portugol:
  545. if scanner.scan(r"''"):
  546. token = String.Escape
  547. elif scanner.scan(r"\""):
  548. token = String
  549. stack.pop()
  550. elif scanner.scan(r"[^\"]*"):
  551. token = String
  552. else:
  553. scanner.get_char()
  554. stack.pop()
  555. else:
  556. if scanner.scan(r"''"):
  557. token = String.Escape
  558. elif scanner.scan(r"'"):
  559. token = String
  560. stack.pop()
  561. elif scanner.scan(r"[^']*"):
  562. token = String
  563. else:
  564. scanner.get_char()
  565. stack.pop()
  566. elif not self.is_portugol and stack[-1] == 'asm':
  567. if scanner.scan(r'\s+'):
  568. token = Whitespace
  569. elif scanner.scan(r'end'):
  570. token = Keyword
  571. stack.pop()
  572. elif scanner.scan(r'\{.*?\}|\(\*.*?\*\)'):
  573. if scanner.match.startswith('$'):
  574. token = Comment.Preproc
  575. else:
  576. token = Comment.Multiline
  577. elif scanner.scan(r'//.*?$'):
  578. token = Comment.Single
  579. elif scanner.scan(r"'"):
  580. token = String
  581. stack.append('string')
  582. elif scanner.scan(r'@@[A-Za-z_][A-Za-z_0-9]*'):
  583. token = Name.Label
  584. elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'):
  585. lowercase_name = scanner.match.lower()
  586. if lowercase_name in self.ASM_INSTRUCTIONS:
  587. token = Keyword
  588. elif lowercase_name in self.ASM_REGISTERS:
  589. token = Name.Builtin
  590. else:
  591. token = Name
  592. elif scanner.scan(r'[-+*\/=<>:;,.@\^]+'):
  593. token = Operator
  594. elif scanner.scan(r'[\(\)\[\]]+'):
  595. token = Punctuation
  596. elif scanner.scan(r'\$[0-9A-Fa-f]+'):
  597. token = Number.Hex
  598. elif scanner.scan(r'\d+(?![eE]|\.[^.])'):
  599. token = Number.Integer
  600. elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'):
  601. token = Number.Float
  602. else:
  603. scanner.get_char()
  604. stack.pop()
  605. # save the dot!!!11
  606. if not self.is_portugol and scanner.match.strip():
  607. was_dot = scanner.match == '.'
  608. yield scanner.start_pos, token, scanner.match or ''