gdscript.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """
  2. pygments.lexers.gdscript
  3. ~~~~~~~~~~~~~~~~~~~~~~~~
  4. Lexer for GDScript.
  5. Modified by Daniel J. Ramirez <djrmuv@gmail.com> based on the original
  6. python.py.
  7. :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
  8. :license: BSD, see LICENSE for details.
  9. """
  10. import re
  11. from pygments.lexer import RegexLexer, include, bygroups, default, words, \
  12. combined
  13. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  14. Number, Punctuation, Whitespace
  15. __all__ = ["GDScriptLexer"]
  16. class GDScriptLexer(RegexLexer):
  17. """
  18. For GDScript source code.
  19. """
  20. name = "GDScript"
  21. url = 'https://www.godotengine.org'
  22. aliases = ["gdscript", "gd"]
  23. filenames = ["*.gd"]
  24. mimetypes = ["text/x-gdscript", "application/x-gdscript"]
  25. def innerstring_rules(ttype):
  26. return [
  27. # the old style '%s' % (...) string formatting
  28. (r"%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?"
  29. "[hlL]?[E-GXc-giorsux%]",
  30. String.Interpol),
  31. # backslashes, quotes and formatting signs must be parsed one at a time
  32. (r'[^\\\'"%\n]+', ttype),
  33. (r'[\'"\\]', ttype),
  34. # unhandled string formatting sign
  35. (r"%", ttype),
  36. # newlines are an error (use "nl" state)
  37. ]
  38. tokens = {
  39. "root": [
  40. (r"\n", Whitespace),
  41. (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")',
  42. bygroups(Whitespace, String.Affix, String.Doc)),
  43. (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')",
  44. bygroups(Whitespace, String.Affix, String.Doc)),
  45. (r"[^\S\n]+", Whitespace),
  46. (r"#.*$", Comment.Single),
  47. (r"[]{}:(),;[]", Punctuation),
  48. (r"(\\)(\n)", bygroups(Text, Whitespace)),
  49. (r"\\", Text),
  50. (r"(in|and|or|not)\b", Operator.Word),
  51. (r"!=|==|<<|>>|&&|\+=|-=|\*=|/=|%=|&=|\|=|\|\||[-~+/*%=<>&^.!|$]",
  52. Operator),
  53. include("keywords"),
  54. (r"(func)(\s+)", bygroups(Keyword, Whitespace), "funcname"),
  55. (r"(class)(\s+)", bygroups(Keyword, Whitespace), "classname"),
  56. include("builtins"),
  57. ('([rR]|[uUbB][rR]|[rR][uUbB])(""")',
  58. bygroups(String.Affix, String.Double),
  59. "tdqs"),
  60. ("([rR]|[uUbB][rR]|[rR][uUbB])(''')",
  61. bygroups(String.Affix, String.Single),
  62. "tsqs"),
  63. ('([rR]|[uUbB][rR]|[rR][uUbB])(")',
  64. bygroups(String.Affix, String.Double),
  65. "dqs"),
  66. ("([rR]|[uUbB][rR]|[rR][uUbB])(')",
  67. bygroups(String.Affix, String.Single),
  68. "sqs"),
  69. ('([uUbB]?)(""")',
  70. bygroups(String.Affix, String.Double),
  71. combined("stringescape", "tdqs")),
  72. ("([uUbB]?)(''')",
  73. bygroups(String.Affix, String.Single),
  74. combined("stringescape", "tsqs")),
  75. ('([uUbB]?)(")',
  76. bygroups(String.Affix, String.Double),
  77. combined("stringescape", "dqs")),
  78. ("([uUbB]?)(')",
  79. bygroups(String.Affix, String.Single),
  80. combined("stringescape", "sqs")),
  81. include("name"),
  82. include("numbers"),
  83. ],
  84. "keywords": [
  85. (words(("and", "in", "not", "or", "as", "breakpoint", "class",
  86. "class_name", "extends", "is", "func", "setget", "signal",
  87. "tool", "const", "enum", "export", "onready", "static",
  88. "var", "break", "continue", "if", "elif", "else", "for",
  89. "pass", "return", "match", "while", "remote", "master",
  90. "puppet", "remotesync", "mastersync", "puppetsync"),
  91. suffix=r"\b"), Keyword),
  92. ],
  93. "builtins": [
  94. (words(("Color8", "ColorN", "abs", "acos", "asin", "assert", "atan",
  95. "atan2", "bytes2var", "ceil", "char", "clamp", "convert",
  96. "cos", "cosh", "db2linear", "decimals", "dectime", "deg2rad",
  97. "dict2inst", "ease", "exp", "floor", "fmod", "fposmod",
  98. "funcref", "hash", "inst2dict", "instance_from_id", "is_inf",
  99. "is_nan", "lerp", "linear2db", "load", "log", "max", "min",
  100. "nearest_po2", "pow", "preload", "print", "print_stack",
  101. "printerr", "printraw", "prints", "printt", "rad2deg",
  102. "rand_range", "rand_seed", "randf", "randi", "randomize",
  103. "range", "round", "seed", "sign", "sin", "sinh", "sqrt",
  104. "stepify", "str", "str2var", "tan", "tan", "tanh",
  105. "type_exist", "typeof", "var2bytes", "var2str", "weakref",
  106. "yield"), prefix=r"(?<!\.)", suffix=r"\b"),
  107. Name.Builtin),
  108. (r"((?<!\.)(self|false|true)|(PI|TAU|NAN|INF)" r")\b",
  109. Name.Builtin.Pseudo),
  110. (words(("bool", "int", "float", "String", "NodePath", "Vector2",
  111. "Rect2", "Transform2D", "Vector3", "Rect3", "Plane", "Quat",
  112. "Basis", "Transform", "Color", "RID", "Object", "NodePath",
  113. "Dictionary", "Array", "PackedByteArray", "PackedInt32Array",
  114. "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array",
  115. "PackedStringArray", "PackedVector2Array", "PackedVector3Array",
  116. "PackedColorArray", "null", "void"),
  117. prefix=r"(?<!\.)", suffix=r"\b"),
  118. Name.Builtin.Type),
  119. ],
  120. "numbers": [
  121. (r"(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?", Number.Float),
  122. (r"\d+[eE][+-]?[0-9]+j?", Number.Float),
  123. (r"0[xX][a-fA-F0-9]+", Number.Hex),
  124. (r"\d+j?", Number.Integer),
  125. ],
  126. "name": [(r"[a-zA-Z_]\w*", Name)],
  127. "funcname": [(r"[a-zA-Z_]\w*", Name.Function, "#pop"), default("#pop")],
  128. "classname": [(r"[a-zA-Z_]\w*", Name.Class, "#pop")],
  129. "stringescape": [
  130. (
  131. r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|'
  132. r"U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})",
  133. String.Escape,
  134. )
  135. ],
  136. "strings-single": innerstring_rules(String.Single),
  137. "strings-double": innerstring_rules(String.Double),
  138. "dqs": [
  139. (r'"', String.Double, "#pop"),
  140. (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings
  141. include("strings-double"),
  142. ],
  143. "sqs": [
  144. (r"'", String.Single, "#pop"),
  145. (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings
  146. include("strings-single"),
  147. ],
  148. "tdqs": [
  149. (r'"""', String.Double, "#pop"),
  150. include("strings-double"),
  151. (r"\n", Whitespace),
  152. ],
  153. "tsqs": [
  154. (r"'''", String.Single, "#pop"),
  155. include("strings-single"),
  156. (r"\n", Whitespace),
  157. ],
  158. }
  159. def analyse_text(text):
  160. score = 0.0
  161. if re.search(
  162. r"func (_ready|_init|_input|_process|_unhandled_input)", text
  163. ):
  164. score += 0.8
  165. if re.search(
  166. r"(extends |class_name |onready |preload|load|setget|func [^_])",
  167. text
  168. ):
  169. score += 0.4
  170. if re.search(r"(var|const|enum|export|signal|tool)", text):
  171. score += 0.2
  172. return min(score, 1.0)