Debian Codegraph @

mesonbuild/machinefile.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2024 Contributors to the The Meson project
3 # Copyright © 2024 Intel Corporation
4
5 from __future__ import annotations
6 import typing as T
7 import configparser
8 import os
9
10 from . import mparser
11
12 from .cmdline import CmdLineFileParser
13 from .mesonlib import MesonException
14
15 if T.TYPE_CHECKING:
16 from .options import ElementaryOptionValues
17
18
19 HOMEDIR = os.path.expanduser('~')
20
21
22 class MachineFileParser():
23 def __init__(self, filenames: T.List[str], sourcedir: str) -> None:
24 self.parser = CmdLineFileParser()
25 self.constants: T.Dict[str, ElementaryOptionValues] = {'True': True, 'False': False, '~': HOMEDIR}
26 self.sections: T.Dict[str, T.Dict[str, ElementaryOptionValues]] = {}
27
28 for fname in filenames:
29 try:
30 with open(fname, encoding='utf-8') as f:
31 content = f.read()
32 except UnicodeDecodeError as e:
33 raise MesonException(f'Malformed machine file {fname!r} failed to parse as unicode: {e}')
34
35 content = content.replace('@GLOBAL_SOURCE_ROOT@', sourcedir)
36 content = content.replace('@DIRNAME@', os.path.dirname(fname))
37 try:
38 self.parser.read_string(content, fname)
39 except configparser.Error as e:
40 raise MesonException(f'Malformed machine file: {e}')
41
42 # Parse [constants] first so they can be used in other sections
43 if self.parser.has_section('constants'):
44 self.constants.update(self._parse_section('constants'))
45
46 for s in self.parser.sections():
47 if s == 'constants':
48 continue
49 self.sections[s] = self._parse_section(s)
50
51 def _parse_section(self, s: str) -> T.Dict[str, ElementaryOptionValues]:
52 self.scope = self.constants.copy()
53 section: T.Dict[str, ElementaryOptionValues] = {}
54 for entry, value in self.parser.items(s):
55 if ' ' in entry or '\t' in entry or "'" in entry or '"' in entry:
56 raise MesonException(f'Malformed variable name {entry!r} in machine file.')
57 # Windows paths...
58 value = value.replace('\\', '\\\\')
59 try:
60 ast = mparser.Parser(value, 'machinefile', machinefile=True).parse()
61 if not ast.lines:
62 raise MesonException('value cannot be empty')
63 res = self._evaluate_statement(ast.lines[0])
64 except MesonException as e:
65 raise MesonException(f'Malformed value in machine file variable {entry!r}: {str(e)}.')
66 except KeyError as e:
67 raise MesonException(f'Undefined constant {e.args[0]!r} in machine file variable {entry!r}.')
68 section[entry] = res
69 self.scope[entry] = res
70 return section
71
72 def _evaluate_statement(self, node: mparser.BaseNode) -> ElementaryOptionValues:
73 if isinstance(node, (mparser.StringNode)):
74 return node.value
75 elif isinstance(node, mparser.BooleanNode):
76 return node.value
77 elif isinstance(node, mparser.NumberNode):
78 return node.value
79 elif isinstance(node, mparser.ParenthesizedNode):
80 return self._evaluate_statement(node.inner)
81 elif isinstance(node, mparser.ArrayNode):
82 a = [self._evaluate_statement(arg) for arg in node.args.arguments]
83 assert all(isinstance(s, str) for s in a), 'for mypy'
84 return T.cast('T.List[str]', a)
85 elif isinstance(node, mparser.IdNode):
86 return self.scope[node.value]
87 elif isinstance(node, mparser.ArithmeticNode):
88 l = self._evaluate_statement(node.left)
89 r = self._evaluate_statement(node.right)
90 if node.operation == '+':
91 if isinstance(l, str) and isinstance(r, str):
92 return l + r
93 if isinstance(l, list) and isinstance(r, list):
94 return l + r
95 elif node.operation == '/':
96 if isinstance(l, str) and isinstance(r, str):
97 return os.path.join(l, r)
98 raise MesonException('Unsupported node type')
99
100 def parse_machine_files(filenames: T.List[str], sourcedir: str) -> T.Dict[str, T.Dict[str, ElementaryOptionValues]]:
101 parser = MachineFileParser(filenames, sourcedir)
102 return parser.sections
103
104
105 class MachineFileStore:
106 def __init__(self, native_files: T.Optional[T.List[str]], cross_files: T.Optional[T.List[str]], source_dir: str):
107 self.native = parse_machine_files(native_files if native_files is not None else [], source_dir)
108 self.cross = parse_machine_files(cross_files if cross_files is not None else [], source_dir)