pascal.py 30 KB

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