sdkconfig.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # Copyright 2021 Espressif Systems (Shanghai) CO LTD
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import kconfiglib
  17. from pyparsing import (Combine, Group, Literal, Optional, Word, alphanums, hexnums, infixNotation, nums, oneOf,
  18. opAssoc, printables, quotedString, removeQuotes)
  19. class SDKConfig:
  20. """
  21. Encapsulates an sdkconfig file. Defines grammar of a configuration entry, and enables
  22. evaluation of logical expressions involving those entries.
  23. """
  24. # A configuration entry is in the form CONFIG=VALUE. Definitions of components of that grammar
  25. IDENTIFIER = Word(alphanums.upper() + '_')
  26. HEX = Combine('0x' + Word(hexnums)).setParseAction(lambda t:int(t[0], 16))
  27. DECIMAL = Combine(Optional(Literal('+') | Literal('-')) + Word(nums)).setParseAction(lambda t:int(t[0]))
  28. LITERAL = Word(printables.replace(':', ''))
  29. QUOTED_LITERAL = quotedString.setParseAction(removeQuotes)
  30. VALUE = HEX | DECIMAL | LITERAL | QUOTED_LITERAL
  31. # Operators supported by the expression evaluation
  32. OPERATOR = oneOf(['=', '!=', '>', '<', '<=', '>='])
  33. def __init__(self, kconfig_file, sdkconfig_file):
  34. self.config = kconfiglib.Kconfig(kconfig_file)
  35. self.config.load_config(sdkconfig_file)
  36. def evaluate_expression(self, expression):
  37. result = self.config.eval_string(expression)
  38. if result == 0: # n
  39. return False
  40. elif result == 2: # y
  41. return True
  42. else: # m
  43. raise Exception('unsupported config expression result')
  44. @staticmethod
  45. def get_expression_grammar():
  46. identifier = SDKConfig.IDENTIFIER.setResultsName('identifier')
  47. operator = SDKConfig.OPERATOR.setResultsName('operator')
  48. value = SDKConfig.VALUE.setResultsName('value')
  49. test_binary = identifier + operator + value
  50. test_single = identifier
  51. test = test_binary | test_single
  52. condition = Group(Optional('(').suppress() + test + Optional(')').suppress())
  53. grammar = infixNotation(condition, [
  54. ('!', 1, opAssoc.RIGHT),
  55. ('&&', 2, opAssoc.LEFT),
  56. ('||', 2, opAssoc.LEFT)])
  57. return grammar