optinterpreter.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # Copyright 2013-2014 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import re
  12. import functools
  13. import typing as T
  14. from . import mparser
  15. from . import coredata
  16. from . import mesonlib
  17. from . import compilers
  18. forbidden_option_names = set(coredata.builtin_options.keys())
  19. forbidden_prefixes = [lang + '_' for lang in compilers.all_languages] + ['b_', 'backend_']
  20. reserved_prefixes = ['cross_']
  21. def is_invalid_name(name: str, *, log: bool = True) -> bool:
  22. if name in forbidden_option_names:
  23. return True
  24. pref = name.split('_')[0] + '_'
  25. if pref in forbidden_prefixes:
  26. return True
  27. if pref in reserved_prefixes:
  28. if log:
  29. from . import mlog
  30. mlog.deprecation('Option uses prefix "%s", which is reserved for Meson. This will become an error in the future.' % pref)
  31. return False
  32. class OptionException(mesonlib.MesonException):
  33. pass
  34. def permitted_kwargs(permitted):
  35. """Function that validates kwargs for options."""
  36. def _wraps(func):
  37. @functools.wraps(func)
  38. def _inner(name, description, kwargs):
  39. bad = [a for a in kwargs.keys() if a not in permitted]
  40. if bad:
  41. raise OptionException('Invalid kwargs for option "{}": "{}"'.format(
  42. name, ' '.join(bad)))
  43. return func(description, kwargs)
  44. return _inner
  45. return _wraps
  46. optname_regex = re.compile('[^a-zA-Z0-9_-]')
  47. @permitted_kwargs({'value', 'yield'})
  48. def StringParser(description, kwargs):
  49. return coredata.UserStringOption(description,
  50. kwargs.get('value', ''),
  51. kwargs.get('choices', []),
  52. kwargs.get('yield', coredata.default_yielding))
  53. @permitted_kwargs({'value', 'yield'})
  54. def BooleanParser(description, kwargs):
  55. return coredata.UserBooleanOption(description,
  56. kwargs.get('value', True),
  57. kwargs.get('yield', coredata.default_yielding))
  58. @permitted_kwargs({'value', 'yield', 'choices'})
  59. def ComboParser(description, kwargs):
  60. if 'choices' not in kwargs:
  61. raise OptionException('Combo option missing "choices" keyword.')
  62. choices = kwargs['choices']
  63. if not isinstance(choices, list):
  64. raise OptionException('Combo choices must be an array.')
  65. for i in choices:
  66. if not isinstance(i, str):
  67. raise OptionException('Combo choice elements must be strings.')
  68. return coredata.UserComboOption(description,
  69. choices,
  70. kwargs.get('value', choices[0]),
  71. kwargs.get('yield', coredata.default_yielding),)
  72. @permitted_kwargs({'value', 'min', 'max', 'yield'})
  73. def IntegerParser(description, kwargs):
  74. if 'value' not in kwargs:
  75. raise OptionException('Integer option must contain value argument.')
  76. inttuple = (kwargs.get('min', None), kwargs.get('max', None), kwargs['value'])
  77. return coredata.UserIntegerOption(description,
  78. inttuple,
  79. kwargs.get('yield', coredata.default_yielding))
  80. # FIXME: Cannot use FeatureNew while parsing options because we parse it before
  81. # reading options in project(). See func_project() in interpreter.py
  82. #@FeatureNew('array type option()', '0.44.0')
  83. @permitted_kwargs({'value', 'yield', 'choices'})
  84. def string_array_parser(description, kwargs):
  85. if 'choices' in kwargs:
  86. choices = kwargs['choices']
  87. if not isinstance(choices, list):
  88. raise OptionException('Array choices must be an array.')
  89. for i in choices:
  90. if not isinstance(i, str):
  91. raise OptionException('Array choice elements must be strings.')
  92. value = kwargs.get('value', choices)
  93. else:
  94. choices = None
  95. value = kwargs.get('value', [])
  96. if not isinstance(value, list):
  97. raise OptionException('Array choices must be passed as an array.')
  98. return coredata.UserArrayOption(description,
  99. value,
  100. choices=choices,
  101. yielding=kwargs.get('yield', coredata.default_yielding))
  102. @permitted_kwargs({'value', 'yield'})
  103. def FeatureParser(description, kwargs):
  104. return coredata.UserFeatureOption(description,
  105. kwargs.get('value', 'auto'),
  106. yielding=kwargs.get('yield', coredata.default_yielding))
  107. option_types = {'string': StringParser,
  108. 'boolean': BooleanParser,
  109. 'combo': ComboParser,
  110. 'integer': IntegerParser,
  111. 'array': string_array_parser,
  112. 'feature': FeatureParser,
  113. } # type: T.Dict[str, T.Callable[[str, T.Dict], coredata.UserOption]]
  114. class OptionInterpreter:
  115. def __init__(self, subproject):
  116. self.options = {}
  117. self.subproject = subproject
  118. def process(self, option_file):
  119. try:
  120. with open(option_file, 'r', encoding='utf8') as f:
  121. ast = mparser.Parser(f.read(), option_file).parse()
  122. except mesonlib.MesonException as me:
  123. me.file = option_file
  124. raise me
  125. if not isinstance(ast, mparser.CodeBlockNode):
  126. e = OptionException('Option file is malformed.')
  127. e.lineno = ast.lineno()
  128. e.file = option_file
  129. raise e
  130. for cur in ast.lines:
  131. try:
  132. self.evaluate_statement(cur)
  133. except Exception as e:
  134. e.lineno = cur.lineno
  135. e.colno = cur.colno
  136. e.file = option_file
  137. raise e
  138. def reduce_single(self, arg):
  139. if isinstance(arg, str):
  140. return arg
  141. elif isinstance(arg, (mparser.StringNode, mparser.BooleanNode,
  142. mparser.NumberNode)):
  143. return arg.value
  144. elif isinstance(arg, mparser.ArrayNode):
  145. return [self.reduce_single(curarg) for curarg in arg.args.arguments]
  146. elif isinstance(arg, mparser.UMinusNode):
  147. res = self.reduce_single(arg.value)
  148. if not isinstance(res, (int, float)):
  149. raise OptionException('Token after "-" is not a number')
  150. return -res
  151. elif isinstance(arg, mparser.NotNode):
  152. res = self.reduce_single(arg.value)
  153. if not isinstance(res, bool):
  154. raise OptionException('Token after "not" is not a a boolean')
  155. return not res
  156. else:
  157. raise OptionException('Arguments may only be string, int, bool, or array of those.')
  158. def reduce_arguments(self, args):
  159. assert(isinstance(args, mparser.ArgumentNode))
  160. if args.incorrect_order():
  161. raise OptionException('All keyword arguments must be after positional arguments.')
  162. reduced_pos = [self.reduce_single(arg) for arg in args.arguments]
  163. reduced_kw = {}
  164. for key in args.kwargs.keys():
  165. if not isinstance(key, mparser.IdNode):
  166. raise OptionException('Keyword argument name is not a string.')
  167. a = args.kwargs[key]
  168. reduced_kw[key.value] = self.reduce_single(a)
  169. return reduced_pos, reduced_kw
  170. def evaluate_statement(self, node):
  171. if not isinstance(node, mparser.FunctionNode):
  172. raise OptionException('Option file may only contain option definitions')
  173. func_name = node.func_name
  174. if func_name != 'option':
  175. raise OptionException('Only calls to option() are allowed in option files.')
  176. (posargs, kwargs) = self.reduce_arguments(node.args)
  177. # FIXME: Cannot use FeatureNew while parsing options because we parse
  178. # it before reading options in project(). See func_project() in
  179. # interpreter.py
  180. #if 'yield' in kwargs:
  181. # FeatureNew('option yield', '0.45.0').use(self.subproject)
  182. if 'type' not in kwargs:
  183. raise OptionException('Option call missing mandatory "type" keyword argument')
  184. opt_type = kwargs.pop('type')
  185. if opt_type not in option_types:
  186. raise OptionException('Unknown type %s.' % opt_type)
  187. if len(posargs) != 1:
  188. raise OptionException('Option() must have one (and only one) positional argument')
  189. opt_name = posargs[0]
  190. if not isinstance(opt_name, str):
  191. raise OptionException('Positional argument must be a string.')
  192. if optname_regex.search(opt_name) is not None:
  193. raise OptionException('Option names can only contain letters, numbers or dashes.')
  194. if is_invalid_name(opt_name):
  195. raise OptionException('Option name %s is reserved.' % opt_name)
  196. if self.subproject != '':
  197. opt_name = self.subproject + ':' + opt_name
  198. opt = option_types[opt_type](opt_name, kwargs.pop('description', ''), kwargs)
  199. if opt.description == '':
  200. opt.description = opt_name
  201. self.options[opt_name] = opt